Annotation of loncom/interface/loncommon.pm, revision 1.1213

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1213  ! raeburn     4: # $Id: loncommon.pm,v 1.1212 2015/04/06 19:05:27 raeburn Exp $
1.10      albertel    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.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.687     raeburn    75: use DateTime::Locale::Catalog;
1.1091    foxr       76: use Text::Aspell;
1.1094    raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1174    raeburn    79: use Crypt::DES;
                     80: use DynaLoader; # for Crypt::DES version
1.117     www        81: 
1.517     raeburn    82: # ---------------------------------------------- Designs
                     83: use vars qw(%defaultdesign);
                     84: 
1.22      www        85: my $readit;
                     86: 
1.517     raeburn    87: 
1.157     matthew    88: ##
                     89: ## Global Variables
                     90: ##
1.46      matthew    91: 
1.643     foxr       92: 
                     93: # ----------------------------------------------- SSI with retries:
                     94: #
                     95: 
                     96: =pod
                     97: 
1.648     raeburn    98: =head1 Server Side include with retries:
1.643     foxr       99: 
                    100: =over 4
                    101: 
1.648     raeburn   102: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      103: 
                    104: Performs an ssi with some number of retries.  Retries continue either
                    105: until the result is ok or until the retry count supplied by the
                    106: caller is exhausted.  
                    107: 
                    108: Inputs:
1.648     raeburn   109: 
                    110: =over 4
                    111: 
1.643     foxr      112: resource   - Identifies the resource to insert.
1.648     raeburn   113: 
1.643     foxr      114: retries    - Count of the number of retries allowed.
1.648     raeburn   115: 
1.643     foxr      116: form       - Hash that identifies the rendering options.
                    117: 
1.648     raeburn   118: =back
                    119: 
                    120: Returns:
                    121: 
                    122: =over 4
                    123: 
1.643     foxr      124: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   125: 
1.643     foxr      126: response   - The response from the last attempt (which may or may not have been successful.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: =back
                    131: 
1.643     foxr      132: =cut
                    133: 
                    134: sub ssi_with_retries {
                    135:     my ($resource, $retries, %form) = @_;
                    136: 
                    137: 
                    138:     my $ok = 0;			# True if we got a good response.
                    139:     my $content;
                    140:     my $response;
                    141: 
                    142:     # Try to get the ssi done. within the retries count:
                    143: 
                    144:     do {
                    145: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    146: 	$ok      = $response->is_success;
1.650     www       147:         if (!$ok) {
                    148:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    149:         }
1.643     foxr      150: 	$retries--;
                    151:     } while (!$ok && ($retries > 0));
                    152: 
                    153:     if (!$ok) {
                    154: 	$content = '';		# On error return an empty content.
                    155:     }
                    156:     return ($content, $response);
                    157: 
                    158: }
                    159: 
                    160: 
                    161: 
1.20      www       162: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  163: my %language;
1.124     www       164: my %supported_language;
1.1088    foxr      165: my %supported_codes;
1.1048    foxr      166: my %latex_language;		# For choosing hyphenation in <transl..>
                    167: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  168: my %cprtag;
1.192     taceyjo1  169: my %scprtag;
1.351     www       170: my %fe; my %fd; my %fm;
1.41      ng        171: my %category_extensions;
1.12      harris41  172: 
1.46      matthew   173: # ---------------------------------------------- Thesaurus variables
1.144     matthew   174: #
                    175: # %Keywords:
                    176: #      A hash used by &keyword to determine if a word is considered a keyword.
                    177: # $thesaurus_db_file 
                    178: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   179: 
                    180: my %Keywords;
                    181: my $thesaurus_db_file;
                    182: 
1.144     matthew   183: #
                    184: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    185: # thesaurus.tab, and filecategories.tab.
                    186: #
1.18      www       187: BEGIN {
1.46      matthew   188:     # Variable initialization
                    189:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    190:     #
1.22      www       191:     unless ($readit) {
1.12      harris41  192: # ------------------------------------------------------------------- languages
                    193:     {
1.158     raeburn   194:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    195:                                    '/language.tab';
                    196:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  197:             while (my $line = <$fh>) {
                    198:                 next if ($line=~/^\#/);
                    199:                 chomp($line);
1.1088    foxr      200:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   201:                 $language{$key}=$val.' - '.$enc;
                    202:                 if ($sup) {
                    203:                     $supported_language{$key}=$sup;
1.1088    foxr      204: 		    $supported_codes{$key}   = $code;
1.158     raeburn   205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      208: 		    $latex_language{$code} = $latex;
1.1048    foxr      209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   265:                 push @{$category_extensions{lc($category)}},$extension;
                    266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1116    raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    538:         $credits_element) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:         }
1.293     raeburn   590:         if (multflag !=null && multflag != '') {
                    591:             url += '&multiple='+multflag;
                    592:         }
1.909     raeburn   593:         var title = '$wintitle';
1.91      www       594:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    595:         options += ',width=700,height=600';
                    596:         stdeditbrowser = open(url,title,options,'1');
                    597:         stdeditbrowser.focus();
                    598:     }
1.876     raeburn   599: $id_functions
                    600: ENDSTDBRW
1.1116    raeburn   601:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    602:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    603:                                       $credits_element);
1.876     raeburn   604:     }
                    605:     $output .= '
                    606: // ]]>
                    607: </script>';
                    608:     return $output;
                    609: }
                    610: 
                    611: sub javascript_index_functions {
                    612:     return <<"ENDJS";
                    613: 
                    614: function getFormIdByName(formname) {
                    615:     for (var i=0;i<document.forms.length;i++) {
                    616:         if (document.forms[i].name == formname) {
                    617:             return i;
                    618:         }
                    619:     }
                    620:     return -1;
                    621: }
                    622: 
                    623: function getIndexByName(formid,item) {
                    624:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    625:         if (document.forms[formid].elements[i].name == item) {
                    626:             return i;
                    627:         }
                    628:     }
                    629:     return -1;
                    630: }
1.468     raeburn   631: 
1.876     raeburn   632: function getDomainFromSelectbox(formname,udom) {
                    633:     var userdom;
                    634:     var formid = getFormIdByName(formname);
                    635:     if (formid > -1) {
                    636:         var domid = getIndexByName(formid,udom);
                    637:         if (domid > -1) {
                    638:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    639:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    640:             }
                    641:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    642:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   643:             }
                    644:         }
                    645:     }
1.876     raeburn   646:     return userdom;
                    647: }
                    648: 
                    649: ENDJS
1.468     raeburn   650: 
1.876     raeburn   651: }
                    652: 
1.1017    raeburn   653: sub javascript_array_indexof {
1.1018    raeburn   654:     return <<ENDJS;
1.1017    raeburn   655: <script type="text/javascript" language="JavaScript">
                    656: // <![CDATA[
                    657: 
                    658: if (!Array.prototype.indexOf) {
                    659:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    660:         "use strict";
                    661:         if (this === void 0 || this === null) {
                    662:             throw new TypeError();
                    663:         }
                    664:         var t = Object(this);
                    665:         var len = t.length >>> 0;
                    666:         if (len === 0) {
                    667:             return -1;
                    668:         }
                    669:         var n = 0;
                    670:         if (arguments.length > 0) {
                    671:             n = Number(arguments[1]);
1.1088    foxr      672:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   673:                 n = 0;
                    674:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    675:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    676:             }
                    677:         }
                    678:         if (n >= len) {
                    679:             return -1;
                    680:         }
                    681:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    682:         for (; k < len; k++) {
                    683:             if (k in t && t[k] === searchElement) {
                    684:                 return k;
                    685:             }
                    686:         }
                    687:         return -1;
                    688:     }
                    689: }
                    690: 
                    691: // ]]>
                    692: </script>
                    693: 
                    694: ENDJS
                    695: 
                    696: }
                    697: 
1.876     raeburn   698: sub userbrowser_javascript {
                    699:     my $id_functions = &javascript_index_functions();
                    700:     return <<"ENDUSERBRW";
                    701: 
1.888     raeburn   702: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   703:     var url = '/adm/pickuser?';
                    704:     var userdom = getDomainFromSelectbox(formname,udom);
                    705:     if (userdom != null) {
                    706:        if (userdom != '') {
                    707:            url += 'srchdom='+userdom+'&';
                    708:        }
                    709:     }
                    710:     url += 'form=' + formname + '&unameelement='+uname+
                    711:                                 '&udomelement='+udom+
                    712:                                 '&ulastelement='+ulast+
                    713:                                 '&ufirstelement='+ufirst+
                    714:                                 '&uemailelement='+uemail+
1.881     raeburn   715:                                 '&hideudomelement='+hideudom+
                    716:                                 '&coursedom='+crsdom;
1.888     raeburn   717:     if ((caller != null) && (caller != undefined)) {
                    718:         url += '&caller='+caller;
                    719:     }
1.876     raeburn   720:     var title = 'User_Browser';
                    721:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    722:     options += ',width=700,height=600';
                    723:     var stdeditbrowser = open(url,title,options,'1');
                    724:     stdeditbrowser.focus();
                    725: }
                    726: 
1.888     raeburn   727: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   728:     var formid = getFormIdByName(formname);
                    729:     if (formid > -1) {
1.888     raeburn   730:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   731:         var domid = getIndexByName(formid,udom);
                    732:         var hidedomid = getIndexByName(formid,origdom);
                    733:         if (hidedomid > -1) {
                    734:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   735:             var unameval = document.forms[formid].elements[unameid].value;
                    736:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    737:                 if (domid > -1) {
                    738:                     var slct = document.forms[formid].elements[domid];
                    739:                     if (slct.type == 'select-one') {
                    740:                         var i;
                    741:                         for (i=0;i<slct.length;i++) {
                    742:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    743:                         }
                    744:                     }
                    745:                     if (slct.type == 'hidden') {
                    746:                         slct.value = fixeddom;
1.876     raeburn   747:                     }
                    748:                 }
1.468     raeburn   749:             }
                    750:         }
                    751:     }
1.876     raeburn   752:     return;
                    753: }
                    754: 
                    755: $id_functions
                    756: ENDUSERBRW
1.468     raeburn   757: }
                    758: 
                    759: sub setsec_javascript {
1.1116    raeburn   760:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   761:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    762:         $communityrolestr);
                    763:     if ($role_element ne '') {
                    764:         my @allroles = ('st','ta','ep','in','ad');
                    765:         foreach my $crstype ('Course','Community') {
                    766:             if ($crstype eq 'Community') {
                    767:                 foreach my $role (@allroles) {
                    768:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    769:                 }
                    770:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    771:             } else {
                    772:                 foreach my $role (@allroles) {
                    773:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    774:                 }
                    775:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    776:             }
                    777:         }
                    778:         $rolestr = '"'.join('","',@allroles).'"';
                    779:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    780:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    781:     }
1.468     raeburn   782:     my $setsections = qq|
                    783: function setSect(sectionlist) {
1.629     raeburn   784:     var sectionsArray = new Array();
                    785:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    786:         sectionsArray = sectionlist.split(",");
                    787:     }
1.468     raeburn   788:     var numSections = sectionsArray.length;
                    789:     document.$formname.$sec_element.length = 0;
                    790:     if (numSections == 0) {
                    791:         document.$formname.$sec_element.multiple=false;
                    792:         document.$formname.$sec_element.size=1;
                    793:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    794:     } else {
                    795:         if (numSections == 1) {
                    796:             document.$formname.$sec_element.multiple=false;
                    797:             document.$formname.$sec_element.size=1;
                    798:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    799:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    800:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    801:         } else {
                    802:             for (var i=0; i<numSections; i++) {
                    803:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    804:             }
                    805:             document.$formname.$sec_element.multiple=true
                    806:             if (numSections < 3) {
                    807:                 document.$formname.$sec_element.size=numSections;
                    808:             } else {
                    809:                 document.$formname.$sec_element.size=3;
                    810:             }
                    811:             document.$formname.$sec_element.options[0].selected = false
                    812:         }
                    813:     }
1.91      www       814: }
1.905     raeburn   815: 
                    816: function setRole(crstype) {
1.468     raeburn   817: |;
1.905     raeburn   818:     if ($role_element eq '') {
                    819:         $setsections .= '    return;
                    820: }
                    821: ';
                    822:     } else {
                    823:         $setsections .= qq|
                    824:     var elementLength = document.$formname.$role_element.length;
                    825:     var allroles = Array($rolestr);
                    826:     var courserolenames = Array($courserolestr);
                    827:     var communityrolenames = Array($communityrolestr);
                    828:     if (elementLength != undefined) {
                    829:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    830:             if (crstype == 'Course') {
                    831:                 return;
                    832:             } else {
                    833:                 allroles[5] = 'co';
                    834:                 for (var i=0; i<6; i++) {
                    835:                     document.$formname.$role_element.options[i].value = allroles[i];
                    836:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    837:                 }
                    838:             }
                    839:         } else {
                    840:             if (crstype == 'Community') {
                    841:                 return;
                    842:             } else {
                    843:                 allroles[5] = 'cc';
                    844:                 for (var i=0; i<6; i++) {
                    845:                     document.$formname.$role_element.options[i].value = allroles[i];
                    846:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    847:                 }
                    848:             }
                    849:         }
                    850:     }
                    851:     return;
                    852: }
                    853: |;
                    854:     }
1.1116    raeburn   855:     if ($credits_element) {
                    856:         $setsections .= qq|
                    857: function setCredits(defaultcredits) {
                    858:     document.$formname.$credits_element.value = defaultcredits;
                    859:     return;
                    860: }
                    861: |;
                    862:     }
1.468     raeburn   863:     return $setsections;
                    864: }
                    865: 
1.91      www       866: sub selectcourse_link {
1.909     raeburn   867:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    868:        $typeelement) = @_;
                    869:    my $type = $selecttype;
1.871     raeburn   870:    my $linktext = &mt('Select Course');
                    871:    if ($selecttype eq 'Community') {
1.909     raeburn   872:        $linktext = &mt('Select Community');
1.906     raeburn   873:    } elsif ($selecttype eq 'Course/Community') {
                    874:        $linktext = &mt('Select Course/Community');
1.909     raeburn   875:        $type = '';
1.1019    raeburn   876:    } elsif ($selecttype eq 'Select') {
                    877:        $linktext = &mt('Select');
                    878:        $type = '';
1.871     raeburn   879:    }
1.787     bisitz    880:    return '<span class="LC_nobreak">'
                    881:          ."<a href='"
                    882:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    883:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   884:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   885:          ."'>".$linktext.'</a>'
1.787     bisitz    886:          .'</span>';
1.74      www       887: }
1.42      matthew   888: 
1.653     raeburn   889: sub selectauthor_link {
                    890:    my ($form,$udom)=@_;
                    891:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    892:           &mt('Select Author').'</a>';
                    893: }
                    894: 
1.876     raeburn   895: sub selectuser_link {
1.881     raeburn   896:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   897:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   898:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   899:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   900:            ');">'.$linktext.'</a>';
1.876     raeburn   901: }
                    902: 
1.273     raeburn   903: sub check_uncheck_jscript {
                    904:     my $jscript = <<"ENDSCRT";
                    905: function checkAll(field) {
                    906:     if (field.length > 0) {
                    907:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   908:             if (!field[i].disabled) { 
                    909:                 field[i].checked = true;
                    910:             }
1.273     raeburn   911:         }
                    912:     } else {
1.1093    raeburn   913:         if (!field.disabled) { 
                    914:             field.checked = true;
                    915:         }
1.273     raeburn   916:     }
                    917: }
                    918:  
                    919: function uncheckAll(field) {
                    920:     if (field.length > 0) {
                    921:         for (i = 0; i < field.length; i++) {
                    922:             field[i].checked = false ;
1.543     albertel  923:         }
                    924:     } else {
1.273     raeburn   925:         field.checked = false ;
                    926:     }
                    927: }
                    928: ENDSCRT
                    929:     return $jscript;
                    930: }
                    931: 
1.656     www       932: sub select_timezone {
1.659     raeburn   933:    my ($name,$selected,$onchange,$includeempty)=@_;
                    934:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    935:    if ($includeempty) {
                    936:        $output .= '<option value=""';
                    937:        if (($selected eq '') || ($selected eq 'local')) {
                    938:            $output .= ' selected="selected" ';
                    939:        }
                    940:        $output .= '> </option>';
                    941:    }
1.657     raeburn   942:    my @timezones = DateTime::TimeZone->all_names;
                    943:    foreach my $tzone (@timezones) {
                    944:        $output.= '<option value="'.$tzone.'"';
                    945:        if ($tzone eq $selected) {
                    946:            $output.=' selected="selected"';
                    947:        }
                    948:        $output.=">$tzone</option>\n";
1.656     www       949:    }
                    950:    $output.="</select>";
                    951:    return $output;
                    952: }
1.273     raeburn   953: 
1.687     raeburn   954: sub select_datelocale {
                    955:     my ($name,$selected,$onchange,$includeempty)=@_;
                    956:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    957:     if ($includeempty) {
                    958:         $output .= '<option value=""';
                    959:         if ($selected eq '') {
                    960:             $output .= ' selected="selected" ';
                    961:         }
                    962:         $output .= '> </option>';
                    963:     }
                    964:     my (@possibles,%locale_names);
                    965:     my @locales = DateTime::Locale::Catalog::Locales;
                    966:     foreach my $locale (@locales) {
                    967:         if (ref($locale) eq 'HASH') {
                    968:             my $id = $locale->{'id'};
                    969:             if ($id ne '') {
                    970:                 my $en_terr = $locale->{'en_territory'};
                    971:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   972:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   973:                 if (grep(/^en$/,@languages) || !@languages) {
                    974:                     if ($en_terr ne '') {
                    975:                         $locale_names{$id} = '('.$en_terr.')';
                    976:                     } elsif ($native_terr ne '') {
                    977:                         $locale_names{$id} = $native_terr;
                    978:                     }
                    979:                 } else {
                    980:                     if ($native_terr ne '') {
                    981:                         $locale_names{$id} = $native_terr.' ';
                    982:                     } elsif ($en_terr ne '') {
                    983:                         $locale_names{$id} = '('.$en_terr.')';
                    984:                     }
                    985:                 }
                    986:                 push (@possibles,$id);
                    987:             }
                    988:         }
                    989:     }
                    990:     foreach my $item (sort(@possibles)) {
                    991:         $output.= '<option value="'.$item.'"';
                    992:         if ($item eq $selected) {
                    993:             $output.=' selected="selected"';
                    994:         }
                    995:         $output.=">$item";
                    996:         if ($locale_names{$item} ne '') {
                    997:             $output.="  $locale_names{$item}</option>\n";
                    998:         }
                    999:         $output.="</option>\n";
                   1000:     }
                   1001:     $output.="</select>";
                   1002:     return $output;
                   1003: }
                   1004: 
1.792     raeburn  1005: sub select_language {
                   1006:     my ($name,$selected,$includeempty) = @_;
                   1007:     my %langchoices;
                   1008:     if ($includeempty) {
1.1117    raeburn  1009:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1010:     }
                   1011:     foreach my $id (&languageids()) {
                   1012:         my $code = &supportedlanguagecode($id);
                   1013:         if ($code) {
                   1014:             $langchoices{$code} = &plainlanguagedescription($id);
                   1015:         }
                   1016:     }
1.1117    raeburn  1017:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1018:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1019: }
                   1020: 
1.42      matthew  1021: =pod
1.36      matthew  1022: 
1.1088    foxr     1023: 
                   1024: =item * &list_languages()
                   1025: 
                   1026: Returns an array reference that is suitable for use in language prompters.
                   1027: Each array element is itself a two element array.  The first element
                   1028: is the language code.  The second element a descsriptiuon of the 
                   1029: language itself.  This is suitable for use in e.g.
                   1030: &Apache::edit::select_arg (once dereferenced that is).
                   1031: 
                   1032: =cut 
                   1033: 
                   1034: sub list_languages {
                   1035:     my @lang_choices;
                   1036: 
                   1037:     foreach my $id (&languageids()) {
                   1038: 	my $code = &supportedlanguagecode($id);
                   1039: 	if ($code) {
                   1040: 	    my $selector    = $supported_codes{$id};
                   1041: 	    my $description = &plainlanguagedescription($id);
                   1042: 	    push (@lang_choices, [$selector, $description]);
                   1043: 	}
                   1044:     }
                   1045:     return \@lang_choices;
                   1046: }
                   1047: 
                   1048: =pod
                   1049: 
1.648     raeburn  1050: =item * &linked_select_forms(...)
1.36      matthew  1051: 
                   1052: linked_select_forms returns a string containing a <script></script> block
                   1053: and html for two <select> menus.  The select menus will be linked in that
                   1054: changing the value of the first menu will result in new values being placed
                   1055: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1056: order unless a defined order is provided.
1.36      matthew  1057: 
                   1058: linked_select_forms takes the following ordered inputs:
                   1059: 
                   1060: =over 4
                   1061: 
1.112     bowersj2 1062: =item * $formname, the name of the <form> tag
1.36      matthew  1063: 
1.112     bowersj2 1064: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $firstdefault, the default value for the first menu
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1069: 
1.112     bowersj2 1070: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1071: 
1.112     bowersj2 1072: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1073: 
1.609     raeburn  1074: =item * $menuorder, the order of values in the first menu
                   1075: 
1.1115    raeburn  1076: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1077:         event for the first <select> tag
                   1078: 
                   1079: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1080:         event for the second <select> tag
                   1081: 
1.41      ng       1082: =back 
                   1083: 
1.36      matthew  1084: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1085: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1086: values for the first select menu.  The text that coincides with the 
1.41      ng       1087: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1088: and text for the second menu are given in the hash pointed to by 
                   1089: $menu{$choice1}->{'select2'}.  
                   1090: 
1.112     bowersj2 1091:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1092:                        default => "B3",
                   1093:                        select2 => { 
                   1094:                            B1 => "Choice B1",
                   1095:                            B2 => "Choice B2",
                   1096:                            B3 => "Choice B3",
                   1097:                            B4 => "Choice B4"
1.609     raeburn  1098:                            },
                   1099:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1100:                    },
                   1101:                A2 => { text =>"Choice A2" ,
                   1102:                        default => "C2",
                   1103:                        select2 => { 
                   1104:                            C1 => "Choice C1",
                   1105:                            C2 => "Choice C2",
                   1106:                            C3 => "Choice C3"
1.609     raeburn  1107:                            },
                   1108:                        order => ['C2','C1','C3'],
1.112     bowersj2 1109:                    },
                   1110:                A3 => { text =>"Choice A3" ,
                   1111:                        default => "D6",
                   1112:                        select2 => { 
                   1113:                            D1 => "Choice D1",
                   1114:                            D2 => "Choice D2",
                   1115:                            D3 => "Choice D3",
                   1116:                            D4 => "Choice D4",
                   1117:                            D5 => "Choice D5",
                   1118:                            D6 => "Choice D6",
                   1119:                            D7 => "Choice D7"
1.609     raeburn  1120:                            },
                   1121:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1122:                    }
                   1123:                );
1.36      matthew  1124: 
                   1125: =cut
                   1126: 
                   1127: sub linked_select_forms {
                   1128:     my ($formname,
                   1129:         $middletext,
                   1130:         $firstdefault,
                   1131:         $firstselectname,
                   1132:         $secondselectname, 
1.609     raeburn  1133:         $hashref,
                   1134:         $menuorder,
1.1115    raeburn  1135:         $onchangefirst,
                   1136:         $onchangesecond
1.36      matthew  1137:         ) = @_;
                   1138:     my $second = "document.$formname.$secondselectname";
                   1139:     my $first = "document.$formname.$firstselectname";
                   1140:     # output the javascript to do the changing
                   1141:     my $result = '';
1.776     bisitz   1142:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1143:     $result.="// <![CDATA[\n";
1.36      matthew  1144:     $result.="var select2data = new Object();\n";
                   1145:     $" = '","';
                   1146:     my $debug = '';
                   1147:     foreach my $s1 (sort(keys(%$hashref))) {
                   1148:         $result.="select2data.d_$s1 = new Object();\n";        
                   1149:         $result.="select2data.d_$s1.def = new String('".
                   1150:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1151:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1152:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1153:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1154:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1155:         }
1.36      matthew  1156:         $result.="\"@s2values\");\n";
                   1157:         $result.="select2data.d_$s1.texts = new Array(";        
                   1158:         my @s2texts;
                   1159:         foreach my $value (@s2values) {
                   1160:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1161:         }
                   1162:         $result.="\"@s2texts\");\n";
                   1163:     }
                   1164:     $"=' ';
                   1165:     $result.= <<"END";
                   1166: 
                   1167: function select1_changed() {
                   1168:     // Determine new choice
                   1169:     var newvalue = "d_" + $first.value;
                   1170:     // update select2
                   1171:     var values     = select2data[newvalue].values;
                   1172:     var texts      = select2data[newvalue].texts;
                   1173:     var select2def = select2data[newvalue].def;
                   1174:     var i;
                   1175:     // out with the old
                   1176:     for (i = 0; i < $second.options.length; i++) {
                   1177:         $second.options[i] = null;
                   1178:     }
                   1179:     // in with the nuclear
                   1180:     for (i=0;i<values.length; i++) {
                   1181:         $second.options[i] = new Option(values[i]);
1.143     matthew  1182:         $second.options[i].value = values[i];
1.36      matthew  1183:         $second.options[i].text = texts[i];
                   1184:         if (values[i] == select2def) {
                   1185:             $second.options[i].selected = true;
                   1186:         }
                   1187:     }
                   1188: }
1.824     bisitz   1189: // ]]>
1.36      matthew  1190: </script>
                   1191: END
                   1192:     # output the initial values for the selection lists
1.1115    raeburn  1193:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1194:     my @order = sort(keys(%{$hashref}));
                   1195:     if (ref($menuorder) eq 'ARRAY') {
                   1196:         @order = @{$menuorder};
                   1197:     }
                   1198:     foreach my $value (@order) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1201:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1205:     $result .= $middletext;
1.1115    raeburn  1206:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1207:     if ($onchangesecond) {
                   1208:         $result .= ' onchange="'.$onchangesecond.'"';
                   1209:     }
                   1210:     $result .= ">\n";
1.36      matthew  1211:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1212:     
                   1213:     my @secondorder = sort(keys(%select2));
                   1214:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1215:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1216:     }
                   1217:     foreach my $value (@secondorder) {
1.36      matthew  1218:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1219:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1220:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1221:     }
                   1222:     $result .= "</select>\n";
                   1223:     #    return $debug;
                   1224:     return $result;
                   1225: }   #  end of sub linked_select_forms {
                   1226: 
1.45      matthew  1227: =pod
1.44      bowersj2 1228: 
1.973     raeburn  1229: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1230: 
1.112     bowersj2 1231: Returns a string corresponding to an HTML link to the given help
                   1232: $topic, where $topic corresponds to the name of a .tex file in
                   1233: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1234: spaces. 
                   1235: 
                   1236: $text will optionally be linked to the same topic, allowing you to
                   1237: link text in addition to the graphic. If you do not want to link
                   1238: text, but wish to specify one of the later parameters, pass an
                   1239: empty string. 
                   1240: 
                   1241: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1242: the link will not open a new window. If false, the link will open
                   1243: a new window using Javascript. (Default is false.) 
                   1244: 
                   1245: $width and $height are optional numerical parameters that will
                   1246: override the width and height of the popped up window, which may
1.973     raeburn  1247: be useful for certain help topics with big pictures included.
                   1248: 
                   1249: $imgid is the id of the img tag used for the help icon. This may be
                   1250: used in a javascript call to switch the image src.  See 
                   1251: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1252: 
                   1253: =cut
                   1254: 
                   1255: sub help_open_topic {
1.973     raeburn  1256:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1257:     $text = "" if (not defined $text);
1.44      bowersj2 1258:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1259:     $width = 500 if (not defined $width);
1.44      bowersj2 1260:     $height = 400 if (not defined $height);
                   1261:     my $filename = $topic;
                   1262:     $filename =~ s/ /_/g;
                   1263: 
1.48      bowersj2 1264:     my $template = "";
                   1265:     my $link;
1.572     banghart 1266:     
1.159     www      1267:     $topic=~s/\W/\_/g;
1.44      bowersj2 1268: 
1.572     banghart 1269:     if (!$stayOnPage) {
1.1033    www      1270: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1271:     } elsif ($stayOnPage eq 'popup') {
                   1272:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1273:     } else {
1.48      bowersj2 1274: 	$link = "/adm/help/${filename}.hlp";
                   1275:     }
                   1276: 
                   1277:     # Add the text
1.755     neumanie 1278:     if ($text ne "") {	
1.763     bisitz   1279: 	$template.='<span class="LC_help_open_topic">'
                   1280:                   .'<a target="_top" href="'.$link.'">'
                   1281:                   .$text.'</a>';
1.48      bowersj2 1282:     }
                   1283: 
1.763     bisitz   1284:     # (Always) Add the graphic
1.179     matthew  1285:     my $title = &mt('Online Help');
1.667     raeburn  1286:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1287:     if ($imgid ne '') {
                   1288:         $imgid = ' id="'.$imgid.'"';
                   1289:     }
1.763     bisitz   1290:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1291:               .'<img src="'.$helpicon.'" border="0"'
                   1292:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1293:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1294:               .' /></a>';
                   1295:     if ($text ne "") {	
                   1296:         $template.='</span>';
                   1297:     }
1.44      bowersj2 1298:     return $template;
                   1299: 
1.106     bowersj2 1300: }
                   1301: 
                   1302: # This is a quicky function for Latex cheatsheet editing, since it 
                   1303: # appears in at least four places
                   1304: sub helpLatexCheatsheet {
1.1037    www      1305:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1306:     my $out;
1.106     bowersj2 1307:     my $addOther = '';
1.732     raeburn  1308:     if ($topic) {
1.1037    www      1309: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1310:     }
                   1311:     $out = '<span>' # Start cheatsheet
                   1312: 	  .$addOther
                   1313:           .'<span>'
1.1037    www      1314: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1315: 	  .'</span> <span>'
1.1037    www      1316: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1317: 	  .'</span>';
1.732     raeburn  1318:     unless ($not_author) {
1.1186    kruse    1319:         $out .= '<span>'
                   1320:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1321:                .'</span> <span>'
                   1322:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1323: 	       .'</span>';
1.732     raeburn  1324:     }
1.763     bisitz   1325:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1326:     return $out;
1.172     www      1327: }
                   1328: 
1.430     albertel 1329: sub general_help {
                   1330:     my $helptopic='Student_Intro';
                   1331:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1332: 	$helptopic='Authoring_Intro';
1.907     raeburn  1333:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1334: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1335:     } elsif ($env{'request.role'}=~/^dc/) {
                   1336:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1337:     }
                   1338:     return $helptopic;
                   1339: }
                   1340: 
                   1341: sub update_help_link {
                   1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1343:     my $origurl = $ENV{'REQUEST_URI'};
                   1344:     $origurl=~s|^/~|/priv/|;
                   1345:     my $timestamp = time;
                   1346:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1347:         $$datum = &escape($$datum);
                   1348:     }
                   1349: 
                   1350:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1351:     my $output .= <<"ENDOUTPUT";
                   1352: <script type="text/javascript">
1.824     bisitz   1353: // <![CDATA[
1.430     albertel 1354: banner_link = '$banner_link';
1.824     bisitz   1355: // ]]>
1.430     albertel 1356: </script>
                   1357: ENDOUTPUT
                   1358:     return $output;
                   1359: }
                   1360: 
                   1361: # now just updates the help link and generates a blue icon
1.193     raeburn  1362: sub help_open_menu {
1.430     albertel 1363:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1364: 	= @_;    
1.949     droeschl 1365:     $stayOnPage = 1;
1.430     albertel 1366:     my $output;
                   1367:     if ($component_help) {
                   1368: 	if (!$text) {
                   1369: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1370: 				       $width,$height);
                   1371: 	} else {
                   1372: 	    my $help_text;
                   1373: 	    $help_text=&unescape($topic);
                   1374: 	    $output='<table><tr><td>'.
                   1375: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1376: 				 $width,$height).'</td></tr></table>';
                   1377: 	}
                   1378:     }
                   1379:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1380:     return $output.$banner_link;
                   1381: }
                   1382: 
                   1383: sub top_nav_help {
                   1384:     my ($text) = @_;
1.436     albertel 1385:     $text = &mt($text);
1.949     droeschl 1386:     my $stay_on_page = 1;
                   1387: 
1.1168    raeburn  1388:     my ($link,$banner_link);
                   1389:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1390:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1391: 	                         : "javascript:helpMenu('open')";
                   1392:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1393:     }
1.201     raeburn  1394:     my $title = &mt('Get help');
1.1168    raeburn  1395:     if ($link) {
                   1396:         return <<"END";
1.436     albertel 1397: $banner_link
1.1159    raeburn  1398: <a href="$link" title="$title">$text</a>
1.436     albertel 1399: END
1.1168    raeburn  1400:     } else {
                   1401:         return '&nbsp;'.$text.'&nbsp;';
                   1402:     }
1.436     albertel 1403: }
                   1404: 
                   1405: sub help_menu_js {
1.1154    raeburn  1406:     my ($httphost) = @_;
1.949     droeschl 1407:     my $stayOnPage = 1;
1.436     albertel 1408:     my $width = 620;
                   1409:     my $height = 600;
1.430     albertel 1410:     my $helptopic=&general_help();
1.1154    raeburn  1411:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1412:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1413:     my $start_page =
                   1414:         &Apache::loncommon::start_page('Help Menu', undef,
                   1415: 				       {'frameset'    => 1,
                   1416: 					'js_ready'    => 1,
1.1154    raeburn  1417:                                         'use_absolute' => $httphost,
1.331     albertel 1418: 					'add_entries' => {
1.1168    raeburn  1419: 					    'border' => '0', 
1.579     raeburn  1420: 					    'rows'   => "110,*",},});
1.331     albertel 1421:     my $end_page =
                   1422:         &Apache::loncommon::end_page({'frameset' => 1,
                   1423: 				      'js_ready' => 1,});
                   1424: 
1.436     albertel 1425:     my $template .= <<"ENDTEMPLATE";
                   1426: <script type="text/javascript">
1.877     bisitz   1427: // <![CDATA[
1.253     albertel 1428: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1429: var banner_link = '';
1.243     raeburn  1430: function helpMenu(target) {
                   1431:     var caller = this;
                   1432:     if (target == 'open') {
                   1433:         var newWindow = null;
                   1434:         try {
1.262     albertel 1435:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1436:         }
                   1437:         catch(error) {
                   1438:             writeHelp(caller);
                   1439:             return;
                   1440:         }
                   1441:         if (newWindow) {
                   1442:             caller = newWindow;
                   1443:         }
1.193     raeburn  1444:     }
1.243     raeburn  1445:     writeHelp(caller);
                   1446:     return;
                   1447: }
                   1448: function writeHelp(caller) {
1.1168    raeburn  1449:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1450:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1451:     caller.document.close();
                   1452:     caller.focus();
1.193     raeburn  1453: }
1.877     bisitz   1454: // END LON-CAPA Internal -->
1.253     albertel 1455: // ]]>
1.436     albertel 1456: </script>
1.193     raeburn  1457: ENDTEMPLATE
                   1458:     return $template;
                   1459: }
                   1460: 
1.172     www      1461: sub help_open_bug {
                   1462:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1463:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1464:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1465:     $text = "" if (not defined $text);
                   1466: 	$stayOnPage=1;
1.184     albertel 1467:     $width = 600 if (not defined $width);
                   1468:     $height = 600 if (not defined $height);
1.172     www      1469: 
                   1470:     $topic=~s/\W+/\+/g;
                   1471:     my $link='';
                   1472:     my $template='';
1.379     albertel 1473:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1474: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1475:     if (!$stayOnPage)
                   1476:     {
                   1477: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1478:     }
                   1479:     else
                   1480:     {
                   1481: 	$link = $url;
                   1482:     }
                   1483:     # Add the text
                   1484:     if ($text ne "")
                   1485:     {
                   1486: 	$template .= 
                   1487:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1488:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1489:     }
                   1490: 
                   1491:     # Add the graphic
1.179     matthew  1492:     my $title = &mt('Report a Bug');
1.215     albertel 1493:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1494:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1495:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1496: ENDTEMPLATE
                   1497:     if ($text ne '') { $template.='</td></tr></table>' };
                   1498:     return $template;
                   1499: 
                   1500: }
                   1501: 
                   1502: sub help_open_faq {
                   1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1504:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1505:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1506:     $text = "" if (not defined $text);
                   1507: 	$stayOnPage=1;
                   1508:     $width = 350 if (not defined $width);
                   1509:     $height = 400 if (not defined $height);
                   1510: 
                   1511:     $topic=~s/\W+/\+/g;
                   1512:     my $link='';
                   1513:     my $template='';
                   1514:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1515:     if (!$stayOnPage)
                   1516:     {
                   1517: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1518:     }
                   1519:     else
                   1520:     {
                   1521: 	$link = $url;
                   1522:     }
                   1523: 
                   1524:     # Add the text
                   1525:     if ($text ne "")
                   1526:     {
                   1527: 	$template .= 
1.173     www      1528:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1529:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1530:     }
                   1531: 
                   1532:     # Add the graphic
1.179     matthew  1533:     my $title = &mt('View the FAQ');
1.215     albertel 1534:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1535:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1536:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1537: ENDTEMPLATE
                   1538:     if ($text ne '') { $template.='</td></tr></table>' };
                   1539:     return $template;
                   1540: 
1.44      bowersj2 1541: }
1.37      matthew  1542: 
1.180     matthew  1543: ###############################################################
                   1544: ###############################################################
                   1545: 
1.45      matthew  1546: =pod
                   1547: 
1.648     raeburn  1548: =item * &change_content_javascript():
1.256     matthew  1549: 
                   1550: This and the next function allow you to create small sections of an
                   1551: otherwise static HTML page that you can update on the fly with
                   1552: Javascript, even in Netscape 4.
                   1553: 
                   1554: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1555: must be written to the HTML page once. It will prove the Javascript
                   1556: function "change(name, content)". Calling the change function with the
                   1557: name of the section 
                   1558: you want to update, matching the name passed to C<changable_area>, and
                   1559: the new content you want to put in there, will put the content into
                   1560: that area.
                   1561: 
                   1562: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1563: to contain room for the original contents. You need to "make space"
                   1564: for whatever changes you wish to make, and be B<sure> to check your
                   1565: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1566: it's adequate for updating a one-line status display, but little more.
                   1567: This script will set the space to 100% width, so you only need to
                   1568: worry about height in Netscape 4.
                   1569: 
                   1570: Modern browsers are much less limiting, and if you can commit to the
                   1571: user not using Netscape 4, this feature may be used freely with
                   1572: pretty much any HTML.
                   1573: 
                   1574: =cut
                   1575: 
                   1576: sub change_content_javascript {
                   1577:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1578:     if ($env{'browser.type'} eq 'netscape' &&
                   1579: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1580: 	return (<<NETSCAPE4);
                   1581: 	function change(name, content) {
                   1582: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1583: 	    doc.open();
                   1584: 	    doc.write(content);
                   1585: 	    doc.close();
                   1586: 	}
                   1587: NETSCAPE4
                   1588:     } else {
                   1589: 	# Otherwise, we need to use semi-standards-compliant code
                   1590: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1591: 	# is really scary, and every useful browser supports it
                   1592: 	return (<<DOMBASED);
                   1593: 	function change(name, content) {
                   1594: 	    element = document.getElementById(name);
                   1595: 	    element.innerHTML = content;
                   1596: 	}
                   1597: DOMBASED
                   1598:     }
                   1599: }
                   1600: 
                   1601: =pod
                   1602: 
1.648     raeburn  1603: =item * &changable_area($name,$origContent):
1.256     matthew  1604: 
                   1605: This provides a "changable area" that can be modified on the fly via
                   1606: the Javascript code provided in C<change_content_javascript>. $name is
                   1607: the name you will use to reference the area later; do not repeat the
                   1608: same name on a given HTML page more then once. $origContent is what
                   1609: the area will originally contain, which can be left blank.
                   1610: 
                   1611: =cut
                   1612: 
                   1613: sub changable_area {
                   1614:     my ($name, $origContent) = @_;
                   1615: 
1.258     albertel 1616:     if ($env{'browser.type'} eq 'netscape' &&
                   1617: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1618: 	# If this is netscape 4, we need to use the Layer tag
                   1619: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1620:     } else {
                   1621: 	return "<span id='$name'>$origContent</span>";
                   1622:     }
                   1623: }
                   1624: 
                   1625: =pod
                   1626: 
1.648     raeburn  1627: =item * &viewport_geometry_js 
1.590     raeburn  1628: 
                   1629: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1630: 
                   1631: =cut
                   1632: 
                   1633: 
                   1634: sub viewport_geometry_js { 
                   1635:     return <<"GEOMETRY";
                   1636: var Geometry = {};
                   1637: function init_geometry() {
                   1638:     if (Geometry.init) { return };
                   1639:     Geometry.init=1;
                   1640:     if (window.innerHeight) {
                   1641:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1642:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1643:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1644:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1645:     }
                   1646:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1647:         Geometry.getViewportHeight =
                   1648:             function() { return document.documentElement.clientHeight; };
                   1649:         Geometry.getViewportWidth =
                   1650:             function() { return document.documentElement.clientWidth; };
                   1651: 
                   1652:         Geometry.getHorizontalScroll =
                   1653:             function() { return document.documentElement.scrollLeft; };
                   1654:         Geometry.getVerticalScroll =
                   1655:             function() { return document.documentElement.scrollTop; };
                   1656:     }
                   1657:     else if (document.body.clientHeight) {
                   1658:         Geometry.getViewportHeight =
                   1659:             function() { return document.body.clientHeight; };
                   1660:         Geometry.getViewportWidth =
                   1661:             function() { return document.body.clientWidth; };
                   1662:         Geometry.getHorizontalScroll =
                   1663:             function() { return document.body.scrollLeft; };
                   1664:         Geometry.getVerticalScroll =
                   1665:             function() { return document.body.scrollTop; };
                   1666:     }
                   1667: }
                   1668: 
                   1669: GEOMETRY
                   1670: }
                   1671: 
                   1672: =pod
                   1673: 
1.648     raeburn  1674: =item * &viewport_size_js()
1.590     raeburn  1675: 
                   1676: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1677: 
                   1678: =cut
                   1679: 
                   1680: sub viewport_size_js {
                   1681:     my $geometry = &viewport_geometry_js();
                   1682:     return <<"DIMS";
                   1683: 
                   1684: $geometry
                   1685: 
                   1686: function getViewportDims(width,height) {
                   1687:     init_geometry();
                   1688:     width.value = Geometry.getViewportWidth();
                   1689:     height.value = Geometry.getViewportHeight();
                   1690:     return;
                   1691: }
                   1692: 
                   1693: DIMS
                   1694: }
                   1695: 
                   1696: =pod
                   1697: 
1.648     raeburn  1698: =item * &resize_textarea_js()
1.565     albertel 1699: 
                   1700: emits the needed javascript to resize a textarea to be as big as possible
                   1701: 
                   1702: creates a function resize_textrea that takes two IDs first should be
                   1703: the id of the element to resize, second should be the id of a div that
                   1704: surrounds everything that comes after the textarea, this routine needs
                   1705: to be attached to the <body> for the onload and onresize events.
                   1706: 
1.648     raeburn  1707: =back
1.565     albertel 1708: 
                   1709: =cut
                   1710: 
                   1711: sub resize_textarea_js {
1.590     raeburn  1712:     my $geometry = &viewport_geometry_js();
1.565     albertel 1713:     return <<"RESIZE";
                   1714:     <script type="text/javascript">
1.824     bisitz   1715: // <![CDATA[
1.590     raeburn  1716: $geometry
1.565     albertel 1717: 
1.588     albertel 1718: function getX(element) {
                   1719:     var x = 0;
                   1720:     while (element) {
                   1721: 	x += element.offsetLeft;
                   1722: 	element = element.offsetParent;
                   1723:     }
                   1724:     return x;
                   1725: }
                   1726: function getY(element) {
                   1727:     var y = 0;
                   1728:     while (element) {
                   1729: 	y += element.offsetTop;
                   1730: 	element = element.offsetParent;
                   1731:     }
                   1732:     return y;
                   1733: }
                   1734: 
                   1735: 
1.565     albertel 1736: function resize_textarea(textarea_id,bottom_id) {
                   1737:     init_geometry();
                   1738:     var textarea        = document.getElementById(textarea_id);
                   1739:     //alert(textarea);
                   1740: 
1.588     albertel 1741:     var textarea_top    = getY(textarea);
1.565     albertel 1742:     var textarea_height = textarea.offsetHeight;
                   1743:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1744:     var bottom_top      = getY(bottom);
1.565     albertel 1745:     var bottom_height   = bottom.offsetHeight;
                   1746:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1747:     var fudge           = 23;
1.565     albertel 1748:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1749:     if (new_height < 300) {
                   1750: 	new_height = 300;
                   1751:     }
                   1752:     textarea.style.height=new_height+'px';
                   1753: }
1.824     bisitz   1754: // ]]>
1.565     albertel 1755: </script>
                   1756: RESIZE
                   1757: 
                   1758: }
                   1759: 
1.1205    golterma 1760: sub colorfuleditor_js {
                   1761:     return <<"COLORFULEDIT"
                   1762: <script type="text/javascript">
                   1763: // <![CDATA[>
                   1764:     function fold_box(curDepth, lastresource){
                   1765: 
                   1766:     // we need a list because there can be several blocks you need to fold in one tag
                   1767:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1768:     // but there is only one folding button per tag
                   1769:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1770: 
                   1771:         if(block.item(0).style.display == 'none'){
                   1772: 
                   1773:             foldbutton.value = '@{[&mt("Hide")]}';
                   1774:             for (i = 0; i < block.length; i++){
                   1775:                 block.item(i).style.display = '';
                   1776:             }
                   1777:         }else{
                   1778: 
                   1779:             foldbutton.value = '@{[&mt("Show")]}';
                   1780:             for (i = 0; i < block.length; i++){
                   1781:                 // block.item(i).style.visibility = 'collapse';
                   1782:                 block.item(i).style.display = 'none';
                   1783:             }
                   1784:         };
                   1785:         saveState(lastresource);
                   1786:     }
                   1787: 
                   1788:     function saveState (lastresource) {
                   1789: 
                   1790:         var tag_list = getTagList();
                   1791:         if(tag_list != null){
                   1792:             var timestamp = new Date().getTime();
                   1793:             var key = lastresource;
                   1794: 
                   1795:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1796:             // starting with timestamp
                   1797:             var value = timestamp+';';
                   1798: 
                   1799:             // building the list of key-value pairs
                   1800:             for(var i = 0; i < tag_list.length; i++){
                   1801:                 value += tag_list[i]+',';
                   1802:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1803:             }
                   1804: 
                   1805:             // only iterate whole storage if nothing to override
                   1806:             if(localStorage.getItem(key) == null){        
                   1807: 
                   1808:                 // prevent storage from growing large
                   1809:                 if(localStorage.length > 50){
                   1810:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1811:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1812:                     var oldest_key;
                   1813:                     
                   1814:                     for(var i = 1; i < localStorage.length; i++){
                   1815:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1816:                             oldest_key = localStorage.key(i);
                   1817:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1818:                         }
                   1819:                     }
                   1820:                     localStorage.removeItem(oldest_key);
                   1821:                 }
                   1822:             }
                   1823:             localStorage.setItem(key,value);
                   1824:         }
                   1825:     }
                   1826: 
                   1827:     // restore folding status of blocks (on page load)
                   1828:     function restoreState (lastresource) {
                   1829:         if(localStorage.getItem(lastresource) != null){
                   1830:             var key = lastresource;
                   1831:             var value = localStorage.getItem(key);
                   1832:             var regex_delTimestamp = /^\d+;/;
                   1833: 
                   1834:             value.replace(regex_delTimestamp, '');
                   1835: 
                   1836:             var valueArr = value.split(';');
                   1837:             var pairs;
                   1838:             var elements;
                   1839:             for (var i = 0; i < valueArr.length; i++){
                   1840:                 pairs = valueArr[i].split(',');
                   1841:                 elements = document.getElementsByName(pairs[0]);
                   1842: 
                   1843:                 for (var j = 0; j < elements.length; j++){  
                   1844:                     elements[j].style.display = pairs[1];
                   1845:                     if (pairs[1] == "none"){
                   1846:                         var regex_id = /([_\\d]+)\$/;
                   1847:                         regex_id.exec(pairs[0]);
                   1848:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1849:                     }
                   1850:                 }
                   1851:             }
                   1852:         }
                   1853:     }
                   1854: 
                   1855:     function getTagList () {
                   1856:         
                   1857:         var stringToSearch = document.lonhomework.innerHTML;
                   1858: 
                   1859:         var ret = new Array();
                   1860:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1861:         var tag_list = stringToSearch.match(regex_findBlock);
                   1862: 
                   1863:         if(tag_list != null){
                   1864:             for(var i = 0; i < tag_list.length; i++){            
                   1865:                 ret.push(tag_list[i].replace(/"/, ''));
                   1866:             }
                   1867:         }
                   1868:         return ret;
                   1869:     }
                   1870: 
                   1871:     function saveScrollPosition (resource) {
                   1872:         var tag_list = getTagList();
                   1873: 
                   1874:         // we dont always want to jump to the first block
                   1875:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1876:         if(\$(window).scrollTop() > 170){
                   1877:             if(tag_list != null){
                   1878:                 var result;
                   1879:                 for(var i = 0; i < tag_list.length; i++){
                   1880:                     if(isElementInViewport(tag_list[i])){
                   1881:                         result += tag_list[i]+';';
                   1882:                     }
                   1883:                 }
                   1884:                 sessionStorage.setItem('anchor_'+resource, result);
                   1885:             }
                   1886:         } else {
                   1887:             // we dont need to save zero, just delete the item to leave everything tidy
                   1888:             sessionStorage.removeItem('anchor_'+resource);
                   1889:         }
                   1890:     }
                   1891: 
                   1892:     function restoreScrollPosition(resource){
                   1893: 
                   1894:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1895:         if(elem != null){
                   1896:             var tag_list = elem.split(';');
                   1897:             var elem_list;
                   1898: 
                   1899:             for(var i = 0; i < tag_list.length; i++){
                   1900:                 elem_list = document.getElementsByName(tag_list[i]);
                   1901:                 
                   1902:                 if(elem_list.length > 0){
                   1903:                     elem = elem_list[0];
                   1904:                     break;
                   1905:                 }
                   1906:             }
                   1907:             elem.scrollIntoView();
                   1908:         }
                   1909:     }
                   1910: 
                   1911:     function isElementInViewport(el) {
                   1912: 
                   1913:         // change to last element instead of first
                   1914:         var elem = document.getElementsByName(el);
                   1915:         var rect = elem[0].getBoundingClientRect();
                   1916: 
                   1917:         return (
                   1918:             rect.top >= 0 &&
                   1919:             rect.left >= 0 &&
                   1920:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1921:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1922:         );
                   1923:     }
                   1924:     
                   1925:     function autosize(depth){
                   1926:         var cmInst = window['cm'+depth];
                   1927:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1928: 
                   1929:         // is fixed size, switching to dynamic
                   1930:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1931:             cmInst.setSize("","auto");
                   1932:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1933:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1934: 
                   1935:         // is dynamic size, switching to fixed
                   1936:         } else {
                   1937:             cmInst.setSize("","300px");
                   1938:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1939:             sessionStorage.removeItem("autosized_"+depth);
                   1940:         }
                   1941:     }
                   1942: 
                   1943: 
                   1944: 
                   1945: // ]]>
                   1946: </script>
                   1947: COLORFULEDIT
                   1948: }
                   1949: 
                   1950: sub xmleditor_js {
                   1951:     return <<XMLEDIT
                   1952: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1953: <script type="text/javascript">
                   1954: // <![CDATA[>
                   1955: 
                   1956:     function saveScrollPosition (resource) {
                   1957: 
                   1958:         var scrollPos = \$(window).scrollTop();
                   1959:         sessionStorage.setItem(resource,scrollPos);
                   1960:     }
                   1961: 
                   1962:     function restoreScrollPosition(resource){
                   1963: 
                   1964:         var scrollPos = sessionStorage.getItem(resource);
                   1965:         \$(window).scrollTop(scrollPos);
                   1966:     }
                   1967: 
                   1968:     // unless internet explorer
                   1969:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1970: 
                   1971:         \$(document).ready(function() {
                   1972:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1973:         });
                   1974:     }
                   1975: 
                   1976:     // inserts text at cursor position into codemirror (xml editor only)
                   1977:     function insertText(text){
                   1978:         cm.focus();
                   1979:         var curPos = cm.getCursor();
                   1980:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1981:     }
                   1982: // ]]>
                   1983: </script>
                   1984: XMLEDIT
                   1985: }
                   1986: 
                   1987: sub insert_folding_button {
                   1988:     my $curDepth = $Apache::lonxml::curdepth;
                   1989:     my $lastresource = $env{'request.ambiguous'};
                   1990: 
                   1991:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   1992:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1993: }
                   1994: 
1.565     albertel 1995: =pod
                   1996: 
1.256     matthew  1997: =head1 Excel and CSV file utility routines
                   1998: 
                   1999: =cut
                   2000: 
                   2001: ###############################################################
                   2002: ###############################################################
                   2003: 
                   2004: =pod
                   2005: 
1.1162    raeburn  2006: =over 4
                   2007: 
1.648     raeburn  2008: =item * &csv_translate($text) 
1.37      matthew  2009: 
1.185     www      2010: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2011: format.
                   2012: 
                   2013: =cut
                   2014: 
1.180     matthew  2015: ###############################################################
                   2016: ###############################################################
1.37      matthew  2017: sub csv_translate {
                   2018:     my $text = shift;
                   2019:     $text =~ s/\"/\"\"/g;
1.209     albertel 2020:     $text =~ s/\n/ /g;
1.37      matthew  2021:     return $text;
                   2022: }
1.180     matthew  2023: 
                   2024: ###############################################################
                   2025: ###############################################################
                   2026: 
                   2027: =pod
                   2028: 
1.648     raeburn  2029: =item * &define_excel_formats()
1.180     matthew  2030: 
                   2031: Define some commonly used Excel cell formats.
                   2032: 
                   2033: Currently supported formats:
                   2034: 
                   2035: =over 4
                   2036: 
                   2037: =item header
                   2038: 
                   2039: =item bold
                   2040: 
                   2041: =item h1
                   2042: 
                   2043: =item h2
                   2044: 
                   2045: =item h3
                   2046: 
1.256     matthew  2047: =item h4
                   2048: 
                   2049: =item i
                   2050: 
1.180     matthew  2051: =item date
                   2052: 
                   2053: =back
                   2054: 
                   2055: Inputs: $workbook
                   2056: 
                   2057: Returns: $format, a hash reference.
                   2058: 
1.1057    foxr     2059: 
1.180     matthew  2060: =cut
                   2061: 
                   2062: ###############################################################
                   2063: ###############################################################
                   2064: sub define_excel_formats {
                   2065:     my ($workbook) = @_;
                   2066:     my $format;
                   2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2068:                                                 bottom    => 1,
                   2069:                                                 align     => 'center');
                   2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2076:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2077:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2078:     return $format;
                   2079: }
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
1.113     bowersj2 2083: 
                   2084: =pod
                   2085: 
1.648     raeburn  2086: =item * &create_workbook()
1.255     matthew  2087: 
                   2088: Create an Excel worksheet.  If it fails, output message on the
                   2089: request object and return undefs.
                   2090: 
                   2091: Inputs: Apache request object
                   2092: 
                   2093: Returns (undef) on failure, 
                   2094:     Excel worksheet object, scalar with filename, and formats 
                   2095:     from &Apache::loncommon::define_excel_formats on success
                   2096: 
                   2097: =cut
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
                   2101: sub create_workbook {
                   2102:     my ($r) = @_;
                   2103:         #
                   2104:     # Create the excel spreadsheet
                   2105:     my $filename = '/prtspool/'.
1.258     albertel 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2107:         time.'_'.rand(1000000000).'.xls';
                   2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2109:     if (! defined($workbook)) {
                   2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2111:         $r->print(
                   2112:             '<p class="LC_error">'
                   2113:            .&mt('Problems occurred in creating the new Excel file.')
                   2114:            .' '.&mt('This error has been logged.')
                   2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2116:            .'</p>'
                   2117:         );
1.255     matthew  2118:         return (undef);
                   2119:     }
                   2120:     #
1.1014    foxr     2121:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2122:     #
                   2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2124:     return ($workbook,$filename,$format);
                   2125: }
                   2126: 
                   2127: ###############################################################
                   2128: ###############################################################
                   2129: 
                   2130: =pod
                   2131: 
1.648     raeburn  2132: =item * &create_text_file()
1.113     bowersj2 2133: 
1.542     raeburn  2134: Create a file to write to and eventually make available to the user.
1.256     matthew  2135: If file creation fails, outputs an error message on the request object and 
                   2136: return undefs.
1.113     bowersj2 2137: 
1.256     matthew  2138: Inputs: Apache request object, and file suffix
1.113     bowersj2 2139: 
1.256     matthew  2140: Returns (undef) on failure, 
                   2141:     Filehandle and filename on success.
1.113     bowersj2 2142: 
                   2143: =cut
                   2144: 
1.256     matthew  2145: ###############################################################
                   2146: ###############################################################
                   2147: sub create_text_file {
                   2148:     my ($r,$suffix) = @_;
                   2149:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2150:     my $fh;
                   2151:     my $filename = '/prtspool/'.
1.258     albertel 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2153:         time.'_'.rand(1000000000).'.'.$suffix;
                   2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2155:     if (! defined($fh)) {
                   2156:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2157:         $r->print(
                   2158:             '<p class="LC_error">'
                   2159:            .&mt('Problems occurred in creating the output file.')
                   2160:            .' '.&mt('This error has been logged.')
                   2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2162:            .'</p>'
                   2163:         );
1.113     bowersj2 2164:     }
1.256     matthew  2165:     return ($fh,$filename)
1.113     bowersj2 2166: }
                   2167: 
                   2168: 
1.256     matthew  2169: =pod 
1.113     bowersj2 2170: 
                   2171: =back
                   2172: 
                   2173: =cut
1.37      matthew  2174: 
                   2175: ###############################################################
1.33      matthew  2176: ##        Home server <option> list generating code          ##
                   2177: ###############################################################
1.35      matthew  2178: 
1.169     www      2179: # ------------------------------------------
                   2180: 
                   2181: sub domain_select {
                   2182:     my ($name,$value,$multiple)=@_;
                   2183:     my %domains=map { 
1.514     albertel 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2185:     } &Apache::lonnet::all_domains();
1.169     www      2186:     if ($multiple) {
                   2187: 	$domains{''}=&mt('Any domain');
1.550     albertel 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2189: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2190:     } else {
1.550     albertel 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2192: 	return &select_form($name,$value,\%domains);
1.169     www      2193:     }
                   2194: }
                   2195: 
1.282     albertel 2196: #-------------------------------------------
                   2197: 
                   2198: =pod
                   2199: 
1.519     raeburn  2200: =head1 Routines for form select boxes
                   2201: 
                   2202: =over 4
                   2203: 
1.648     raeburn  2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2205: 
                   2206: Returns a string containing a <select> element int multiple mode
                   2207: 
                   2208: 
                   2209: Args:
                   2210:   $name - name of the <select> element
1.506     raeburn  2211:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2212:   $size - number of rows long the select element is
1.283     albertel 2213:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2214:           (shown text should already have been &mt())
1.506     raeburn  2215:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2216: 
1.282     albertel 2217: =cut
                   2218: 
                   2219: #-------------------------------------------
1.169     www      2220: sub multiple_select_form {
1.284     albertel 2221:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2223:     my $output='';
1.191     matthew  2224:     if (! defined($size)) {
                   2225:         $size = 4;
1.283     albertel 2226:         if (scalar(keys(%$hash))<4) {
                   2227:             $size = scalar(keys(%$hash));
1.191     matthew  2228:         }
                   2229:     }
1.734     bisitz   2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2231:     my @order;
1.506     raeburn  2232:     if (ref($order) eq 'ARRAY')  {
                   2233:         @order = @{$order};
                   2234:     } else {
                   2235:         @order = sort(keys(%$hash));
1.501     banghart 2236:     }
                   2237:     if (exists($$hash{'select_form_order'})) {
                   2238:         @order = @{$$hash{'select_form_order'}};
                   2239:     }
                   2240:         
1.284     albertel 2241:     foreach my $key (@order) {
1.356     albertel 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2243:         $output.='selected="selected" ' if ($selected{$key});
                   2244:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2245:     }
                   2246:     $output.="</select>\n";
                   2247:     return $output;
                   2248: }
                   2249: 
1.88      www      2250: #-------------------------------------------
                   2251: 
                   2252: =pod
                   2253: 
1.970     raeburn  2254: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2255: 
                   2256: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2257: allow a user to select options from a ref to a hash containing:
                   2258: option_name => displayed text. An optional $onchange can include
                   2259: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2260: 
1.88      www      2261: See lonrights.pm for an example invocation and use.
                   2262: 
                   2263: =cut
                   2264: 
                   2265: #-------------------------------------------
                   2266: sub select_form {
1.970     raeburn  2267:     my ($def,$name,$hashref,$onchange) = @_;
                   2268:     return unless (ref($hashref) eq 'HASH');
                   2269:     if ($onchange) {
                   2270:         $onchange = ' onchange="'.$onchange.'"';
                   2271:     }
                   2272:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2273:     my @keys;
1.970     raeburn  2274:     if (exists($hashref->{'select_form_order'})) {
                   2275: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2276:     } else {
1.970     raeburn  2277: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2278:     }
1.356     albertel 2279:     foreach my $key (@keys) {
                   2280:         $selectform.=
                   2281: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2282:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2283:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2284:     }
                   2285:     $selectform.="</select>";
                   2286:     return $selectform;
                   2287: }
                   2288: 
1.475     www      2289: # For display filters
                   2290: 
                   2291: sub display_filter {
1.1074    raeburn  2292:     my ($context) = @_;
1.475     www      2293:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2294:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2295:     my $phraseinput = 'hidden';
                   2296:     my $includeinput = 'hidden';
                   2297:     my ($checked,$includetypestext);
                   2298:     if ($env{'form.displayfilter'} eq 'containing') {
                   2299:         $phraseinput = 'text'; 
                   2300:         if ($context eq 'parmslog') {
                   2301:             $includeinput = 'checkbox';
                   2302:             if ($env{'form.includetypes'}) {
                   2303:                 $checked = ' checked="checked"';
                   2304:             }
                   2305:             $includetypestext = &mt('Include parameter types');
                   2306:         }
                   2307:     } else {
                   2308:         $includetypestext = '&nbsp;';
                   2309:     }
                   2310:     my ($additional,$secondid,$thirdid);
                   2311:     if ($context eq 'parmslog') {
                   2312:         $additional = 
                   2313:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2314:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2315:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2316:             '</label>';
                   2317:         $secondid = 'includetypes';
                   2318:         $thirdid = 'includetypestext';
                   2319:     }
                   2320:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2321:                                                     '$secondid','$thirdid')";
                   2322:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2323: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2324: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2325: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2326:            &mt('Filter: [_1]',
1.477     www      2327: 	   &select_form($env{'form.displayfilter'},
                   2328: 			'displayfilter',
1.970     raeburn  2329: 			{'currentfolder' => 'Current folder/page',
1.477     www      2330: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2331: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2332: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2333:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2334:                          '" />'.$additional;
                   2335: }
                   2336: 
                   2337: sub display_filter_js {
                   2338:     my $includetext = &mt('Include parameter types');
                   2339:     return <<"ENDJS";
                   2340:   
                   2341: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2342:     var firstType = 'hidden';
                   2343:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2344:         firstType = 'text';
                   2345:     }
                   2346:     firstObject = document.getElementById(firstid);
                   2347:     if (typeof(firstObject) == 'object') {
                   2348:         if (firstObject.type != firstType) {
                   2349:             changeInputType(firstObject,firstType);
                   2350:         }
                   2351:     }
                   2352:     if (context == 'parmslog') {
                   2353:         var secondType = 'hidden';
                   2354:         if (firstType == 'text') {
                   2355:             secondType = 'checkbox';
                   2356:         }
                   2357:         secondObject = document.getElementById(secondid);  
                   2358:         if (typeof(secondObject) == 'object') {
                   2359:             if (secondObject.type != secondType) {
                   2360:                 changeInputType(secondObject,secondType);
                   2361:             }
                   2362:         }
                   2363:         var textItem = document.getElementById(thirdid);
                   2364:         var currtext = textItem.innerHTML;
                   2365:         var newtext;
                   2366:         if (firstType == 'text') {
                   2367:             newtext = '$includetext';
                   2368:         } else {
                   2369:             newtext = '&nbsp;';
                   2370:         }
                   2371:         if (currtext != newtext) {
                   2372:             textItem.innerHTML = newtext;
                   2373:         }
                   2374:     }
                   2375:     return;
                   2376: }
                   2377: 
                   2378: function changeInputType(oldObject,newType) {
                   2379:     var newObject = document.createElement('input');
                   2380:     newObject.type = newType;
                   2381:     if (oldObject.size) {
                   2382:         newObject.size = oldObject.size;
                   2383:     }
                   2384:     if (oldObject.value) {
                   2385:         newObject.value = oldObject.value;
                   2386:     }
                   2387:     if (oldObject.name) {
                   2388:         newObject.name = oldObject.name;
                   2389:     }
                   2390:     if (oldObject.id) {
                   2391:         newObject.id = oldObject.id;
                   2392:     }
                   2393:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2394:     return;
                   2395: }
                   2396: 
                   2397: ENDJS
1.475     www      2398: }
                   2399: 
1.167     www      2400: sub gradeleveldescription {
                   2401:     my $gradelevel=shift;
                   2402:     my %gradelevels=(0 => 'Not specified',
                   2403: 		     1 => 'Grade 1',
                   2404: 		     2 => 'Grade 2',
                   2405: 		     3 => 'Grade 3',
                   2406: 		     4 => 'Grade 4',
                   2407: 		     5 => 'Grade 5',
                   2408: 		     6 => 'Grade 6',
                   2409: 		     7 => 'Grade 7',
                   2410: 		     8 => 'Grade 8',
                   2411: 		     9 => 'Grade 9',
                   2412: 		     10 => 'Grade 10',
                   2413: 		     11 => 'Grade 11',
                   2414: 		     12 => 'Grade 12',
                   2415: 		     13 => 'Grade 13',
                   2416: 		     14 => '100 Level',
                   2417: 		     15 => '200 Level',
                   2418: 		     16 => '300 Level',
                   2419: 		     17 => '400 Level',
                   2420: 		     18 => 'Graduate Level');
                   2421:     return &mt($gradelevels{$gradelevel});
                   2422: }
                   2423: 
1.163     www      2424: sub select_level_form {
                   2425:     my ($deflevel,$name)=@_;
                   2426:     unless ($deflevel) { $deflevel=0; }
1.167     www      2427:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2428:     for (my $i=0; $i<=18; $i++) {
                   2429:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2430:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2431:                 ">".&gradeleveldescription($i)."</option>\n";
                   2432:     }
                   2433:     $selectform.="</select>";
                   2434:     return $selectform;
1.163     www      2435: }
1.167     www      2436: 
1.35      matthew  2437: #-------------------------------------------
                   2438: 
1.45      matthew  2439: =pod
                   2440: 
1.1121    raeburn  2441: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2442: 
                   2443: Returns a string containing a <select name='$name' size='1'> form to 
                   2444: allow a user to select the domain to preform an operation in.  
                   2445: See loncreateuser.pm for an example invocation and use.
                   2446: 
1.90      www      2447: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2448: selected");
                   2449: 
1.743     raeburn  2450: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2451: 
1.910     raeburn  2452: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2453: 
1.1121    raeburn  2454: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2455: 
                   2456: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2457: 
1.35      matthew  2458: =cut
                   2459: 
                   2460: #-------------------------------------------
1.34      matthew  2461: sub select_dom_form {
1.1121    raeburn  2462:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2463:     if ($onchange) {
1.874     raeburn  2464:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2465:     }
1.1121    raeburn  2466:     my (@domains,%exclude);
1.910     raeburn  2467:     if (ref($incdoms) eq 'ARRAY') {
                   2468:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2469:     } else {
                   2470:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2471:     }
1.90      www      2472:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2473:     if (ref($excdoms) eq 'ARRAY') {
                   2474:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2475:     }
1.743     raeburn  2476:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2477:     foreach my $dom (@domains) {
1.1121    raeburn  2478:         next if ($exclude{$dom});
1.356     albertel 2479:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2480:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2481:         if ($showdomdesc) {
                   2482:             if ($dom ne '') {
                   2483:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2484:                 if ($domdesc ne '') {
                   2485:                     $selectdomain .= ' ('.$domdesc.')';
                   2486:                 }
                   2487:             } 
                   2488:         }
                   2489:         $selectdomain .= "</option>\n";
1.34      matthew  2490:     }
                   2491:     $selectdomain.="</select>";
                   2492:     return $selectdomain;
                   2493: }
                   2494: 
1.35      matthew  2495: #-------------------------------------------
                   2496: 
1.45      matthew  2497: =pod
                   2498: 
1.648     raeburn  2499: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2500: 
1.586     raeburn  2501: input: 4 arguments (two required, two optional) - 
                   2502:     $domain - domain of new user
                   2503:     $name - name of form element
                   2504:     $default - Value of 'default' causes a default item to be first 
                   2505:                             option, and selected by default. 
                   2506:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2507:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2508: output: returns 2 items: 
1.586     raeburn  2509: (a) form element which contains either:
                   2510:    (i) <select name="$name">
                   2511:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2512:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2513:        </select>
                   2514:        form item if there are multiple library servers in $domain, or
                   2515:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2516:        if there is only one library server in $domain.
                   2517: 
                   2518: (b) number of library servers found.
                   2519: 
                   2520: See loncreateuser.pm for example of use.
1.35      matthew  2521: 
                   2522: =cut
                   2523: 
                   2524: #-------------------------------------------
1.586     raeburn  2525: sub home_server_form_item {
                   2526:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2527:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2528:     my $result;
                   2529:     my $numlib = keys(%servers);
                   2530:     if ($numlib > 1) {
                   2531:         $result .= '<select name="'.$name.'" />'."\n";
                   2532:         if ($default) {
1.804     bisitz   2533:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2534:                        '</option>'."\n";
                   2535:         }
                   2536:         foreach my $hostid (sort(keys(%servers))) {
                   2537:             $result.= '<option value="'.$hostid.'">'.
                   2538: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2539:         }
                   2540:         $result .= '</select>'."\n";
                   2541:     } elsif ($numlib == 1) {
                   2542:         my $hostid;
                   2543:         foreach my $item (keys(%servers)) {
                   2544:             $hostid = $item;
                   2545:         }
                   2546:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2547:                    $hostid.'" />';
                   2548:                    if (!$hide) {
                   2549:                        $result .= $hostid.' '.$servers{$hostid};
                   2550:                    }
                   2551:                    $result .= "\n";
                   2552:     } elsif ($default) {
                   2553:         $result .= '<input type="hidden" name="'.$name.
                   2554:                    '" value="default" />';
                   2555:                    if (!$hide) {
                   2556:                        $result .= &mt('default');
                   2557:                    }
                   2558:                    $result .= "\n";
1.33      matthew  2559:     }
1.586     raeburn  2560:     return ($result,$numlib);
1.33      matthew  2561: }
1.112     bowersj2 2562: 
                   2563: =pod
                   2564: 
1.534     albertel 2565: =back 
                   2566: 
1.112     bowersj2 2567: =cut
1.87      matthew  2568: 
                   2569: ###############################################################
1.112     bowersj2 2570: ##                  Decoding User Agent                      ##
1.87      matthew  2571: ###############################################################
                   2572: 
                   2573: =pod
                   2574: 
1.112     bowersj2 2575: =head1 Decoding the User Agent
                   2576: 
                   2577: =over 4
                   2578: 
                   2579: =item * &decode_user_agent()
1.87      matthew  2580: 
                   2581: Inputs: $r
                   2582: 
                   2583: Outputs:
                   2584: 
                   2585: =over 4
                   2586: 
1.112     bowersj2 2587: =item * $httpbrowser
1.87      matthew  2588: 
1.112     bowersj2 2589: =item * $clientbrowser
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientversion
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientmathml
1.87      matthew  2594: 
1.112     bowersj2 2595: =item * $clientunicode
1.87      matthew  2596: 
1.112     bowersj2 2597: =item * $clientos
1.87      matthew  2598: 
1.1137    raeburn  2599: =item * $clientmobile
                   2600: 
1.1141    raeburn  2601: =item * $clientinfo
                   2602: 
1.1194    raeburn  2603: =item * $clientosversion
                   2604: 
1.87      matthew  2605: =back
                   2606: 
1.157     matthew  2607: =back 
                   2608: 
1.87      matthew  2609: =cut
                   2610: 
                   2611: ###############################################################
                   2612: ###############################################################
                   2613: sub decode_user_agent {
1.247     albertel 2614:     my ($r)=@_;
1.87      matthew  2615:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2616:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2617:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2618:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2619:     my $clientbrowser='unknown';
                   2620:     my $clientversion='0';
                   2621:     my $clientmathml='';
                   2622:     my $clientunicode='0';
1.1137    raeburn  2623:     my $clientmobile=0;
1.1194    raeburn  2624:     my $clientosversion='';
1.87      matthew  2625:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2626:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2627: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2628: 	    $clientbrowser=$bname;
                   2629:             $httpbrowser=~/$vreg/i;
                   2630: 	    $clientversion=$1;
                   2631:             $clientmathml=($clientversion>=$minv);
                   2632:             $clientunicode=($clientversion>=$univ);
                   2633: 	}
                   2634:     }
                   2635:     my $clientos='unknown';
1.1141    raeburn  2636:     my $clientinfo;
1.87      matthew  2637:     if (($httpbrowser=~/linux/i) ||
                   2638:         ($httpbrowser=~/unix/i) ||
                   2639:         ($httpbrowser=~/ux/i) ||
                   2640:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2641:     if (($httpbrowser=~/vax/i) ||
                   2642:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2643:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2644:     if (($httpbrowser=~/mac/i) ||
                   2645:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2646:     if ($httpbrowser=~/win/i) {
                   2647:         $clientos='win';
                   2648:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2649:             $clientosversion = $1;
                   2650:         }
                   2651:     }
1.87      matthew  2652:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2653:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2654:         $clientmobile=lc($1);
                   2655:     }
1.1141    raeburn  2656:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2657:         $clientinfo = 'firefox-'.$1;
                   2658:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2659:         $clientinfo = 'chromeframe-'.$1;
                   2660:     }
1.87      matthew  2661:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2662:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2663:             $clientosversion);
1.87      matthew  2664: }
                   2665: 
1.32      matthew  2666: ###############################################################
                   2667: ##    Authentication changing form generation subroutines    ##
                   2668: ###############################################################
                   2669: ##
                   2670: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2671: ## hash, and have reasonable default values.
                   2672: ##
                   2673: ##    formname = the name given in the <form> tag.
1.35      matthew  2674: #-------------------------------------------
                   2675: 
1.45      matthew  2676: =pod
                   2677: 
1.112     bowersj2 2678: =head1 Authentication Routines
                   2679: 
                   2680: =over 4
                   2681: 
1.648     raeburn  2682: =item * &authform_xxxxxx()
1.35      matthew  2683: 
                   2684: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2685: handle some of the conveniences required for authentication forms.  
                   2686: This is not an optimal method, but it works.  
                   2687: 
                   2688: =over 4
                   2689: 
1.112     bowersj2 2690: =item * authform_header
1.35      matthew  2691: 
1.112     bowersj2 2692: =item * authform_authorwarning
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_nochange
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_kerberos
1.35      matthew  2697: 
1.112     bowersj2 2698: =item * authform_internal
1.35      matthew  2699: 
1.112     bowersj2 2700: =item * authform_filesystem
1.35      matthew  2701: 
                   2702: =back
                   2703: 
1.648     raeburn  2704: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2705: 
1.35      matthew  2706: =cut
                   2707: 
                   2708: #-------------------------------------------
1.32      matthew  2709: sub authform_header{  
                   2710:     my %in = (
                   2711:         formname => 'cu',
1.80      albertel 2712:         kerb_def_dom => '',
1.32      matthew  2713:         @_,
                   2714:     );
                   2715:     $in{'formname'} = 'document.' . $in{'formname'};
                   2716:     my $result='';
1.80      albertel 2717: 
                   2718: #---------------------------------------------- Code for upper case translation
                   2719:     my $Javascript_toUpperCase;
                   2720:     unless ($in{kerb_def_dom}) {
                   2721:         $Javascript_toUpperCase =<<"END";
                   2722:         switch (choice) {
                   2723:            case 'krb': currentform.elements[choicearg].value =
                   2724:                currentform.elements[choicearg].value.toUpperCase();
                   2725:                break;
                   2726:            default:
                   2727:         }
                   2728: END
                   2729:     } else {
                   2730:         $Javascript_toUpperCase = "";
                   2731:     }
                   2732: 
1.165     raeburn  2733:     my $radioval = "'nochange'";
1.591     raeburn  2734:     if (defined($in{'curr_authtype'})) {
                   2735:         if ($in{'curr_authtype'} ne '') {
                   2736:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2737:         }
1.174     matthew  2738:     }
1.165     raeburn  2739:     my $argfield = 'null';
1.591     raeburn  2740:     if (defined($in{'mode'})) {
1.165     raeburn  2741:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2742:             if (defined($in{'curr_autharg'})) {
                   2743:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2744:                     $argfield = "'$in{'curr_autharg'}'";
                   2745:                 }
                   2746:             }
                   2747:         }
                   2748:     }
                   2749: 
1.32      matthew  2750:     $result.=<<"END";
                   2751: var current = new Object();
1.165     raeburn  2752: current.radiovalue = $radioval;
                   2753: current.argfield = $argfield;
1.32      matthew  2754: 
                   2755: function changed_radio(choice,currentform) {
                   2756:     var choicearg = choice + 'arg';
                   2757:     // If a radio button in changed, we need to change the argfield
                   2758:     if (current.radiovalue != choice) {
                   2759:         current.radiovalue = choice;
                   2760:         if (current.argfield != null) {
                   2761:             currentform.elements[current.argfield].value = '';
                   2762:         }
                   2763:         if (choice == 'nochange') {
                   2764:             current.argfield = null;
                   2765:         } else {
                   2766:             current.argfield = choicearg;
                   2767:             switch(choice) {
                   2768:                 case 'krb': 
                   2769:                     currentform.elements[current.argfield].value = 
                   2770:                         "$in{'kerb_def_dom'}";
                   2771:                 break;
                   2772:               default:
                   2773:                 break;
                   2774:             }
                   2775:         }
                   2776:     }
                   2777:     return;
                   2778: }
1.22      www      2779: 
1.32      matthew  2780: function changed_text(choice,currentform) {
                   2781:     var choicearg = choice + 'arg';
                   2782:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2783:         $Javascript_toUpperCase
1.32      matthew  2784:         // clear old field
                   2785:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2786:             currentform.elements[current.argfield].value = '';
                   2787:         }
                   2788:         current.argfield = choicearg;
                   2789:     }
                   2790:     set_auth_radio_buttons(choice,currentform);
                   2791:     return;
1.20      www      2792: }
1.32      matthew  2793: 
                   2794: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2795:     var numauthchoices = currentform.login.length;
                   2796:     if (typeof numauthchoices  == "undefined") {
                   2797:         return;
                   2798:     } 
1.32      matthew  2799:     var i=0;
1.986     raeburn  2800:     while (i < numauthchoices) {
1.32      matthew  2801:         if (currentform.login[i].value == newvalue) { break; }
                   2802:         i++;
                   2803:     }
1.986     raeburn  2804:     if (i == numauthchoices) {
1.32      matthew  2805:         return;
                   2806:     }
                   2807:     current.radiovalue = newvalue;
                   2808:     currentform.login[i].checked = true;
                   2809:     return;
                   2810: }
                   2811: END
                   2812:     return $result;
                   2813: }
                   2814: 
1.1106    raeburn  2815: sub authform_authorwarning {
1.32      matthew  2816:     my $result='';
1.144     matthew  2817:     $result='<i>'.
                   2818:         &mt('As a general rule, only authors or co-authors should be '.
                   2819:             'filesystem authenticated '.
                   2820:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2821:     return $result;
                   2822: }
                   2823: 
1.1106    raeburn  2824: sub authform_nochange {
1.32      matthew  2825:     my %in = (
                   2826:               formname => 'document.cu',
                   2827:               kerb_def_dom => 'MSU.EDU',
                   2828:               @_,
                   2829:           );
1.1106    raeburn  2830:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2831:     my $result;
1.1104    raeburn  2832:     if (!$authnum) {
1.1105    raeburn  2833:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2834:     } else {
                   2835:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2836:                   '<input type="radio" name="login" value="nochange" '.
                   2837:                   'checked="checked" onclick="'.
1.281     albertel 2838:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2839: 	    '</label>';
1.586     raeburn  2840:     }
1.32      matthew  2841:     return $result;
                   2842: }
                   2843: 
1.591     raeburn  2844: sub authform_kerberos {
1.32      matthew  2845:     my %in = (
                   2846:               formname => 'document.cu',
                   2847:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2848:               kerb_def_auth => 'krb4',
1.32      matthew  2849:               @_,
                   2850:               );
1.586     raeburn  2851:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2852:         $autharg,$jscall);
1.1106    raeburn  2853:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2854:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2855:        $check5 = ' checked="checked"';
1.80      albertel 2856:     } else {
1.772     bisitz   2857:        $check4 = ' checked="checked"';
1.80      albertel 2858:     }
1.165     raeburn  2859:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2860:     if (defined($in{'curr_authtype'})) {
                   2861:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2862:             $krbcheck = ' checked="checked"';
1.623     raeburn  2863:             if (defined($in{'mode'})) {
                   2864:                 if ($in{'mode'} eq 'modifyuser') {
                   2865:                     $krbcheck = '';
                   2866:                 }
                   2867:             }
1.591     raeburn  2868:             if (defined($in{'curr_kerb_ver'})) {
                   2869:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2870:                     $check5 = ' checked="checked"';
1.591     raeburn  2871:                     $check4 = '';
                   2872:                 } else {
1.772     bisitz   2873:                     $check4 = ' checked="checked"';
1.591     raeburn  2874:                     $check5 = '';
                   2875:                 }
1.586     raeburn  2876:             }
1.591     raeburn  2877:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2878:                 $krbarg = $in{'curr_autharg'};
                   2879:             }
1.586     raeburn  2880:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2881:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2882:                     $result = 
                   2883:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2884:         $in{'curr_autharg'},$krbver);
                   2885:                 } else {
                   2886:                     $result =
                   2887:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2888:                 }
                   2889:                 return $result; 
                   2890:             }
                   2891:         }
                   2892:     } else {
                   2893:         if ($authnum == 1) {
1.784     bisitz   2894:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2895:         }
                   2896:     }
1.586     raeburn  2897:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2898:         return;
1.587     raeburn  2899:     } elsif ($authtype eq '') {
1.591     raeburn  2900:         if (defined($in{'mode'})) {
1.587     raeburn  2901:             if ($in{'mode'} eq 'modifycourse') {
                   2902:                 if ($authnum == 1) {
1.1104    raeburn  2903:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2904:                 }
                   2905:             }
                   2906:         }
1.586     raeburn  2907:     }
                   2908:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2909:     if ($authtype eq '') {
                   2910:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2911:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2912:                     $krbcheck.' />';
                   2913:     }
                   2914:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2915:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2916:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2917:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2918:          $in{'curr_authtype'} eq 'krb4')) {
                   2919:         $result .= &mt
1.144     matthew  2920:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2921:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2922:          '<label>'.$authtype,
1.281     albertel 2923:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2924:              'value="'.$krbarg.'" '.
1.144     matthew  2925:              'onchange="'.$jscall.'" />',
1.281     albertel 2926:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2927:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2928: 	 '</label>');
1.586     raeburn  2929:     } elsif ($can_assign{'krb4'}) {
                   2930:         $result .= &mt
                   2931:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2932:          '[_3] Version 4 [_4]',
                   2933:          '<label>'.$authtype,
                   2934:          '</label><input type="text" size="10" name="krbarg" '.
                   2935:              'value="'.$krbarg.'" '.
                   2936:              'onchange="'.$jscall.'" />',
                   2937:          '<label><input type="hidden" name="krbver" value="4" />',
                   2938:          '</label>');
                   2939:     } elsif ($can_assign{'krb5'}) {
                   2940:         $result .= &mt
                   2941:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2942:          '[_3] Version 5 [_4]',
                   2943:          '<label>'.$authtype,
                   2944:          '</label><input type="text" size="10" name="krbarg" '.
                   2945:              'value="'.$krbarg.'" '.
                   2946:              'onchange="'.$jscall.'" />',
                   2947:          '<label><input type="hidden" name="krbver" value="5" />',
                   2948:          '</label>');
                   2949:     }
1.32      matthew  2950:     return $result;
                   2951: }
                   2952: 
1.1106    raeburn  2953: sub authform_internal {
1.586     raeburn  2954:     my %in = (
1.32      matthew  2955:                 formname => 'document.cu',
                   2956:                 kerb_def_dom => 'MSU.EDU',
                   2957:                 @_,
                   2958:                 );
1.586     raeburn  2959:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2960:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2961:     if (defined($in{'curr_authtype'})) {
                   2962:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2963:             if ($can_assign{'int'}) {
1.772     bisitz   2964:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2965:                 if (defined($in{'mode'})) {
                   2966:                     if ($in{'mode'} eq 'modifyuser') {
                   2967:                         $intcheck = '';
                   2968:                     }
                   2969:                 }
1.591     raeburn  2970:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2971:                     $intarg = $in{'curr_autharg'};
                   2972:                 }
                   2973:             } else {
                   2974:                 $result = &mt('Currently internally authenticated.');
                   2975:                 return $result;
1.165     raeburn  2976:             }
                   2977:         }
1.586     raeburn  2978:     } else {
                   2979:         if ($authnum == 1) {
1.784     bisitz   2980:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2981:         }
                   2982:     }
                   2983:     if (!$can_assign{'int'}) {
                   2984:         return;
1.587     raeburn  2985:     } elsif ($authtype eq '') {
1.591     raeburn  2986:         if (defined($in{'mode'})) {
1.587     raeburn  2987:             if ($in{'mode'} eq 'modifycourse') {
                   2988:                 if ($authnum == 1) {
1.1104    raeburn  2989:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2990:                 }
                   2991:             }
                   2992:         }
1.165     raeburn  2993:     }
1.586     raeburn  2994:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2995:     if ($authtype eq '') {
                   2996:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2997:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2998:     }
1.605     bisitz   2999:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  3000:                $intarg.'" onchange="'.$jscall.'" />';
                   3001:     $result = &mt
1.144     matthew  3002:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3003:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   3004:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  3005:     return $result;
                   3006: }
                   3007: 
1.1104    raeburn  3008: sub authform_local {
1.32      matthew  3009:     my %in = (
                   3010:               formname => 'document.cu',
                   3011:               kerb_def_dom => 'MSU.EDU',
                   3012:               @_,
                   3013:               );
1.586     raeburn  3014:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3015:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3016:     if (defined($in{'curr_authtype'})) {
                   3017:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3018:             if ($can_assign{'loc'}) {
1.772     bisitz   3019:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3020:                 if (defined($in{'mode'})) {
                   3021:                     if ($in{'mode'} eq 'modifyuser') {
                   3022:                         $loccheck = '';
                   3023:                     }
                   3024:                 }
1.591     raeburn  3025:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3026:                     $locarg = $in{'curr_autharg'};
                   3027:                 }
                   3028:             } else {
                   3029:                 $result = &mt('Currently using local (institutional) authentication.');
                   3030:                 return $result;
1.165     raeburn  3031:             }
                   3032:         }
1.586     raeburn  3033:     } else {
                   3034:         if ($authnum == 1) {
1.784     bisitz   3035:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3036:         }
                   3037:     }
                   3038:     if (!$can_assign{'loc'}) {
                   3039:         return;
1.587     raeburn  3040:     } elsif ($authtype eq '') {
1.591     raeburn  3041:         if (defined($in{'mode'})) {
1.587     raeburn  3042:             if ($in{'mode'} eq 'modifycourse') {
                   3043:                 if ($authnum == 1) {
1.1104    raeburn  3044:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3045:                 }
                   3046:             }
                   3047:         }
1.165     raeburn  3048:     }
1.586     raeburn  3049:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3050:     if ($authtype eq '') {
                   3051:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3052:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3053:                     $jscall.'" />';
                   3054:     }
                   3055:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3056:                $locarg.'" onchange="'.$jscall.'" />';
                   3057:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3058:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3059:     return $result;
                   3060: }
                   3061: 
1.1106    raeburn  3062: sub authform_filesystem {
1.32      matthew  3063:     my %in = (
                   3064:               formname => 'document.cu',
                   3065:               kerb_def_dom => 'MSU.EDU',
                   3066:               @_,
                   3067:               );
1.586     raeburn  3068:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3069:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3070:     if (defined($in{'curr_authtype'})) {
                   3071:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3072:             if ($can_assign{'fsys'}) {
1.772     bisitz   3073:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3074:                 if (defined($in{'mode'})) {
                   3075:                     if ($in{'mode'} eq 'modifyuser') {
                   3076:                         $fsyscheck = '';
                   3077:                     }
                   3078:                 }
1.586     raeburn  3079:             } else {
                   3080:                 $result = &mt('Currently Filesystem Authenticated.');
                   3081:                 return $result;
                   3082:             }           
                   3083:         }
                   3084:     } else {
                   3085:         if ($authnum == 1) {
1.784     bisitz   3086:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3087:         }
                   3088:     }
                   3089:     if (!$can_assign{'fsys'}) {
                   3090:         return;
1.587     raeburn  3091:     } elsif ($authtype eq '') {
1.591     raeburn  3092:         if (defined($in{'mode'})) {
1.587     raeburn  3093:             if ($in{'mode'} eq 'modifycourse') {
                   3094:                 if ($authnum == 1) {
1.1104    raeburn  3095:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3096:                 }
                   3097:             }
                   3098:         }
1.586     raeburn  3099:     }
                   3100:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3101:     if ($authtype eq '') {
                   3102:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3103:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3104:                     $jscall.'" />';
                   3105:     }
                   3106:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3107:                ' onchange="'.$jscall.'" />';
                   3108:     $result = &mt
1.144     matthew  3109:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3110:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3111:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3112:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3113:                   'onchange="'.$jscall.'" />');
1.32      matthew  3114:     return $result;
                   3115: }
                   3116: 
1.586     raeburn  3117: sub get_assignable_auth {
                   3118:     my ($dom) = @_;
                   3119:     if ($dom eq '') {
                   3120:         $dom = $env{'request.role.domain'};
                   3121:     }
                   3122:     my %can_assign = (
                   3123:                           krb4 => 1,
                   3124:                           krb5 => 1,
                   3125:                           int  => 1,
                   3126:                           loc  => 1,
                   3127:                      );
                   3128:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3129:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3130:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3131:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3132:             my $context;
                   3133:             if ($env{'request.role'} =~ /^au/) {
                   3134:                 $context = 'author';
                   3135:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3136:                 $context = 'domain';
                   3137:             } elsif ($env{'request.course.id'}) {
                   3138:                 $context = 'course';
                   3139:             }
                   3140:             if ($context) {
                   3141:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3142:                    %can_assign = %{$authhash->{$context}}; 
                   3143:                 }
                   3144:             }
                   3145:         }
                   3146:     }
                   3147:     my $authnum = 0;
                   3148:     foreach my $key (keys(%can_assign)) {
                   3149:         if ($can_assign{$key}) {
                   3150:             $authnum ++;
                   3151:         }
                   3152:     }
                   3153:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3154:         $authnum --;
                   3155:     }
                   3156:     return ($authnum,%can_assign);
                   3157: }
                   3158: 
1.80      albertel 3159: ###############################################################
                   3160: ##    Get Kerberos Defaults for Domain                 ##
                   3161: ###############################################################
                   3162: ##
                   3163: ## Returns default kerberos version and an associated argument
                   3164: ## as listed in file domain.tab. If not listed, provides
                   3165: ## appropriate default domain and kerberos version.
                   3166: ##
                   3167: #-------------------------------------------
                   3168: 
                   3169: =pod
                   3170: 
1.648     raeburn  3171: =item * &get_kerberos_defaults()
1.80      albertel 3172: 
                   3173: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3174: version and domain. If not found, it defaults to version 4 and the 
                   3175: domain of the server.
1.80      albertel 3176: 
1.648     raeburn  3177: =over 4
                   3178: 
1.80      albertel 3179: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3180: 
1.648     raeburn  3181: =back
                   3182: 
                   3183: =back
                   3184: 
1.80      albertel 3185: =cut
                   3186: 
                   3187: #-------------------------------------------
                   3188: sub get_kerberos_defaults {
                   3189:     my $domain=shift;
1.641     raeburn  3190:     my ($krbdef,$krbdefdom);
                   3191:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3192:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3193:         $krbdef = $domdefaults{'auth_def'};
                   3194:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3195:     } else {
1.80      albertel 3196:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3197:         my $krbdefdom=$1;
                   3198:         $krbdefdom=~tr/a-z/A-Z/;
                   3199:         $krbdef = "krb4";
                   3200:     }
                   3201:     return ($krbdef,$krbdefdom);
                   3202: }
1.112     bowersj2 3203: 
1.32      matthew  3204: 
1.46      matthew  3205: ###############################################################
                   3206: ##                Thesaurus Functions                        ##
                   3207: ###############################################################
1.20      www      3208: 
1.46      matthew  3209: =pod
1.20      www      3210: 
1.112     bowersj2 3211: =head1 Thesaurus Functions
                   3212: 
                   3213: =over 4
                   3214: 
1.648     raeburn  3215: =item * &initialize_keywords()
1.46      matthew  3216: 
                   3217: Initializes the package variable %Keywords if it is empty.  Uses the
                   3218: package variable $thesaurus_db_file.
                   3219: 
                   3220: =cut
                   3221: 
                   3222: ###################################################
                   3223: 
                   3224: sub initialize_keywords {
                   3225:     return 1 if (scalar keys(%Keywords));
                   3226:     # If we are here, %Keywords is empty, so fill it up
                   3227:     #   Make sure the file we need exists...
                   3228:     if (! -e $thesaurus_db_file) {
                   3229:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3230:                                  " failed because it does not exist");
                   3231:         return 0;
                   3232:     }
                   3233:     #   Set up the hash as a database
                   3234:     my %thesaurus_db;
                   3235:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3236:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3237:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3238:                                  $thesaurus_db_file);
                   3239:         return 0;
                   3240:     } 
                   3241:     #  Get the average number of appearances of a word.
                   3242:     my $avecount = $thesaurus_db{'average.count'};
                   3243:     #  Put keywords (those that appear > average) into %Keywords
                   3244:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3245:         my ($count,undef) = split /:/,$data;
                   3246:         $Keywords{$word}++ if ($count > $avecount);
                   3247:     }
                   3248:     untie %thesaurus_db;
                   3249:     # Remove special values from %Keywords.
1.356     albertel 3250:     foreach my $value ('total.count','average.count') {
                   3251:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3252:   }
1.46      matthew  3253:     return 1;
                   3254: }
                   3255: 
                   3256: ###################################################
                   3257: 
                   3258: =pod
                   3259: 
1.648     raeburn  3260: =item * &keyword($word)
1.46      matthew  3261: 
                   3262: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3263: than the average number of times in the thesaurus database.  Calls 
                   3264: &initialize_keywords
                   3265: 
                   3266: =cut
                   3267: 
                   3268: ###################################################
1.20      www      3269: 
                   3270: sub keyword {
1.46      matthew  3271:     return if (!&initialize_keywords());
                   3272:     my $word=lc(shift());
                   3273:     $word=~s/\W//g;
                   3274:     return exists($Keywords{$word});
1.20      www      3275: }
1.46      matthew  3276: 
                   3277: ###############################################################
                   3278: 
                   3279: =pod 
1.20      www      3280: 
1.648     raeburn  3281: =item * &get_related_words()
1.46      matthew  3282: 
1.160     matthew  3283: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3284: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3285: will be returned.  The order of the words returned is determined by the
                   3286: database which holds them.
                   3287: 
                   3288: Uses global $thesaurus_db_file.
                   3289: 
1.1057    foxr     3290: 
1.46      matthew  3291: =cut
                   3292: 
                   3293: ###############################################################
                   3294: sub get_related_words {
                   3295:     my $keyword = shift;
                   3296:     my %thesaurus_db;
                   3297:     if (! -e $thesaurus_db_file) {
                   3298:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3299:                                  "failed because the file does not exist");
                   3300:         return ();
                   3301:     }
                   3302:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3303:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3304:         return ();
                   3305:     } 
                   3306:     my @Words=();
1.429     www      3307:     my $count=0;
1.46      matthew  3308:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3309: 	# The first element is the number of times
                   3310: 	# the word appears.  We do not need it now.
1.429     www      3311: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3312: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3313: 	my $threshold=$mostfrequentcount/10;
                   3314:         foreach my $possibleword (@RelatedWords) {
                   3315:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3316:             if ($wordcount>$threshold) {
                   3317: 		push(@Words,$word);
                   3318:                 $count++;
                   3319:                 if ($count>10) { last; }
                   3320: 	    }
1.20      www      3321:         }
                   3322:     }
1.46      matthew  3323:     untie %thesaurus_db;
                   3324:     return @Words;
1.14      harris41 3325: }
1.1090    foxr     3326: ###############################################################
                   3327: #
                   3328: #  Spell checking
                   3329: #
                   3330: 
                   3331: =pod
                   3332: 
1.1142    raeburn  3333: =back
                   3334: 
1.1090    foxr     3335: =head1 Spell checking
                   3336: 
                   3337: =over 4
                   3338: 
                   3339: =item * &check_spelling($wordlist $language)
                   3340: 
                   3341: Takes a string containing words and feeds it to an external
                   3342: spellcheck program via a pipeline. Returns a string containing
                   3343: them mis-spelled words.
                   3344: 
                   3345: Parameters:
                   3346: 
                   3347: =over 4
                   3348: 
                   3349: =item - $wordlist
                   3350: 
                   3351: String that will be fed into the spellcheck program.
                   3352: 
                   3353: =item - $language
                   3354: 
                   3355: Language string that specifies the language for which the spell
                   3356: check will be performed.
                   3357: 
                   3358: =back
                   3359: 
                   3360: =back
                   3361: 
                   3362: Note: This sub assumes that aspell is installed.
                   3363: 
                   3364: 
                   3365: =cut
                   3366: 
1.46      matthew  3367: 
1.1090    foxr     3368: sub check_spelling {
                   3369:     my ($wordlist, $language) = @_;
1.1091    foxr     3370:     my @misspellings;
                   3371:     
                   3372:     # Generate the speller and set the langauge.
                   3373:     # if explicitly selected:
1.1090    foxr     3374: 
1.1091    foxr     3375:     my $speller = Text::Aspell->new;
1.1090    foxr     3376:     if ($language) {
1.1091    foxr     3377: 	$speller->set_option('lang', $language);
1.1090    foxr     3378:     }
                   3379: 
1.1091    foxr     3380:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3381: 
1.1091    foxr     3382:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3383: 
1.1091    foxr     3384:     foreach my $word (@words) {
                   3385: 	if(! $speller->check($word)) {
                   3386: 	    push(@misspellings, $word);
1.1090    foxr     3387: 	}
                   3388:     }
1.1091    foxr     3389:     return join(' ', @misspellings);
                   3390:     
1.1090    foxr     3391: }
                   3392: 
1.61      www      3393: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3394: =pod
                   3395: 
1.112     bowersj2 3396: =head1 User Name Functions
                   3397: 
                   3398: =over 4
                   3399: 
1.648     raeburn  3400: =item * &plainname($uname,$udom,$first)
1.81      albertel 3401: 
1.112     bowersj2 3402: Takes a users logon name and returns it as a string in
1.226     albertel 3403: "first middle last generation" form 
                   3404: if $first is set to 'lastname' then it returns it as
                   3405: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3406: 
                   3407: =cut
1.61      www      3408: 
1.295     www      3409: 
1.81      albertel 3410: ###############################################################
1.61      www      3411: sub plainname {
1.226     albertel 3412:     my ($uname,$udom,$first)=@_;
1.537     albertel 3413:     return if (!defined($uname) || !defined($udom));
1.295     www      3414:     my %names=&getnames($uname,$udom);
1.226     albertel 3415:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3416: 					  $names{'middlename'},
                   3417: 					  $names{'lastname'},
                   3418: 					  $names{'generation'},$first);
                   3419:     $name=~s/^\s+//;
1.62      www      3420:     $name=~s/\s+$//;
                   3421:     $name=~s/\s+/ /g;
1.353     albertel 3422:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3423:     return $name;
1.61      www      3424: }
1.66      www      3425: 
                   3426: # -------------------------------------------------------------------- Nickname
1.81      albertel 3427: =pod
                   3428: 
1.648     raeburn  3429: =item * &nickname($uname,$udom)
1.81      albertel 3430: 
                   3431: Gets a users name and returns it as a string as
                   3432: 
                   3433: "&quot;nickname&quot;"
1.66      www      3434: 
1.81      albertel 3435: if the user has a nickname or
                   3436: 
                   3437: "first middle last generation"
                   3438: 
                   3439: if the user does not
                   3440: 
                   3441: =cut
1.66      www      3442: 
                   3443: sub nickname {
                   3444:     my ($uname,$udom)=@_;
1.537     albertel 3445:     return if (!defined($uname) || !defined($udom));
1.295     www      3446:     my %names=&getnames($uname,$udom);
1.68      albertel 3447:     my $name=$names{'nickname'};
1.66      www      3448:     if ($name) {
                   3449:        $name='&quot;'.$name.'&quot;'; 
                   3450:     } else {
                   3451:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3452: 	     $names{'lastname'}.' '.$names{'generation'};
                   3453:        $name=~s/\s+$//;
                   3454:        $name=~s/\s+/ /g;
                   3455:     }
                   3456:     return $name;
                   3457: }
                   3458: 
1.295     www      3459: sub getnames {
                   3460:     my ($uname,$udom)=@_;
1.537     albertel 3461:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3462:     if ($udom eq 'public' && $uname eq 'public') {
                   3463: 	return ('lastname' => &mt('Public'));
                   3464:     }
1.295     www      3465:     my $id=$uname.':'.$udom;
                   3466:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3467:     if ($cached) {
                   3468: 	return %{$names};
                   3469:     } else {
                   3470: 	my %loadnames=&Apache::lonnet::get('environment',
                   3471:                     ['firstname','middlename','lastname','generation','nickname'],
                   3472: 					 $udom,$uname);
                   3473: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3474: 	return %loadnames;
                   3475:     }
                   3476: }
1.61      www      3477: 
1.542     raeburn  3478: # -------------------------------------------------------------------- getemails
1.648     raeburn  3479: 
1.542     raeburn  3480: =pod
                   3481: 
1.648     raeburn  3482: =item * &getemails($uname,$udom)
1.542     raeburn  3483: 
                   3484: Gets a user's email information and returns it as a hash with keys:
                   3485: notification, critnotification, permanentemail
                   3486: 
                   3487: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3488: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3489:  
1.648     raeburn  3490: 
1.542     raeburn  3491: =cut
                   3492: 
1.648     raeburn  3493: 
1.466     albertel 3494: sub getemails {
                   3495:     my ($uname,$udom)=@_;
                   3496:     if ($udom eq 'public' && $uname eq 'public') {
                   3497: 	return;
                   3498:     }
1.467     www      3499:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3500:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3501:     my $id=$uname.':'.$udom;
                   3502:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3503:     if ($cached) {
                   3504: 	return %{$names};
                   3505:     } else {
                   3506: 	my %loadnames=&Apache::lonnet::get('environment',
                   3507:                     			   ['notification','critnotification',
                   3508: 					    'permanentemail'],
                   3509: 					   $udom,$uname);
                   3510: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3511: 	return %loadnames;
                   3512:     }
                   3513: }
                   3514: 
1.551     albertel 3515: sub flush_email_cache {
                   3516:     my ($uname,$udom)=@_;
                   3517:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3518:     if (!$uname) { $uname=$env{'user.name'};   }
                   3519:     return if ($udom eq 'public' && $uname eq 'public');
                   3520:     my $id=$uname.':'.$udom;
                   3521:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3522: }
                   3523: 
1.728     raeburn  3524: # -------------------------------------------------------------------- getlangs
                   3525: 
                   3526: =pod
                   3527: 
                   3528: =item * &getlangs($uname,$udom)
                   3529: 
                   3530: Gets a user's language preference and returns it as a hash with key:
                   3531: language.
                   3532: 
                   3533: =cut
                   3534: 
                   3535: 
                   3536: sub getlangs {
                   3537:     my ($uname,$udom) = @_;
                   3538:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3539:     if (!$uname) { $uname=$env{'user.name'};   }
                   3540:     my $id=$uname.':'.$udom;
                   3541:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3542:     if ($cached) {
                   3543:         return %{$langs};
                   3544:     } else {
                   3545:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3546:                                            $udom,$uname);
                   3547:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3548:         return %loadlangs;
                   3549:     }
                   3550: }
                   3551: 
                   3552: sub flush_langs_cache {
                   3553:     my ($uname,$udom)=@_;
                   3554:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3555:     if (!$uname) { $uname=$env{'user.name'};   }
                   3556:     return if ($udom eq 'public' && $uname eq 'public');
                   3557:     my $id=$uname.':'.$udom;
                   3558:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3559: }
                   3560: 
1.61      www      3561: # ------------------------------------------------------------------ Screenname
1.81      albertel 3562: 
                   3563: =pod
                   3564: 
1.648     raeburn  3565: =item * &screenname($uname,$udom)
1.81      albertel 3566: 
                   3567: Gets a users screenname and returns it as a string
                   3568: 
                   3569: =cut
1.61      www      3570: 
                   3571: sub screenname {
                   3572:     my ($uname,$udom)=@_;
1.258     albertel 3573:     if ($uname eq $env{'user.name'} &&
                   3574: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3575:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3576:     return $names{'screenname'};
1.62      www      3577: }
                   3578: 
1.212     albertel 3579: 
1.802     bisitz   3580: # ------------------------------------------------------------- Confirm Wrapper
                   3581: =pod
                   3582: 
1.1142    raeburn  3583: =item * &confirmwrapper($message)
1.802     bisitz   3584: 
                   3585: Wrap messages about completion of operation in box
                   3586: 
                   3587: =cut
                   3588: 
                   3589: sub confirmwrapper {
                   3590:     my ($message)=@_;
                   3591:     if ($message) {
                   3592:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3593:                .$message."\n"
                   3594:                .'</div>'."\n";
                   3595:     } else {
                   3596:         return $message;
                   3597:     }
                   3598: }
                   3599: 
1.62      www      3600: # ------------------------------------------------------------- Message Wrapper
                   3601: 
                   3602: sub messagewrapper {
1.369     www      3603:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3604:     return 
1.441     albertel 3605:         '<a href="/adm/email?compose=individual&amp;'.
                   3606:         'recname='.$username.'&amp;recdom='.$domain.
                   3607: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3608:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3609: }
1.802     bisitz   3610: 
1.74      www      3611: # --------------------------------------------------------------- Notes Wrapper
                   3612: 
                   3613: sub noteswrapper {
                   3614:     my ($link,$un,$do)=@_;
                   3615:     return 
1.896     amueller 3616: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3617: }
1.802     bisitz   3618: 
1.62      www      3619: # ------------------------------------------------------------- Aboutme Wrapper
                   3620: 
                   3621: sub aboutmewrapper {
1.1070    raeburn  3622:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3623:     if (!defined($username)  && !defined($domain)) {
                   3624:         return;
                   3625:     }
1.1096    raeburn  3626:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3627: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3628: }
                   3629: 
                   3630: # ------------------------------------------------------------ Syllabus Wrapper
                   3631: 
                   3632: sub syllabuswrapper {
1.707     bisitz   3633:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3634:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3635: }
1.14      harris41 3636: 
1.802     bisitz   3637: # -----------------------------------------------------------------------------
                   3638: 
1.208     matthew  3639: sub track_student_link {
1.887     raeburn  3640:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3641:     my $link ="/adm/trackstudent?";
1.208     matthew  3642:     my $title = 'View recent activity';
                   3643:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3644:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3645:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3646:         $title .= ' of this student';
1.268     albertel 3647:     } 
1.208     matthew  3648:     if (defined($target) && $target !~ /^\s*$/) {
                   3649:         $target = qq{target="$target"};
                   3650:     } else {
                   3651:         $target = '';
                   3652:     }
1.268     albertel 3653:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3654:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3655:     $title = &mt($title);
                   3656:     $linktext = &mt($linktext);
1.448     albertel 3657:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3658: 	&help_open_topic('View_recent_activity');
1.208     matthew  3659: }
                   3660: 
1.781     raeburn  3661: sub slot_reservations_link {
                   3662:     my ($linktext,$sname,$sdom,$target) = @_;
                   3663:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3664:     my $title = 'View slot reservation history';
                   3665:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3666:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3667:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3668:         $title .= ' of this student';
                   3669:     }
                   3670:     if (defined($target) && $target !~ /^\s*$/) {
                   3671:         $target = qq{target="$target"};
                   3672:     } else {
                   3673:         $target = '';
                   3674:     }
                   3675:     $title = &mt($title);
                   3676:     $linktext = &mt($linktext);
                   3677:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3678: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3679: 
                   3680: }
                   3681: 
1.508     www      3682: # ===================================================== Display a student photo
                   3683: 
                   3684: 
1.509     albertel 3685: sub student_image_tag {
1.508     www      3686:     my ($domain,$user)=@_;
                   3687:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3688:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3689: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3690:     } else {
                   3691: 	return '';
                   3692:     }
                   3693: }
                   3694: 
1.112     bowersj2 3695: =pod
                   3696: 
                   3697: =back
                   3698: 
                   3699: =head1 Access .tab File Data
                   3700: 
                   3701: =over 4
                   3702: 
1.648     raeburn  3703: =item * &languageids() 
1.112     bowersj2 3704: 
                   3705: returns list of all language ids
                   3706: 
                   3707: =cut
                   3708: 
1.14      harris41 3709: sub languageids {
1.16      harris41 3710:     return sort(keys(%language));
1.14      harris41 3711: }
                   3712: 
1.112     bowersj2 3713: =pod
                   3714: 
1.648     raeburn  3715: =item * &languagedescription() 
1.112     bowersj2 3716: 
                   3717: returns description of a specified language id
                   3718: 
                   3719: =cut
                   3720: 
1.14      harris41 3721: sub languagedescription {
1.125     www      3722:     my $code=shift;
                   3723:     return  ($supported_language{$code}?'* ':'').
                   3724:             $language{$code}.
1.126     www      3725: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3726: }
                   3727: 
1.1048    foxr     3728: =pod
                   3729: 
                   3730: =item * &plainlanguagedescription
                   3731: 
                   3732: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3733: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3734: 
                   3735: =cut
                   3736: 
1.145     www      3737: sub plainlanguagedescription {
                   3738:     my $code=shift;
                   3739:     return $language{$code};
                   3740: }
                   3741: 
1.1048    foxr     3742: =pod
                   3743: 
                   3744: =item * &supportedlanguagecode
                   3745: 
                   3746: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3747: code.
                   3748: 
                   3749: =cut
                   3750: 
1.145     www      3751: sub supportedlanguagecode {
                   3752:     my $code=shift;
                   3753:     return $supported_language{$code};
1.97      www      3754: }
                   3755: 
1.112     bowersj2 3756: =pod
                   3757: 
1.1048    foxr     3758: =item * &latexlanguage()
                   3759: 
                   3760: Given a language key code returns the correspondnig language to use
                   3761: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3762: is no supported hyphenation for the language code.
                   3763: 
                   3764: =cut
                   3765: 
                   3766: sub latexlanguage {
                   3767:     my $code = shift;
                   3768:     return $latex_language{$code};
                   3769: }
                   3770: 
                   3771: =pod
                   3772: 
                   3773: =item * &latexhyphenation()
                   3774: 
                   3775: Same as above but what's supplied is the language as it might be stored
                   3776: in the metadata.
                   3777: 
                   3778: =cut
                   3779: 
                   3780: sub latexhyphenation {
                   3781:     my $key = shift;
                   3782:     return $latex_language_bykey{$key};
                   3783: }
                   3784: 
                   3785: =pod
                   3786: 
1.648     raeburn  3787: =item * &copyrightids() 
1.112     bowersj2 3788: 
                   3789: returns list of all copyrights
                   3790: 
                   3791: =cut
                   3792: 
                   3793: sub copyrightids {
                   3794:     return sort(keys(%cprtag));
                   3795: }
                   3796: 
                   3797: =pod
                   3798: 
1.648     raeburn  3799: =item * &copyrightdescription() 
1.112     bowersj2 3800: 
                   3801: returns description of a specified copyright id
                   3802: 
                   3803: =cut
                   3804: 
                   3805: sub copyrightdescription {
1.166     www      3806:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3807: }
1.197     matthew  3808: 
                   3809: =pod
                   3810: 
1.648     raeburn  3811: =item * &source_copyrightids() 
1.192     taceyjo1 3812: 
                   3813: returns list of all source copyrights
                   3814: 
                   3815: =cut
                   3816: 
                   3817: sub source_copyrightids {
                   3818:     return sort(keys(%scprtag));
                   3819: }
                   3820: 
                   3821: =pod
                   3822: 
1.648     raeburn  3823: =item * &source_copyrightdescription() 
1.192     taceyjo1 3824: 
                   3825: returns description of a specified source copyright id
                   3826: 
                   3827: =cut
                   3828: 
                   3829: sub source_copyrightdescription {
                   3830:     return &mt($scprtag{shift(@_)});
                   3831: }
1.112     bowersj2 3832: 
                   3833: =pod
                   3834: 
1.648     raeburn  3835: =item * &filecategories() 
1.112     bowersj2 3836: 
                   3837: returns list of all file categories
                   3838: 
                   3839: =cut
                   3840: 
                   3841: sub filecategories {
                   3842:     return sort(keys(%category_extensions));
                   3843: }
                   3844: 
                   3845: =pod
                   3846: 
1.648     raeburn  3847: =item * &filecategorytypes() 
1.112     bowersj2 3848: 
                   3849: returns list of file types belonging to a given file
                   3850: category
                   3851: 
                   3852: =cut
                   3853: 
                   3854: sub filecategorytypes {
1.356     albertel 3855:     my ($cat) = @_;
                   3856:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3857: }
                   3858: 
                   3859: =pod
                   3860: 
1.648     raeburn  3861: =item * &fileembstyle() 
1.112     bowersj2 3862: 
                   3863: returns embedding style for a specified file type
                   3864: 
                   3865: =cut
                   3866: 
                   3867: sub fileembstyle {
                   3868:     return $fe{lc(shift(@_))};
1.169     www      3869: }
                   3870: 
1.351     www      3871: sub filemimetype {
                   3872:     return $fm{lc(shift(@_))};
                   3873: }
                   3874: 
1.169     www      3875: 
                   3876: sub filecategoryselect {
                   3877:     my ($name,$value)=@_;
1.189     matthew  3878:     return &select_form($value,$name,
1.970     raeburn  3879:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3880: }
                   3881: 
                   3882: =pod
                   3883: 
1.648     raeburn  3884: =item * &filedescription() 
1.112     bowersj2 3885: 
                   3886: returns description for a specified file type
                   3887: 
                   3888: =cut
                   3889: 
                   3890: sub filedescription {
1.188     matthew  3891:     my $file_description = $fd{lc(shift())};
                   3892:     $file_description =~ s:([\[\]]):~$1:g;
                   3893:     return &mt($file_description);
1.112     bowersj2 3894: }
                   3895: 
                   3896: =pod
                   3897: 
1.648     raeburn  3898: =item * &filedescriptionex() 
1.112     bowersj2 3899: 
                   3900: returns description for a specified file type with
                   3901: extra formatting
                   3902: 
                   3903: =cut
                   3904: 
                   3905: sub filedescriptionex {
                   3906:     my $ex=shift;
1.188     matthew  3907:     my $file_description = $fd{lc($ex)};
                   3908:     $file_description =~ s:([\[\]]):~$1:g;
                   3909:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3910: }
                   3911: 
                   3912: # End of .tab access
                   3913: =pod
                   3914: 
                   3915: =back
                   3916: 
                   3917: =cut
                   3918: 
                   3919: # ------------------------------------------------------------------ File Types
                   3920: sub fileextensions {
                   3921:     return sort(keys(%fe));
                   3922: }
                   3923: 
1.97      www      3924: # ----------------------------------------------------------- Display Languages
                   3925: # returns a hash with all desired display languages
                   3926: #
                   3927: 
                   3928: sub display_languages {
                   3929:     my %languages=();
1.695     raeburn  3930:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3931: 	$languages{$lang}=1;
1.97      www      3932:     }
                   3933:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3934:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3935: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3936: 	    $languages{$lang}=1;
1.97      www      3937:         }
                   3938:     }
                   3939:     return %languages;
1.14      harris41 3940: }
                   3941: 
1.582     albertel 3942: sub languages {
                   3943:     my ($possible_langs) = @_;
1.695     raeburn  3944:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3945:     if (!ref($possible_langs)) {
                   3946: 	if( wantarray ) {
                   3947: 	    return @preferred_langs;
                   3948: 	} else {
                   3949: 	    return $preferred_langs[0];
                   3950: 	}
                   3951:     }
                   3952:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3953:     my @preferred_possibilities;
                   3954:     foreach my $preferred_lang (@preferred_langs) {
                   3955: 	if (exists($possibilities{$preferred_lang})) {
                   3956: 	    push(@preferred_possibilities, $preferred_lang);
                   3957: 	}
                   3958:     }
                   3959:     if( wantarray ) {
                   3960: 	return @preferred_possibilities;
                   3961:     }
                   3962:     return $preferred_possibilities[0];
                   3963: }
                   3964: 
1.742     raeburn  3965: sub user_lang {
                   3966:     my ($touname,$toudom,$fromcid) = @_;
                   3967:     my @userlangs;
                   3968:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3969:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3970:                     $env{'course.'.$fromcid.'.languages'}));
                   3971:     } else {
                   3972:         my %langhash = &getlangs($touname,$toudom);
                   3973:         if ($langhash{'languages'} ne '') {
                   3974:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3975:         } else {
                   3976:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3977:             if ($domdefs{'lang_def'} ne '') {
                   3978:                 @userlangs = ($domdefs{'lang_def'});
                   3979:             }
                   3980:         }
                   3981:     }
                   3982:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3983:     my $user_lh = Apache::localize->get_handle(@languages);
                   3984:     return $user_lh;
                   3985: }
                   3986: 
                   3987: 
1.112     bowersj2 3988: ###############################################################
                   3989: ##               Student Answer Attempts                     ##
                   3990: ###############################################################
                   3991: 
                   3992: =pod
                   3993: 
                   3994: =head1 Alternate Problem Views
                   3995: 
                   3996: =over 4
                   3997: 
1.648     raeburn  3998: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  3999:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4000: 
                   4001: Return string with previous attempt on problem. Arguments:
                   4002: 
                   4003: =over 4
                   4004: 
                   4005: =item * $symb: Problem, including path
                   4006: 
                   4007: =item * $username: username of the desired student
                   4008: 
                   4009: =item * $domain: domain of the desired student
1.14      harris41 4010: 
1.112     bowersj2 4011: =item * $course: Course ID
1.14      harris41 4012: 
1.112     bowersj2 4013: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4014:     something
1.14      harris41 4015: 
1.112     bowersj2 4016: =item * $regexp: if string matches this regexp, the string will be
                   4017:     sent to $gradesub
1.14      harris41 4018: 
1.112     bowersj2 4019: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4020: 
1.1199    raeburn  4021: =item * $usec: section of the desired student
                   4022: 
                   4023: =item * $identifier: counter for student (multiple students one problem) or 
                   4024:     problem (one student; whole sequence).
                   4025: 
1.112     bowersj2 4026: =back
1.14      harris41 4027: 
1.112     bowersj2 4028: The output string is a table containing all desired attempts, if any.
1.16      harris41 4029: 
1.112     bowersj2 4030: =cut
1.1       albertel 4031: 
                   4032: sub get_previous_attempt {
1.1199    raeburn  4033:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4034:   my $prevattempts='';
1.43      ng       4035:   no strict 'refs';
1.1       albertel 4036:   if ($symb) {
1.3       albertel 4037:     my (%returnhash)=
                   4038:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4039:     if ($returnhash{'version'}) {
                   4040:       my %lasthash=();
                   4041:       my $version;
                   4042:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4043:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4044:             if ($key =~ /\.rawrndseed$/) {
                   4045:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4046:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4047:             } else {
                   4048:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4049:             }
1.19      harris41 4050:         }
1.1       albertel 4051:       }
1.596     albertel 4052:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4053:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4054:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4055:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4056:       foreach my $key (sort(keys(%lasthash))) {
                   4057: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4058: 	if ($#parts > 0) {
1.31      albertel 4059: 	  my $data=$parts[-1];
1.989     raeburn  4060:           next if ($data eq 'foilorder');
1.31      albertel 4061: 	  pop(@parts);
1.1010    www      4062:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4063:           if ($data eq 'type') {
                   4064:               unless ($showsurv) {
                   4065:                   my $id = join(',',@parts);
                   4066:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4067:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4068:                       $lasthidden{$ign.'.'.$id} = 1;
                   4069:                   }
1.945     raeburn  4070:               }
1.1199    raeburn  4071:               if ($identifier ne '') {
                   4072:                   my $id = join(',',@parts);
                   4073:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4074:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4075:                       $hidestatus{$ign.'.'.$id} = 1;
                   4076:                   }
                   4077:               }
                   4078:           } elsif ($data eq 'regrader') {
                   4079:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4080:                   my $id = join(',',@parts);
                   4081:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4082:               }
1.1010    www      4083:           } 
1.31      albertel 4084: 	} else {
1.41      ng       4085: 	  if ($#parts == 0) {
                   4086: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4087: 	  } else {
                   4088: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4089: 	  }
1.31      albertel 4090: 	}
1.16      harris41 4091:       }
1.596     albertel 4092:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4093:       if ($getattempt eq '') {
1.1199    raeburn  4094:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4095:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4096:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4097:                 foreach my $id (keys(%regraded)) {
                   4098:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4099:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4100:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4101:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4102:                     }
                   4103:                 }
                   4104:             }
1.1200    raeburn  4105:         }
                   4106: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4107:             my (@hidden,@unsolved);
1.945     raeburn  4108:             if (%typeparts) {
                   4109:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4110:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4111:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4112:                         push(@hidden,$id);
1.1199    raeburn  4113:                     } elsif ($identifier ne '') {
                   4114:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4115:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4116:                                 ($hidestatus{$id})) {
1.1200    raeburn  4117:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4118:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4119:                                 push(@{$solved{$id}},$version);
                   4120:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4121:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4122:                                 my $skip;
                   4123:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4124:                                     foreach my $reset (@{$resets{$id}}) {
                   4125:                                         if ($reset > $solved{$id}[-1]) {
                   4126:                                             $skip=1;
                   4127:                                             last;
                   4128:                                         }
                   4129:                                     }
                   4130:                                 }
                   4131:                                 unless ($skip) {
                   4132:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4133:                                     push(@unsolved,$partslist);
                   4134:                                 }
                   4135:                             }
                   4136:                         }
1.945     raeburn  4137:                     }
                   4138:                 }
                   4139:             }
                   4140:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4141:                            '<td>'.&mt('Transaction [_1]',$version);
                   4142:             if (@unsolved) {
                   4143:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4144:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4145:                                  &mt('Hide').'</label></span>';
                   4146:             }
                   4147:             $prevattempts .= '</td>';
1.945     raeburn  4148:             if (@hidden) {
                   4149:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4150:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4151:                     my $hide;
                   4152:                     foreach my $id (@hidden) {
                   4153:                         if ($key =~ /^\Q$id\E/) {
                   4154:                             $hide = 1;
                   4155:                             last;
                   4156:                         }
                   4157:                     }
                   4158:                     if ($hide) {
                   4159:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4160:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4161:                             my $value = &format_previous_attempt_value($key,
                   4162:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4163:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4164:                         } else {
                   4165:                             $prevattempts.='<td>&nbsp;</td>';
                   4166:                         }
                   4167:                     } else {
                   4168:                         if ($key =~ /\./) {
1.1212    raeburn  4169:                             my $value = $returnhash{$version.':'.$key};
                   4170:                             if ($key =~ /\.rndseed$/) {
                   4171:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4172:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4173:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4174:                                 }
                   4175:                             }
                   4176:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4177:                                            '&nbsp;</td>';
1.945     raeburn  4178:                         } else {
                   4179:                             $prevattempts.='<td>&nbsp;</td>';
                   4180:                         }
                   4181:                     }
                   4182:                 }
                   4183:             } else {
                   4184: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4185:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4186:                     my $value = $returnhash{$version.':'.$key};
                   4187:                     if ($key =~ /\.rndseed$/) {
                   4188:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4189:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4190:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4191:                         }
                   4192:                     }
                   4193:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4194:                                    '&nbsp;</td>';
1.945     raeburn  4195: 	        }
                   4196:             }
                   4197: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4198: 	 }
1.1       albertel 4199:       }
1.945     raeburn  4200:       my @currhidden = keys(%lasthidden);
1.596     albertel 4201:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4202:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4203:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4204:           if (%typeparts) {
                   4205:               my $hidden;
                   4206:               foreach my $id (@currhidden) {
                   4207:                   if ($key =~ /^\Q$id\E/) {
                   4208:                       $hidden = 1;
                   4209:                       last;
                   4210:                   }
                   4211:               }
                   4212:               if ($hidden) {
                   4213:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4214:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4215:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4216:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4217:                           $value = &$gradesub($value);
                   4218:                       }
1.1173    kruse    4219:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4220:                   } else {
                   4221:                       $prevattempts.='<td>&nbsp;</td>';
                   4222:                   }
                   4223:               } else {
                   4224:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4225:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4226:                       $value = &$gradesub($value);
                   4227:                   }
1.1173    kruse    4228:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4229:               }
                   4230:           } else {
                   4231: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4232: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4233:                   $value = &$gradesub($value);
                   4234:               }
1.1173    kruse    4235: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4236:           }
1.16      harris41 4237:       }
1.596     albertel 4238:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4239:     } else {
1.596     albertel 4240:       $prevattempts=
                   4241: 	  &start_data_table().&start_data_table_row().
                   4242: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4243: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4244:     }
                   4245:   } else {
1.596     albertel 4246:     $prevattempts=
                   4247: 	  &start_data_table().&start_data_table_row().
                   4248: 	  '<td>'.&mt('No data.').'</td>'.
                   4249: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4250:   }
1.10      albertel 4251: }
                   4252: 
1.581     albertel 4253: sub format_previous_attempt_value {
                   4254:     my ($key,$value) = @_;
1.1011    www      4255:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4256:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4257:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4258:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4259:     } elsif ($key =~ /answerstring$/) {
                   4260:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4261:         my @answer = %answers;
                   4262:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4263:         my @anskeys = sort(keys(%answers));
                   4264:         if (@anskeys == 1) {
                   4265:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4266:             if ($answer =~ m{\0}) {
                   4267:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4268:             }
                   4269:             my $tag_internal_answer_name = 'INTERNAL';
                   4270:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4271:                 $value = $answer; 
                   4272:             } else {
                   4273:                 $value = $anskeys[0].'='.$answer;
                   4274:             }
                   4275:         } else {
                   4276:             foreach my $ans (@anskeys) {
                   4277:                 my $answer = $answers{$ans};
1.1001    raeburn  4278:                 if ($answer =~ m{\0}) {
                   4279:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4280:                 }
                   4281:                 $value .=  $ans.'='.$answer.'<br />';;
                   4282:             } 
                   4283:         }
1.581     albertel 4284:     } else {
1.1173    kruse    4285:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4286:     }
                   4287:     return $value;
                   4288: }
                   4289: 
                   4290: 
1.107     albertel 4291: sub relative_to_absolute {
                   4292:     my ($url,$output)=@_;
                   4293:     my $parser=HTML::TokeParser->new(\$output);
                   4294:     my $token;
                   4295:     my $thisdir=$url;
                   4296:     my @rlinks=();
                   4297:     while ($token=$parser->get_token) {
                   4298: 	if ($token->[0] eq 'S') {
                   4299: 	    if ($token->[1] eq 'a') {
                   4300: 		if ($token->[2]->{'href'}) {
                   4301: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4302: 		}
                   4303: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4304: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4305: 	    } elsif ($token->[1] eq 'base') {
                   4306: 		$thisdir=$token->[2]->{'href'};
                   4307: 	    }
                   4308: 	}
                   4309:     }
                   4310:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4311:     foreach my $link (@rlinks) {
1.726     raeburn  4312: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4313: 		($link=~/^\//) ||
                   4314: 		($link=~/^javascript:/i) ||
                   4315: 		($link=~/^mailto:/i) ||
                   4316: 		($link=~/^\#/)) {
                   4317: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4318: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4319: 	}
                   4320:     }
                   4321: # -------------------------------------------------- Deal with Applet codebases
                   4322:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4323:     return $output;
                   4324: }
                   4325: 
1.112     bowersj2 4326: =pod
                   4327: 
1.648     raeburn  4328: =item * &get_student_view()
1.112     bowersj2 4329: 
                   4330: show a snapshot of what student was looking at
                   4331: 
                   4332: =cut
                   4333: 
1.10      albertel 4334: sub get_student_view {
1.186     albertel 4335:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4336:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4337:   my (%form);
1.10      albertel 4338:   my @elements=('symb','courseid','domain','username');
                   4339:   foreach my $element (@elements) {
1.186     albertel 4340:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4341:   }
1.186     albertel 4342:   if (defined($moreenv)) {
                   4343:       %form=(%form,%{$moreenv});
                   4344:   }
1.236     albertel 4345:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4346:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4347:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4348:   $userview=~s/\<body[^\>]*\>//gi;
                   4349:   $userview=~s/\<\/body\>//gi;
                   4350:   $userview=~s/\<html\>//gi;
                   4351:   $userview=~s/\<\/html\>//gi;
                   4352:   $userview=~s/\<head\>//gi;
                   4353:   $userview=~s/\<\/head\>//gi;
                   4354:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4355:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4356:   if (wantarray) {
                   4357:      return ($userview,$response);
                   4358:   } else {
                   4359:      return $userview;
                   4360:   }
                   4361: }
                   4362: 
                   4363: sub get_student_view_with_retries {
                   4364:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4365: 
                   4366:     my $ok = 0;                 # True if we got a good response.
                   4367:     my $content;
                   4368:     my $response;
                   4369: 
                   4370:     # Try to get the student_view done. within the retries count:
                   4371:     
                   4372:     do {
                   4373:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4374:          $ok      = $response->is_success;
                   4375:          if (!$ok) {
                   4376:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4377:          }
                   4378:          $retries--;
                   4379:     } while (!$ok && ($retries > 0));
                   4380:     
                   4381:     if (!$ok) {
                   4382:        $content = '';          # On error return an empty content.
                   4383:     }
1.651     www      4384:     if (wantarray) {
                   4385:        return ($content, $response);
                   4386:     } else {
                   4387:        return $content;
                   4388:     }
1.11      albertel 4389: }
                   4390: 
1.112     bowersj2 4391: =pod
                   4392: 
1.648     raeburn  4393: =item * &get_student_answers() 
1.112     bowersj2 4394: 
                   4395: show a snapshot of how student was answering problem
                   4396: 
                   4397: =cut
                   4398: 
1.11      albertel 4399: sub get_student_answers {
1.100     sakharuk 4400:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4401:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4402:   my (%moreenv);
1.11      albertel 4403:   my @elements=('symb','courseid','domain','username');
                   4404:   foreach my $element (@elements) {
1.186     albertel 4405:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4406:   }
1.186     albertel 4407:   $moreenv{'grade_target'}='answer';
                   4408:   %moreenv=(%form,%moreenv);
1.497     raeburn  4409:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4410:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4411:   return $userview;
1.1       albertel 4412: }
1.116     albertel 4413: 
                   4414: =pod
                   4415: 
                   4416: =item * &submlink()
                   4417: 
1.242     albertel 4418: Inputs: $text $uname $udom $symb $target
1.116     albertel 4419: 
                   4420: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4421: 
                   4422: =cut
                   4423: 
                   4424: ###############################################
                   4425: sub submlink {
1.242     albertel 4426:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4427:     if (!($uname && $udom)) {
                   4428: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4429: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4430: 	if (!$symb) { $symb=$cursymb; }
                   4431:     }
1.254     matthew  4432:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4433:     $symb=&escape($symb);
1.960     bisitz   4434:     if ($target) { $target=" target=\"$target\""; }
                   4435:     return
                   4436:         '<a href="/adm/grades?command=submission'.
                   4437:         '&amp;symb='.$symb.
                   4438:         '&amp;student='.$uname.
                   4439:         '&amp;userdom='.$udom.'"'.
                   4440:         $target.'>'.$text.'</a>';
1.242     albertel 4441: }
                   4442: ##############################################
                   4443: 
                   4444: =pod
                   4445: 
                   4446: =item * &pgrdlink()
                   4447: 
                   4448: Inputs: $text $uname $udom $symb $target
                   4449: 
                   4450: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4451: 
                   4452: =cut
                   4453: 
                   4454: ###############################################
                   4455: sub pgrdlink {
                   4456:     my $link=&submlink(@_);
                   4457:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4458:     return $link;
                   4459: }
                   4460: ##############################################
                   4461: 
                   4462: =pod
                   4463: 
                   4464: =item * &pprmlink()
                   4465: 
                   4466: Inputs: $text $uname $udom $symb $target
                   4467: 
                   4468: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4469: student and a specific resource
1.242     albertel 4470: 
                   4471: =cut
                   4472: 
                   4473: ###############################################
                   4474: sub pprmlink {
                   4475:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4476:     if (!($uname && $udom)) {
                   4477: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4478: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4479: 	if (!$symb) { $symb=$cursymb; }
                   4480:     }
1.254     matthew  4481:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4482:     $symb=&escape($symb);
1.242     albertel 4483:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4484:     return '<a href="/adm/parmset?command=set&amp;'.
                   4485: 	'symb='.$symb.'&amp;uname='.$uname.
                   4486: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4487: }
                   4488: ##############################################
1.37      matthew  4489: 
1.112     bowersj2 4490: =pod
                   4491: 
                   4492: =back
                   4493: 
                   4494: =cut
                   4495: 
1.37      matthew  4496: ###############################################
1.51      www      4497: 
                   4498: 
                   4499: sub timehash {
1.687     raeburn  4500:     my ($thistime) = @_;
                   4501:     my $timezone = &Apache::lonlocal::gettimezone();
                   4502:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4503:                      ->set_time_zone($timezone);
                   4504:     my $wday = $dt->day_of_week();
                   4505:     if ($wday == 7) { $wday = 0; }
                   4506:     return ( 'second' => $dt->second(),
                   4507:              'minute' => $dt->minute(),
                   4508:              'hour'   => $dt->hour(),
                   4509:              'day'     => $dt->day_of_month(),
                   4510:              'month'   => $dt->month(),
                   4511:              'year'    => $dt->year(),
                   4512:              'weekday' => $wday,
                   4513:              'dayyear' => $dt->day_of_year(),
                   4514:              'dlsav'   => $dt->is_dst() );
1.51      www      4515: }
                   4516: 
1.370     www      4517: sub utc_string {
                   4518:     my ($date)=@_;
1.371     www      4519:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4520: }
                   4521: 
1.51      www      4522: sub maketime {
                   4523:     my %th=@_;
1.687     raeburn  4524:     my ($epoch_time,$timezone,$dt);
                   4525:     $timezone = &Apache::lonlocal::gettimezone();
                   4526:     eval {
                   4527:         $dt = DateTime->new( year   => $th{'year'},
                   4528:                              month  => $th{'month'},
                   4529:                              day    => $th{'day'},
                   4530:                              hour   => $th{'hour'},
                   4531:                              minute => $th{'minute'},
                   4532:                              second => $th{'second'},
                   4533:                              time_zone => $timezone,
                   4534:                          );
                   4535:     };
                   4536:     if (!$@) {
                   4537:         $epoch_time = $dt->epoch;
                   4538:         if ($epoch_time) {
                   4539:             return $epoch_time;
                   4540:         }
                   4541:     }
1.51      www      4542:     return POSIX::mktime(
                   4543:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4544:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4545: }
                   4546: 
                   4547: #########################################
1.51      www      4548: 
                   4549: sub findallcourses {
1.482     raeburn  4550:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4551:     my %roles;
                   4552:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4553:     my %courses;
1.51      www      4554:     my $now=time;
1.482     raeburn  4555:     if (!defined($uname)) {
                   4556:         $uname = $env{'user.name'};
                   4557:     }
                   4558:     if (!defined($udom)) {
                   4559:         $udom = $env{'user.domain'};
                   4560:     }
                   4561:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4562:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4563:         if (!%roles) {
                   4564:             %roles = (
                   4565:                        cc => 1,
1.907     raeburn  4566:                        co => 1,
1.482     raeburn  4567:                        in => 1,
                   4568:                        ep => 1,
                   4569:                        ta => 1,
                   4570:                        cr => 1,
                   4571:                        st => 1,
                   4572:              );
                   4573:         }
                   4574:         foreach my $entry (keys(%roleshash)) {
                   4575:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4576:             if ($trole =~ /^cr/) { 
                   4577:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4578:             } else {
                   4579:                 next if (!exists($roles{$trole}));
                   4580:             }
                   4581:             if ($tend) {
                   4582:                 next if ($tend < $now);
                   4583:             }
                   4584:             if ($tstart) {
                   4585:                 next if ($tstart > $now);
                   4586:             }
1.1058    raeburn  4587:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4588:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4589:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4590:             if ($secpart eq '') {
                   4591:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4592:                 $sec = 'none';
1.1058    raeburn  4593:                 $value .= $cnum.'/';
1.482     raeburn  4594:             } else {
                   4595:                 $cnum = $cnumpart;
                   4596:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4597:                 $value .= $cnum.'/'.$sec;
                   4598:             }
                   4599:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4600:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4601:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4602:                 }
                   4603:             } else {
                   4604:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4605:             }
1.482     raeburn  4606:         }
                   4607:     } else {
                   4608:         foreach my $key (keys(%env)) {
1.483     albertel 4609: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4610:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4611: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4612: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4613: 	        next if (%roles && !exists($roles{$role}));
                   4614: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4615:                 my $active=1;
                   4616:                 if ($starttime) {
                   4617: 		    if ($now<$starttime) { $active=0; }
                   4618:                 }
                   4619:                 if ($endtime) {
                   4620:                     if ($now>$endtime) { $active=0; }
                   4621:                 }
                   4622:                 if ($active) {
1.1058    raeburn  4623:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4624:                     if ($sec eq '') {
                   4625:                         $sec = 'none';
1.1058    raeburn  4626:                     } else {
                   4627:                         $value .= $sec;
                   4628:                     }
                   4629:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4630:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4631:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4632:                         }
                   4633:                     } else {
                   4634:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4635:                     }
1.474     raeburn  4636:                 }
                   4637:             }
1.51      www      4638:         }
                   4639:     }
1.474     raeburn  4640:     return %courses;
1.51      www      4641: }
1.37      matthew  4642: 
1.54      www      4643: ###############################################
1.474     raeburn  4644: 
                   4645: sub blockcheck {
1.1189    raeburn  4646:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4647: 
1.1189    raeburn  4648:     if (defined($udom) && defined($uname)) {
                   4649:         # If uname and udom are for a course, check for blocks in the course.
                   4650:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4651:             my ($startblock,$endblock,$triggerblock) =
                   4652:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4653:             return ($startblock,$endblock,$triggerblock);
                   4654:         }
                   4655:     } else {
1.490     raeburn  4656:         $udom = $env{'user.domain'};
                   4657:         $uname = $env{'user.name'};
                   4658:     }
                   4659: 
1.502     raeburn  4660:     my $startblock = 0;
                   4661:     my $endblock = 0;
1.1062    raeburn  4662:     my $triggerblock = '';
1.482     raeburn  4663:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4664: 
1.490     raeburn  4665:     # If uname is for a user, and activity is course-specific, i.e.,
                   4666:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4667: 
1.490     raeburn  4668:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4669:          $activity eq 'groups' || $activity eq 'printout') &&
                   4670:         ($env{'request.course.id'})) {
1.490     raeburn  4671:         foreach my $key (keys(%live_courses)) {
                   4672:             if ($key ne $env{'request.course.id'}) {
                   4673:                 delete($live_courses{$key});
                   4674:             }
                   4675:         }
                   4676:     }
                   4677: 
                   4678:     my $otheruser = 0;
                   4679:     my %own_courses;
                   4680:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4681:         # Resource belongs to user other than current user.
                   4682:         $otheruser = 1;
                   4683:         # Gather courses for current user
                   4684:         %own_courses = 
                   4685:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4686:     }
                   4687: 
                   4688:     # Gather active course roles - course coordinator, instructor, 
                   4689:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4690: 
                   4691:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4692:         my ($cdom,$cnum);
                   4693:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4694:             $cdom = $env{'course.'.$course.'.domain'};
                   4695:             $cnum = $env{'course.'.$course.'.num'};
                   4696:         } else {
1.490     raeburn  4697:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4698:         }
                   4699:         my $no_ownblock = 0;
                   4700:         my $no_userblock = 0;
1.533     raeburn  4701:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4702:             # Check if current user has 'evb' priv for this
                   4703:             if (defined($own_courses{$course})) {
                   4704:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4705:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4706:                     if ($sec ne 'none') {
                   4707:                         $checkrole .= '/'.$sec;
                   4708:                     }
                   4709:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4710:                         $no_ownblock = 1;
                   4711:                         last;
                   4712:                     }
                   4713:                 }
                   4714:             }
                   4715:             # if they have 'evb' priv and are currently not playing student
                   4716:             next if (($no_ownblock) &&
                   4717:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4718:         }
1.474     raeburn  4719:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4720:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4721:             if ($sec ne 'none') {
1.482     raeburn  4722:                 $checkrole .= '/'.$sec;
1.474     raeburn  4723:             }
1.490     raeburn  4724:             if ($otheruser) {
                   4725:                 # Resource belongs to user other than current user.
                   4726:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4727:                 my (%allroles,%userroles);
                   4728:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4729:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4730:                         my ($trole,$tdom,$tnum,$tsec);
                   4731:                         if ($entry =~ /^cr/) {
                   4732:                             ($trole,$tdom,$tnum,$tsec) = 
                   4733:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4734:                         } else {
                   4735:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4736:                         }
                   4737:                         my ($spec,$area,$trest);
                   4738:                         $area = '/'.$tdom.'/'.$tnum;
                   4739:                         $trest = $tnum;
                   4740:                         if ($tsec ne '') {
                   4741:                             $area .= '/'.$tsec;
                   4742:                             $trest .= '/'.$tsec;
                   4743:                         }
                   4744:                         $spec = $trole.'.'.$area;
                   4745:                         if ($trole =~ /^cr/) {
                   4746:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4747:                                                               $tdom,$spec,$trest,$area);
                   4748:                         } else {
                   4749:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4750:                                                                 $tdom,$spec,$trest,$area);
                   4751:                         }
                   4752:                     }
                   4753:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4754:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4755:                         if ($1) {
                   4756:                             $no_userblock = 1;
                   4757:                             last;
                   4758:                         }
1.486     raeburn  4759:                     }
                   4760:                 }
1.490     raeburn  4761:             } else {
                   4762:                 # Resource belongs to current user
                   4763:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4764:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4765:                     $no_ownblock = 1;
                   4766:                     last;
                   4767:                 }
1.474     raeburn  4768:             }
                   4769:         }
                   4770:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4771:         next if (($no_ownblock) &&
1.491     albertel 4772:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4773:         next if ($no_userblock);
1.474     raeburn  4774: 
1.866     kalberla 4775:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4776:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4777:         
1.1062    raeburn  4778:         my ($start,$end,$trigger) = 
                   4779:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4780:         if (($start != 0) && 
                   4781:             (($startblock == 0) || ($startblock > $start))) {
                   4782:             $startblock = $start;
1.1062    raeburn  4783:             if ($trigger ne '') {
                   4784:                 $triggerblock = $trigger;
                   4785:             }
1.502     raeburn  4786:         }
                   4787:         if (($end != 0)  &&
                   4788:             (($endblock == 0) || ($endblock < $end))) {
                   4789:             $endblock = $end;
1.1062    raeburn  4790:             if ($trigger ne '') {
                   4791:                 $triggerblock = $trigger;
                   4792:             }
1.502     raeburn  4793:         }
1.490     raeburn  4794:     }
1.1062    raeburn  4795:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4796: }
                   4797: 
                   4798: sub get_blocks {
1.1062    raeburn  4799:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4800:     my $startblock = 0;
                   4801:     my $endblock = 0;
1.1062    raeburn  4802:     my $triggerblock = '';
1.490     raeburn  4803:     my $course = $cdom.'_'.$cnum;
                   4804:     $setters->{$course} = {};
                   4805:     $setters->{$course}{'staff'} = [];
                   4806:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4807:     $setters->{$course}{'triggers'} = [];
                   4808:     my (@blockers,%triggered);
                   4809:     my $now = time;
                   4810:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4811:     if ($activity eq 'docs') {
                   4812:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4813:         foreach my $block (@blockers) {
                   4814:             if ($block =~ /^firstaccess____(.+)$/) {
                   4815:                 my $item = $1;
                   4816:                 my $type = 'map';
                   4817:                 my $timersymb = $item;
                   4818:                 if ($item eq 'course') {
                   4819:                     $type = 'course';
                   4820:                 } elsif ($item =~ /___\d+___/) {
                   4821:                     $type = 'resource';
                   4822:                 } else {
                   4823:                     $timersymb = &Apache::lonnet::symbread($item);
                   4824:                 }
                   4825:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4826:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4827:                 $triggered{$block} = {
                   4828:                                        start => $start,
                   4829:                                        end   => $end,
                   4830:                                        type  => $type,
                   4831:                                      };
                   4832:             }
                   4833:         }
                   4834:     } else {
                   4835:         foreach my $block (keys(%commblocks)) {
                   4836:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4837:                 my ($start,$end) = ($1,$2);
                   4838:                 if ($start <= time && $end >= time) {
                   4839:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4840:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4841:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4842:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4843:                                     push(@blockers,$block);
                   4844:                                 }
                   4845:                             }
                   4846:                         }
                   4847:                     }
                   4848:                 }
                   4849:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4850:                 my $item = $1;
                   4851:                 my $timersymb = $item; 
                   4852:                 my $type = 'map';
                   4853:                 if ($item eq 'course') {
                   4854:                     $type = 'course';
                   4855:                 } elsif ($item =~ /___\d+___/) {
                   4856:                     $type = 'resource';
                   4857:                 } else {
                   4858:                     $timersymb = &Apache::lonnet::symbread($item);
                   4859:                 }
                   4860:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4861:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4862:                 if ($start && $end) {
                   4863:                     if (($start <= time) && ($end >= time)) {
                   4864:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4865:                             push(@blockers,$block);
                   4866:                             $triggered{$block} = {
                   4867:                                                    start => $start,
                   4868:                                                    end   => $end,
                   4869:                                                    type  => $type,
                   4870:                                                  };
                   4871:                         }
                   4872:                     }
1.490     raeburn  4873:                 }
1.1062    raeburn  4874:             }
                   4875:         }
                   4876:     }
                   4877:     foreach my $blocker (@blockers) {
                   4878:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4879:             &parse_block_record($commblocks{$blocker});
                   4880:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4881:         my ($start,$end,$triggertype);
                   4882:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4883:             ($start,$end) = ($1,$2);
                   4884:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4885:             $start = $triggered{$blocker}{'start'};
                   4886:             $end = $triggered{$blocker}{'end'};
                   4887:             $triggertype = $triggered{$blocker}{'type'};
                   4888:         }
                   4889:         if ($start) {
                   4890:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4891:             if ($triggertype) {
                   4892:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4893:             } else {
                   4894:                 push(@{$$setters{$course}{'triggers'}},0);
                   4895:             }
                   4896:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4897:                 $startblock = $start;
                   4898:                 if ($triggertype) {
                   4899:                     $triggerblock = $blocker;
1.474     raeburn  4900:                 }
                   4901:             }
1.1062    raeburn  4902:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4903:                $endblock = $end;
                   4904:                if ($triggertype) {
                   4905:                    $triggerblock = $blocker;
                   4906:                }
                   4907:             }
1.474     raeburn  4908:         }
                   4909:     }
1.1062    raeburn  4910:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4911: }
                   4912: 
                   4913: sub parse_block_record {
                   4914:     my ($record) = @_;
                   4915:     my ($setuname,$setudom,$title,$blocks);
                   4916:     if (ref($record) eq 'HASH') {
                   4917:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4918:         $title = &unescape($record->{'event'});
                   4919:         $blocks = $record->{'blocks'};
                   4920:     } else {
                   4921:         my @data = split(/:/,$record,3);
                   4922:         if (scalar(@data) eq 2) {
                   4923:             $title = $data[1];
                   4924:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4925:         } else {
                   4926:             ($setuname,$setudom,$title) = @data;
                   4927:         }
                   4928:         $blocks = { 'com' => 'on' };
                   4929:     }
                   4930:     return ($setuname,$setudom,$title,$blocks);
                   4931: }
                   4932: 
1.854     kalberla 4933: sub blocking_status {
1.1189    raeburn  4934:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4935:     my %setters;
1.890     droeschl 4936: 
1.1061    raeburn  4937: # check for active blocking
1.1062    raeburn  4938:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  4939:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4940:     my $blocked = 0;
                   4941:     if ($startblock && $endblock) {
                   4942:         $blocked = 1;
                   4943:     }
1.890     droeschl 4944: 
1.1061    raeburn  4945: # caller just wants to know whether a block is active
                   4946:     if (!wantarray) { return $blocked; }
                   4947: 
                   4948: # build a link to a popup window containing the details
                   4949:     my $querystring  = "?activity=$activity";
                   4950: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4951:     if ($activity eq 'port') {
                   4952:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4953:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4954:     } elsif ($activity eq 'docs') {
                   4955:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4956:     }
1.1061    raeburn  4957: 
                   4958:     my $output .= <<'END_MYBLOCK';
                   4959: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4960:     var options = "width=" + w + ",height=" + h + ",";
                   4961:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4962:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4963:     var newWin = window.open(url, wdwName, options);
                   4964:     newWin.focus();
                   4965: }
1.890     droeschl 4966: END_MYBLOCK
1.854     kalberla 4967: 
1.1061    raeburn  4968:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4969:   
1.1061    raeburn  4970:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4971:     my $text = &mt('Communication Blocked');
                   4972:     if ($activity eq 'docs') {
                   4973:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4974:     } elsif ($activity eq 'printout') {
                   4975:         $text = &mt('Printing Blocked');
1.1062    raeburn  4976:     }
1.1061    raeburn  4977:     $output .= <<"END_BLOCK";
1.867     kalberla 4978: <div class='LC_comblock'>
1.869     kalberla 4979:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4980:   title='$text'>
                   4981:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4982:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4983:   title='$text'>$text</a>
1.867     kalberla 4984: </div>
                   4985: 
                   4986: END_BLOCK
1.474     raeburn  4987: 
1.1061    raeburn  4988:     return ($blocked, $output);
1.854     kalberla 4989: }
1.490     raeburn  4990: 
1.60      matthew  4991: ###############################################
                   4992: 
1.682     raeburn  4993: sub check_ip_acc {
1.1201    raeburn  4994:     my ($acc,$clientip)=@_;
1.682     raeburn  4995:     &Apache::lonxml::debug("acc is $acc");
                   4996:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4997:         return 1;
                   4998:     }
                   4999:     my $allowed=0;
1.1201    raeburn  5000:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
1.682     raeburn  5001: 
                   5002:     my $name;
                   5003:     foreach my $pattern (split(',',$acc)) {
                   5004:         $pattern =~ s/^\s*//;
                   5005:         $pattern =~ s/\s*$//;
                   5006:         if ($pattern =~ /\*$/) {
                   5007:             #35.8.*
                   5008:             $pattern=~s/\*//;
                   5009:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5010:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5011:             #35.8.3.[34-56]
                   5012:             my $low=$2;
                   5013:             my $high=$3;
                   5014:             $pattern=$1;
                   5015:             if ($ip =~ /^\Q$pattern\E/) {
                   5016:                 my $last=(split(/\./,$ip))[3];
                   5017:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   5018:             }
                   5019:         } elsif ($pattern =~ /^\*/) {
                   5020:             #*.msu.edu
                   5021:             $pattern=~s/\*//;
                   5022:             if (!defined($name)) {
                   5023:                 use Socket;
                   5024:                 my $netaddr=inet_aton($ip);
                   5025:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5026:             }
                   5027:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5028:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5029:             #127.0.0.1
                   5030:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5031:         } else {
                   5032:             #some.name.com
                   5033:             if (!defined($name)) {
                   5034:                 use Socket;
                   5035:                 my $netaddr=inet_aton($ip);
                   5036:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5037:             }
                   5038:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5039:         }
                   5040:         if ($allowed) { last; }
                   5041:     }
                   5042:     return $allowed;
                   5043: }
                   5044: 
                   5045: ###############################################
                   5046: 
1.60      matthew  5047: =pod
                   5048: 
1.112     bowersj2 5049: =head1 Domain Template Functions
                   5050: 
                   5051: =over 4
                   5052: 
                   5053: =item * &determinedomain()
1.60      matthew  5054: 
                   5055: Inputs: $domain (usually will be undef)
                   5056: 
1.63      www      5057: Returns: Determines which domain should be used for designs
1.60      matthew  5058: 
                   5059: =cut
1.54      www      5060: 
1.60      matthew  5061: ###############################################
1.63      www      5062: sub determinedomain {
                   5063:     my $domain=shift;
1.531     albertel 5064:     if (! $domain) {
1.60      matthew  5065:         # Determine domain if we have not been given one
1.893     raeburn  5066:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5067:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5068:         if ($env{'request.role.domain'}) { 
                   5069:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5070:         }
                   5071:     }
1.63      www      5072:     return $domain;
                   5073: }
                   5074: ###############################################
1.517     raeburn  5075: 
1.518     albertel 5076: sub devalidate_domconfig_cache {
                   5077:     my ($udom)=@_;
                   5078:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5079: }
                   5080: 
                   5081: # ---------------------- Get domain configuration for a domain
                   5082: sub get_domainconf {
                   5083:     my ($udom) = @_;
                   5084:     my $cachetime=1800;
                   5085:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5086:     if (defined($cached)) { return %{$result}; }
                   5087: 
                   5088:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5089: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5090:     my (%designhash,%legacy);
1.518     albertel 5091:     if (keys(%domconfig) > 0) {
                   5092:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5093:             if (keys(%{$domconfig{'login'}})) {
                   5094:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5095:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5096:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5097:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5098:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5099:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5100:                                         if ($key eq 'loginvia') {
                   5101:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5102:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5103:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5104:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5105: 
                   5106:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5107:                                                 } else {
                   5108:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5109:                                                 }
1.948     raeburn  5110:                                             }
1.1208    raeburn  5111:                                         } elsif ($key eq 'headtag') {
                   5112:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5113:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5114:                                             }
1.946     raeburn  5115:                                         }
1.1208    raeburn  5116:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5117:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5118:                                         }
1.946     raeburn  5119:                                     }
                   5120:                                 }
                   5121:                             }
                   5122:                         } else {
                   5123:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5124:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5125:                                     $domconfig{'login'}{$key}{$img};
                   5126:                             }
1.699     raeburn  5127:                         }
                   5128:                     } else {
                   5129:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5130:                     }
1.632     raeburn  5131:                 }
                   5132:             } else {
                   5133:                 $legacy{'login'} = 1;
1.518     albertel 5134:             }
1.632     raeburn  5135:         } else {
                   5136:             $legacy{'login'} = 1;
1.518     albertel 5137:         }
                   5138:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5139:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5140:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5141:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5142:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5143:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5144:                         }
1.518     albertel 5145:                     }
                   5146:                 }
1.632     raeburn  5147:             } else {
                   5148:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5149:             }
1.632     raeburn  5150:         } else {
                   5151:             $legacy{'rolecolors'} = 1;
1.518     albertel 5152:         }
1.948     raeburn  5153:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5154:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5155:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5156:             }
                   5157:         }
1.632     raeburn  5158:         if (keys(%legacy) > 0) {
                   5159:             my %legacyhash = &get_legacy_domconf($udom);
                   5160:             foreach my $item (keys(%legacyhash)) {
                   5161:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5162:                     if ($legacy{'login'}) { 
                   5163:                         $designhash{$item} = $legacyhash{$item};
                   5164:                     }
                   5165:                 } else {
                   5166:                     if ($legacy{'rolecolors'}) {
                   5167:                         $designhash{$item} = $legacyhash{$item};
                   5168:                     }
1.518     albertel 5169:                 }
                   5170:             }
                   5171:         }
1.632     raeburn  5172:     } else {
                   5173:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5174:     }
                   5175:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5176: 				  $cachetime);
                   5177:     return %designhash;
                   5178: }
                   5179: 
1.632     raeburn  5180: sub get_legacy_domconf {
                   5181:     my ($udom) = @_;
                   5182:     my %legacyhash;
                   5183:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5184:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5185:     if (-e $designfile) {
                   5186:         if ( open (my $fh,"<$designfile") ) {
                   5187:             while (my $line = <$fh>) {
                   5188:                 next if ($line =~ /^\#/);
                   5189:                 chomp($line);
                   5190:                 my ($key,$val)=(split(/\=/,$line));
                   5191:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5192:             }
                   5193:             close($fh);
                   5194:         }
                   5195:     }
1.1026    raeburn  5196:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5197:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5198:     }
                   5199:     return %legacyhash;
                   5200: }
                   5201: 
1.63      www      5202: =pod
                   5203: 
1.112     bowersj2 5204: =item * &domainlogo()
1.63      www      5205: 
                   5206: Inputs: $domain (usually will be undef)
                   5207: 
                   5208: Returns: A link to a domain logo, if the domain logo exists.
                   5209: If the domain logo does not exist, a description of the domain.
                   5210: 
                   5211: =cut
1.112     bowersj2 5212: 
1.63      www      5213: ###############################################
                   5214: sub domainlogo {
1.517     raeburn  5215:     my $domain = &determinedomain(shift);
1.518     albertel 5216:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5217:     # See if there is a logo
                   5218:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5219:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5220:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5221: 	    if ($imgsrc =~ m{^/res/}) {
                   5222: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5223: 		&Apache::lonnet::repcopy($local_name);
                   5224: 	    }
                   5225: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5226:         } 
                   5227:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5228:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5229:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5230:     } else {
1.60      matthew  5231:         return '';
1.59      www      5232:     }
                   5233: }
1.63      www      5234: ##############################################
                   5235: 
                   5236: =pod
                   5237: 
1.112     bowersj2 5238: =item * &designparm()
1.63      www      5239: 
                   5240: Inputs: $which parameter; $domain (usually will be undef)
                   5241: 
                   5242: Returns: value of designparamter $which
                   5243: 
                   5244: =cut
1.112     bowersj2 5245: 
1.397     albertel 5246: 
1.400     albertel 5247: ##############################################
1.397     albertel 5248: sub designparm {
                   5249:     my ($which,$domain)=@_;
                   5250:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5251:         return $env{'environment.color.'.$which};
1.96      www      5252:     }
1.63      www      5253:     $domain=&determinedomain($domain);
1.1016    raeburn  5254:     my %domdesign;
                   5255:     unless ($domain eq 'public') {
                   5256:         %domdesign = &get_domainconf($domain);
                   5257:     }
1.520     raeburn  5258:     my $output;
1.517     raeburn  5259:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5260:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5261:     } else {
1.520     raeburn  5262:         $output = $defaultdesign{$which};
                   5263:     }
                   5264:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5265:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5266:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5267:             if ($output =~ m{^/res/}) {
                   5268:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5269:                 &Apache::lonnet::repcopy($local_name);
                   5270:             }
1.520     raeburn  5271:             $output = &lonhttpdurl($output);
                   5272:         }
1.63      www      5273:     }
1.520     raeburn  5274:     return $output;
1.63      www      5275: }
1.59      www      5276: 
1.822     bisitz   5277: ##############################################
                   5278: =pod
                   5279: 
1.832     bisitz   5280: =item * &authorspace()
                   5281: 
1.1028    raeburn  5282: Inputs: $url (usually will be undef).
1.832     bisitz   5283: 
1.1132    raeburn  5284: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5285:          directory being viewed (or for which action is being taken). 
                   5286:          If $url is provided, and begins /priv/<domain>/<uname>
                   5287:          the path will be that portion of the $context argument.
                   5288:          Otherwise the path will be for the author space of the current
                   5289:          user when the current role is author, or for that of the 
                   5290:          co-author/assistant co-author space when the current role 
                   5291:          is co-author or assistant co-author.
1.832     bisitz   5292: 
                   5293: =cut
                   5294: 
                   5295: sub authorspace {
1.1028    raeburn  5296:     my ($url) = @_;
                   5297:     if ($url ne '') {
                   5298:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5299:            return $1;
                   5300:         }
                   5301:     }
1.832     bisitz   5302:     my $caname = '';
1.1024    www      5303:     my $cadom = '';
1.1028    raeburn  5304:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5305:         ($cadom,$caname) =
1.832     bisitz   5306:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5307:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5308:         $caname = $env{'user.name'};
1.1024    www      5309:         $cadom = $env{'user.domain'};
1.832     bisitz   5310:     }
1.1028    raeburn  5311:     if (($caname ne '') && ($cadom ne '')) {
                   5312:         return "/priv/$cadom/$caname/";
                   5313:     }
                   5314:     return;
1.832     bisitz   5315: }
                   5316: 
                   5317: ##############################################
                   5318: =pod
                   5319: 
1.822     bisitz   5320: =item * &head_subbox()
                   5321: 
                   5322: Inputs: $content (contains HTML code with page functions, etc.)
                   5323: 
                   5324: Returns: HTML div with $content
                   5325:          To be included in page header
                   5326: 
                   5327: =cut
                   5328: 
                   5329: sub head_subbox {
                   5330:     my ($content)=@_;
                   5331:     my $output =
1.993     raeburn  5332:         '<div class="LC_head_subbox">'
1.822     bisitz   5333:        .$content
                   5334:        .'</div>'
                   5335: }
                   5336: 
                   5337: ##############################################
                   5338: =pod
                   5339: 
                   5340: =item * &CSTR_pageheader()
                   5341: 
1.1026    raeburn  5342: Input: (optional) filename from which breadcrumb trail is built.
                   5343:        In most cases no input as needed, as $env{'request.filename'}
                   5344:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5345: 
                   5346: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5347:          To be included on Authoring Space pages
1.822     bisitz   5348: 
                   5349: =cut
                   5350: 
                   5351: sub CSTR_pageheader {
1.1026    raeburn  5352:     my ($trailfile) = @_;
                   5353:     if ($trailfile eq '') {
                   5354:         $trailfile = $env{'request.filename'};
                   5355:     }
                   5356: 
                   5357: # this is for resources; directories have customtitle, and crumbs
                   5358: # and select recent are created in lonpubdir.pm
                   5359: 
                   5360:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5361:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5362:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5363:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5364:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5365: 
                   5366:     my $parentpath = '';
                   5367:     my $lastitem = '';
                   5368:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5369:         $parentpath = $1;
                   5370:         $lastitem = $2;
                   5371:     } else {
                   5372:         $lastitem = $thisdisfn;
                   5373:     }
1.921     bisitz   5374: 
                   5375:     my $output =
1.822     bisitz   5376:          '<div>'
                   5377:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1132    raeburn  5378:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5379:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5380:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5381:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5382: 
                   5383:     if ($lastitem) {
                   5384:         $output .=
                   5385:              '<span class="LC_filename">'
                   5386:             .$lastitem
                   5387:             .'</span>';
                   5388:     }
                   5389:     $output .=
                   5390:          '<br />'
1.822     bisitz   5391:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5392:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5393:         .'</form>'
                   5394:         .&Apache::lonmenu::constspaceform()
                   5395:         .'</div>';
1.921     bisitz   5396: 
                   5397:     return $output;
1.822     bisitz   5398: }
                   5399: 
1.60      matthew  5400: ###############################################
                   5401: ###############################################
                   5402: 
                   5403: =pod
                   5404: 
1.112     bowersj2 5405: =back
                   5406: 
1.549     albertel 5407: =head1 HTML Helpers
1.112     bowersj2 5408: 
                   5409: =over 4
                   5410: 
                   5411: =item * &bodytag()
1.60      matthew  5412: 
                   5413: Returns a uniform header for LON-CAPA web pages.
                   5414: 
                   5415: Inputs: 
                   5416: 
1.112     bowersj2 5417: =over 4
                   5418: 
                   5419: =item * $title, A title to be displayed on the page.
                   5420: 
                   5421: =item * $function, the current role (can be undef).
                   5422: 
                   5423: =item * $addentries, extra parameters for the <body> tag.
                   5424: 
                   5425: =item * $bodyonly, if defined, only return the <body> tag.
                   5426: 
                   5427: =item * $domain, if defined, force a given domain.
                   5428: 
                   5429: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5430:             text interface only)
1.60      matthew  5431: 
1.814     bisitz   5432: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5433:                      navigational links
1.317     albertel 5434: 
1.338     albertel 5435: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5436: 
1.460     albertel 5437: =item * $args, optional argument valid values are
                   5438:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5439:             inherit_jsmath -> when creating popup window in a page,
                   5440:                               should it have jsmath forced on by the
                   5441:                               current page
1.460     albertel 5442: 
1.1096    raeburn  5443: =item * $advtoolsref, optional argument, ref to an array containing
                   5444:             inlineremote items to be added in "Functions" menu below
                   5445:             breadcrumbs.
                   5446: 
1.112     bowersj2 5447: =back
                   5448: 
1.60      matthew  5449: Returns: A uniform header for LON-CAPA web pages.  
                   5450: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5451: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5452: other decorations will be returned.
                   5453: 
                   5454: =cut
                   5455: 
1.54      www      5456: sub bodytag {
1.831     bisitz   5457:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5458:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5459: 
1.954     raeburn  5460:     my $public;
                   5461:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5462:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5463:         $public = 1;
                   5464:     }
1.460     albertel 5465:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5466:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5467: 
1.183     matthew  5468:     $function = &get_users_function() if (!$function);
1.339     albertel 5469:     my $img =    &designparm($function.'.img',$domain);
                   5470:     my $font =   &designparm($function.'.font',$domain);
                   5471:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5472: 
1.803     bisitz   5473:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5474: 		   'bgcolor' => $pgbg,
1.339     albertel 5475: 		   'text'    => $font,
                   5476:                    'alink'   => &designparm($function.'.alink',$domain),
                   5477: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5478: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5479:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5480: 
1.63      www      5481:  # role and realm
1.1178    raeburn  5482:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5483:     if ($realm) {
                   5484:         $realm = '/'.$realm;
                   5485:     }
1.378     raeburn  5486:     if ($role  eq 'ca') {
1.479     albertel 5487:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5488:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5489:     } 
1.55      www      5490: # realm
1.258     albertel 5491:     if ($env{'request.course.id'}) {
1.378     raeburn  5492:         if ($env{'request.role'} !~ /^cr/) {
                   5493:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5494:         }
1.898     raeburn  5495:         if ($env{'request.course.sec'}) {
                   5496:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5497:         }   
1.359     albertel 5498: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5499:     } else {
                   5500:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5501:     }
1.433     albertel 5502: 
1.359     albertel 5503:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5504: 
1.438     albertel 5505:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5506: 
1.101     www      5507: # construct main body tag
1.359     albertel 5508:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5509: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5510: 
1.1131    raeburn  5511:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5512: 
1.1130    raeburn  5513:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5514:         return $bodytag;
1.1130    raeburn  5515:     }
1.359     albertel 5516: 
1.954     raeburn  5517:     if ($public) {
1.433     albertel 5518: 	undef($role);
                   5519:     }
1.359     albertel 5520:     
1.762     bisitz   5521:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5522:     #
                   5523:     # Extra info if you are the DC
                   5524:     my $dc_info = '';
                   5525:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5526:                         $env{'course.'.$env{'request.course.id'}.
                   5527:                                  '.domain'}.'/'})) {
                   5528:         my $cid = $env{'request.course.id'};
1.917     raeburn  5529:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5530:         $dc_info =~ s/\s+$//;
1.359     albertel 5531:     }
                   5532: 
1.898     raeburn  5533:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5534: 
1.903     droeschl 5535:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5536: 
                   5537:         #    if ($env{'request.state'} eq 'construct') {
                   5538:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5539:         #    }
                   5540: 
1.1130    raeburn  5541:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5542:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5543: 
1.1130    raeburn  5544:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.359     albertel 5545: 
1.916     droeschl 5546:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5547:              if ($dc_info) {
                   5548:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5549:              }
1.1130    raeburn  5550:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5551:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5552:             return $bodytag;
                   5553:         }
1.894     droeschl 5554: 
1.927     raeburn  5555:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5556:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5557:         }
1.916     droeschl 5558: 
1.1130    raeburn  5559:         $bodytag .= $right;
1.852     droeschl 5560: 
1.917     raeburn  5561:         if ($dc_info) {
                   5562:             $dc_info = &dc_courseid_toggle($dc_info);
                   5563:         }
                   5564:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5565: 
1.1169    raeburn  5566:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5567:         if ($args->{'no_secondary_menu'}) {
                   5568:             return $bodytag;
                   5569:         }
1.1169    raeburn  5570:         #don't show menus for public users
1.954     raeburn  5571:         if (!$public){
1.1154    raeburn  5572:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5573:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5574:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5575:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5576:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5577:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5578:             } elsif ($forcereg) {
                   5579:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5580:                                                             $args->{'group'});
                   5581:             } else {
                   5582:                 $bodytag .= 
                   5583:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5584:                                                         $forcereg,$args->{'group'},
                   5585:                                                         $args->{'bread_crumbs'},
                   5586:                                                         $advtoolsref);
1.920     raeburn  5587:             }
1.903     droeschl 5588:         }else{
                   5589:             # this is to seperate menu from content when there's no secondary
                   5590:             # menu. Especially needed for public accessible ressources.
                   5591:             $bodytag .= '<hr style="clear:both" />';
                   5592:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5593:         }
1.903     droeschl 5594: 
1.235     raeburn  5595:         return $bodytag;
1.182     matthew  5596: }
                   5597: 
1.917     raeburn  5598: sub dc_courseid_toggle {
                   5599:     my ($dc_info) = @_;
1.980     raeburn  5600:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5601:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5602:            &mt('(More ...)').'</a></span>'.
                   5603:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5604: }
                   5605: 
1.330     albertel 5606: sub make_attr_string {
                   5607:     my ($register,$attr_ref) = @_;
                   5608: 
                   5609:     if ($attr_ref && !ref($attr_ref)) {
                   5610: 	die("addentries Must be a hash ref ".
                   5611: 	    join(':',caller(1))." ".
                   5612: 	    join(':',caller(0))." ");
                   5613:     }
                   5614: 
                   5615:     if ($register) {
1.339     albertel 5616: 	my ($on_load,$on_unload);
                   5617: 	foreach my $key (keys(%{$attr_ref})) {
                   5618: 	    if      (lc($key) eq 'onload') {
                   5619: 		$on_load.=$attr_ref->{$key}.';';
                   5620: 		delete($attr_ref->{$key});
                   5621: 
                   5622: 	    } elsif (lc($key) eq 'onunload') {
                   5623: 		$on_unload.=$attr_ref->{$key}.';';
                   5624: 		delete($attr_ref->{$key});
                   5625: 	    }
                   5626: 	}
1.953     droeschl 5627: 	$attr_ref->{'onload'}  = $on_load;
                   5628: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5629:     }
1.339     albertel 5630: 
1.330     albertel 5631:     my $attr_string;
1.1159    raeburn  5632:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5633: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5634:     }
                   5635:     return $attr_string;
                   5636: }
                   5637: 
                   5638: 
1.182     matthew  5639: ###############################################
1.251     albertel 5640: ###############################################
                   5641: 
                   5642: =pod
                   5643: 
                   5644: =item * &endbodytag()
                   5645: 
                   5646: Returns a uniform footer for LON-CAPA web pages.
                   5647: 
1.635     raeburn  5648: Inputs: 1 - optional reference to an args hash
                   5649: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5650: a 'Continue' link is not displayed if the page contains an
                   5651: internal redirect in the <head></head> section,
                   5652: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5653: 
                   5654: =cut
                   5655: 
                   5656: sub endbodytag {
1.635     raeburn  5657:     my ($args) = @_;
1.1080    raeburn  5658:     my $endbodytag;
                   5659:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5660:         $endbodytag='</body>';
                   5661:     }
1.269     albertel 5662:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5663:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5664:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5665: 	    $endbodytag=
                   5666: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5667: 	        &mt('Continue').'</a>'.
                   5668: 	        $endbodytag;
                   5669:         }
1.315     albertel 5670:     }
1.251     albertel 5671:     return $endbodytag;
                   5672: }
                   5673: 
1.352     albertel 5674: =pod
                   5675: 
                   5676: =item * &standard_css()
                   5677: 
                   5678: Returns a style sheet
                   5679: 
                   5680: Inputs: (all optional)
                   5681:             domain         -> force to color decorate a page for a specific
                   5682:                                domain
                   5683:             function       -> force usage of a specific rolish color scheme
                   5684:             bgcolor        -> override the default page bgcolor
                   5685: 
                   5686: =cut
                   5687: 
1.343     albertel 5688: sub standard_css {
1.345     albertel 5689:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5690:     $function  = &get_users_function() if (!$function);
                   5691:     my $img    = &designparm($function.'.img',   $domain);
                   5692:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5693:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5694:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5695: #second colour for later usage
1.345     albertel 5696:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5697:     my $pgbg_or_bgcolor =
                   5698: 	         $bgcolor ||
1.352     albertel 5699: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5700:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5701:     my $alink  = &designparm($function.'.alink', $domain);
                   5702:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5703:     my $link   = &designparm($function.'.link',  $domain);
                   5704: 
1.602     albertel 5705:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5706:     my $mono                 = 'monospace';
1.850     bisitz   5707:     my $data_table_head      = $sidebg;
                   5708:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5709:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5710:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5711:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5712:     my $mail_new             = '#FFBB77';
                   5713:     my $mail_new_hover       = '#DD9955';
                   5714:     my $mail_read            = '#BBBB77';
                   5715:     my $mail_read_hover      = '#999944';
                   5716:     my $mail_replied         = '#AAAA88';
                   5717:     my $mail_replied_hover   = '#888855';
                   5718:     my $mail_other           = '#99BBBB';
                   5719:     my $mail_other_hover     = '#669999';
1.391     albertel 5720:     my $table_header         = '#DDDDDD';
1.489     raeburn  5721:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5722:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5723:     my $button_hover         = '#BF2317';
1.392     albertel 5724: 
1.608     albertel 5725:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5726:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5727:                                              : '0 3px 0 4px';
1.448     albertel 5728: 
1.523     albertel 5729: 
1.343     albertel 5730:     return <<END;
1.947     droeschl 5731: 
                   5732: /* needed for iframe to allow 100% height in FF */
                   5733: body, html { 
                   5734:     margin: 0;
                   5735:     padding: 0 0.5%;
                   5736:     height: 99%; /* to avoid scrollbars */
                   5737: }
                   5738: 
1.795     www      5739: body {
1.911     bisitz   5740:   font-family: $sans;
                   5741:   line-height:130%;
                   5742:   font-size:0.83em;
                   5743:   color:$font;
1.795     www      5744: }
                   5745: 
1.959     onken    5746: a:focus,
                   5747: a:focus img {
1.795     www      5748:   color: red;
                   5749: }
1.698     harmsja  5750: 
1.911     bisitz   5751: form, .inline {
                   5752:   display: inline;
1.795     www      5753: }
1.721     harmsja  5754: 
1.795     www      5755: .LC_right {
1.911     bisitz   5756:   text-align:right;
1.795     www      5757: }
                   5758: 
                   5759: .LC_middle {
1.911     bisitz   5760:   vertical-align:middle;
1.795     www      5761: }
1.721     harmsja  5762: 
1.1130    raeburn  5763: .LC_floatleft {
                   5764:   float: left;
                   5765: }
                   5766: 
                   5767: .LC_floatright {
                   5768:   float: right;
                   5769: }
                   5770: 
1.911     bisitz   5771: .LC_400Box {
                   5772:   width:400px;
                   5773: }
1.721     harmsja  5774: 
1.947     droeschl 5775: .LC_iframecontainer {
                   5776:     width: 98%;
                   5777:     margin: 0;
                   5778:     position: fixed;
                   5779:     top: 8.5em;
                   5780:     bottom: 0;
                   5781: }
                   5782: 
                   5783: .LC_iframecontainer iframe{
                   5784:     border: none;
                   5785:     width: 100%;
                   5786:     height: 100%;
                   5787: }
                   5788: 
1.778     bisitz   5789: .LC_filename {
                   5790:   font-family: $mono;
                   5791:   white-space:pre;
1.921     bisitz   5792:   font-size: 120%;
1.778     bisitz   5793: }
                   5794: 
                   5795: .LC_fileicon {
                   5796:   border: none;
                   5797:   height: 1.3em;
                   5798:   vertical-align: text-bottom;
                   5799:   margin-right: 0.3em;
                   5800:   text-decoration:none;
                   5801: }
                   5802: 
1.1008    www      5803: .LC_setting {
                   5804:   text-decoration:underline;
                   5805: }
                   5806: 
1.350     albertel 5807: .LC_error {
                   5808:   color: red;
                   5809: }
1.795     www      5810: 
1.1097    bisitz   5811: .LC_warning {
                   5812:   color: darkorange;
                   5813: }
                   5814: 
1.457     albertel 5815: .LC_diff_removed {
1.733     bisitz   5816:   color: red;
1.394     albertel 5817: }
1.532     albertel 5818: 
                   5819: .LC_info,
1.457     albertel 5820: .LC_success,
                   5821: .LC_diff_added {
1.350     albertel 5822:   color: green;
                   5823: }
1.795     www      5824: 
1.802     bisitz   5825: div.LC_confirm_box {
                   5826:   background-color: #FAFAFA;
                   5827:   border: 1px solid $lg_border_color;
                   5828:   margin-right: 0;
                   5829:   padding: 5px;
                   5830: }
                   5831: 
                   5832: div.LC_confirm_box .LC_error img,
                   5833: div.LC_confirm_box .LC_success img {
                   5834:   vertical-align: middle;
                   5835: }
                   5836: 
1.440     albertel 5837: .LC_icon {
1.771     droeschl 5838:   border: none;
1.790     droeschl 5839:   vertical-align: middle;
1.771     droeschl 5840: }
                   5841: 
1.543     albertel 5842: .LC_docs_spacer {
                   5843:   width: 25px;
                   5844:   height: 1px;
1.771     droeschl 5845:   border: none;
1.543     albertel 5846: }
1.346     albertel 5847: 
1.532     albertel 5848: .LC_internal_info {
1.735     bisitz   5849:   color: #999999;
1.532     albertel 5850: }
                   5851: 
1.794     www      5852: .LC_discussion {
1.1050    www      5853:   background: $data_table_dark;
1.911     bisitz   5854:   border: 1px solid black;
                   5855:   margin: 2px;
1.794     www      5856: }
                   5857: 
                   5858: .LC_disc_action_left {
1.1050    www      5859:   background: $sidebg;
1.911     bisitz   5860:   text-align: left;
1.1050    www      5861:   padding: 4px;
                   5862:   margin: 2px;
1.794     www      5863: }
                   5864: 
                   5865: .LC_disc_action_right {
1.1050    www      5866:   background: $sidebg;
1.911     bisitz   5867:   text-align: right;
1.1050    www      5868:   padding: 4px;
                   5869:   margin: 2px;
1.794     www      5870: }
                   5871: 
                   5872: .LC_disc_new_item {
1.911     bisitz   5873:   background: white;
                   5874:   border: 2px solid red;
1.1050    www      5875:   margin: 4px;
                   5876:   padding: 4px;
1.794     www      5877: }
                   5878: 
                   5879: .LC_disc_old_item {
1.911     bisitz   5880:   background: white;
1.1050    www      5881:   margin: 4px;
                   5882:   padding: 4px;
1.794     www      5883: }
                   5884: 
1.458     albertel 5885: table.LC_pastsubmission {
                   5886:   border: 1px solid black;
                   5887:   margin: 2px;
                   5888: }
                   5889: 
1.924     bisitz   5890: table#LC_menubuttons {
1.345     albertel 5891:   width: 100%;
                   5892:   background: $pgbg;
1.392     albertel 5893:   border: 2px;
1.402     albertel 5894:   border-collapse: separate;
1.803     bisitz   5895:   padding: 0;
1.345     albertel 5896: }
1.392     albertel 5897: 
1.801     tempelho 5898: table#LC_title_bar a {
                   5899:   color: $fontmenu;
                   5900: }
1.836     bisitz   5901: 
1.807     droeschl 5902: table#LC_title_bar {
1.819     tempelho 5903:   clear: both;
1.836     bisitz   5904:   display: none;
1.807     droeschl 5905: }
                   5906: 
1.795     www      5907: table#LC_title_bar,
1.933     droeschl 5908: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5909: table#LC_title_bar.LC_with_remote {
1.359     albertel 5910:   width: 100%;
1.392     albertel 5911:   border-color: $pgbg;
                   5912:   border-style: solid;
                   5913:   border-width: $border;
1.379     albertel 5914:   background: $pgbg;
1.801     tempelho 5915:   color: $fontmenu;
1.392     albertel 5916:   border-collapse: collapse;
1.803     bisitz   5917:   padding: 0;
1.819     tempelho 5918:   margin: 0;
1.359     albertel 5919: }
1.795     www      5920: 
1.933     droeschl 5921: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5922:     margin: 0;
                   5923:     padding: 0;
1.933     droeschl 5924:     position: relative;
                   5925:     list-style: none;
1.913     droeschl 5926: }
1.933     droeschl 5927: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5928:     display: inline;
                   5929: }
1.933     droeschl 5930: 
                   5931: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5932:     padding: 0;
1.933     droeschl 5933:     margin: 0;
                   5934:     float: left;
1.913     droeschl 5935: }
1.933     droeschl 5936: .LC_breadcrumb_tools_tools {
                   5937:     padding: 0;
                   5938:     margin: 0;
1.913     droeschl 5939:     float: right;
                   5940: }
                   5941: 
1.359     albertel 5942: table#LC_title_bar td {
                   5943:   background: $tabbg;
                   5944: }
1.795     www      5945: 
1.911     bisitz   5946: table#LC_menubuttons img {
1.803     bisitz   5947:   border: none;
1.346     albertel 5948: }
1.795     www      5949: 
1.842     droeschl 5950: .LC_breadcrumbs_component {
1.911     bisitz   5951:   float: right;
                   5952:   margin: 0 1em;
1.357     albertel 5953: }
1.842     droeschl 5954: .LC_breadcrumbs_component img {
1.911     bisitz   5955:   vertical-align: middle;
1.777     tempelho 5956: }
1.795     www      5957: 
1.383     albertel 5958: td.LC_table_cell_checkbox {
                   5959:   text-align: center;
                   5960: }
1.795     www      5961: 
                   5962: .LC_fontsize_small {
1.911     bisitz   5963:   font-size: 70%;
1.705     tempelho 5964: }
                   5965: 
1.844     bisitz   5966: #LC_breadcrumbs {
1.911     bisitz   5967:   clear:both;
                   5968:   background: $sidebg;
                   5969:   border-bottom: 1px solid $lg_border_color;
                   5970:   line-height: 2.5em;
1.933     droeschl 5971:   overflow: hidden;
1.911     bisitz   5972:   margin: 0;
                   5973:   padding: 0;
1.995     raeburn  5974:   text-align: left;
1.819     tempelho 5975: }
1.862     bisitz   5976: 
1.1098    bisitz   5977: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5978:   clear:both;
                   5979:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5980:   border: 1px solid $sidebg;
1.1098    bisitz   5981:   margin: 0 0 10px 0;
1.966     bisitz   5982:   padding: 3px;
1.995     raeburn  5983:   text-align: left;
1.822     bisitz   5984: }
                   5985: 
1.795     www      5986: .LC_fontsize_medium {
1.911     bisitz   5987:   font-size: 85%;
1.705     tempelho 5988: }
                   5989: 
1.795     www      5990: .LC_fontsize_large {
1.911     bisitz   5991:   font-size: 120%;
1.705     tempelho 5992: }
                   5993: 
1.346     albertel 5994: .LC_menubuttons_inline_text {
                   5995:   color: $font;
1.698     harmsja  5996:   font-size: 90%;
1.701     harmsja  5997:   padding-left:3px;
1.346     albertel 5998: }
                   5999: 
1.934     droeschl 6000: .LC_menubuttons_inline_text img{
                   6001:   vertical-align: middle;
                   6002: }
                   6003: 
1.1051    www      6004: li.LC_menubuttons_inline_text img {
1.951     onken    6005:   cursor:pointer;
1.1002    droeschl 6006:   text-decoration: none;
1.951     onken    6007: }
                   6008: 
1.526     www      6009: .LC_menubuttons_link {
                   6010:   text-decoration: none;
                   6011: }
1.795     www      6012: 
1.522     albertel 6013: .LC_menubuttons_category {
1.521     www      6014:   color: $font;
1.526     www      6015:   background: $pgbg;
1.521     www      6016:   font-size: larger;
                   6017:   font-weight: bold;
                   6018: }
                   6019: 
1.346     albertel 6020: td.LC_menubuttons_text {
1.911     bisitz   6021:   color: $font;
1.346     albertel 6022: }
1.706     harmsja  6023: 
1.346     albertel 6024: .LC_current_location {
                   6025:   background: $tabbg;
                   6026: }
1.795     www      6027: 
1.938     bisitz   6028: table.LC_data_table {
1.347     albertel 6029:   border: 1px solid #000000;
1.402     albertel 6030:   border-collapse: separate;
1.426     albertel 6031:   border-spacing: 1px;
1.610     albertel 6032:   background: $pgbg;
1.347     albertel 6033: }
1.795     www      6034: 
1.422     albertel 6035: .LC_data_table_dense {
                   6036:   font-size: small;
                   6037: }
1.795     www      6038: 
1.507     raeburn  6039: table.LC_nested_outer {
                   6040:   border: 1px solid #000000;
1.589     raeburn  6041:   border-collapse: collapse;
1.803     bisitz   6042:   border-spacing: 0;
1.507     raeburn  6043:   width: 100%;
                   6044: }
1.795     www      6045: 
1.879     raeburn  6046: table.LC_innerpickbox,
1.507     raeburn  6047: table.LC_nested {
1.803     bisitz   6048:   border: none;
1.589     raeburn  6049:   border-collapse: collapse;
1.803     bisitz   6050:   border-spacing: 0;
1.507     raeburn  6051:   width: 100%;
                   6052: }
1.795     www      6053: 
1.911     bisitz   6054: table.LC_data_table tr th,
                   6055: table.LC_calendar tr th,
1.879     raeburn  6056: table.LC_prior_tries tr th,
                   6057: table.LC_innerpickbox tr th {
1.349     albertel 6058:   font-weight: bold;
                   6059:   background-color: $data_table_head;
1.801     tempelho 6060:   color:$fontmenu;
1.701     harmsja  6061:   font-size:90%;
1.347     albertel 6062: }
1.795     www      6063: 
1.879     raeburn  6064: table.LC_innerpickbox tr th,
                   6065: table.LC_innerpickbox tr td {
                   6066:   vertical-align: top;
                   6067: }
                   6068: 
1.711     raeburn  6069: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6070:   background-color: #CCCCCC;
1.711     raeburn  6071:   font-weight: bold;
                   6072:   text-align: left;
                   6073: }
1.795     www      6074: 
1.912     bisitz   6075: table.LC_data_table tr.LC_odd_row > td {
                   6076:   background-color: $data_table_light;
                   6077:   padding: 2px;
                   6078:   vertical-align: top;
                   6079: }
                   6080: 
1.809     bisitz   6081: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6082:   background-color: $data_table_light;
1.912     bisitz   6083:   vertical-align: top;
                   6084: }
                   6085: 
                   6086: table.LC_data_table tr.LC_even_row > td {
                   6087:   background-color: $data_table_dark;
1.425     albertel 6088:   padding: 2px;
1.900     bisitz   6089:   vertical-align: top;
1.347     albertel 6090: }
1.795     www      6091: 
1.809     bisitz   6092: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6093:   background-color: $data_table_dark;
1.900     bisitz   6094:   vertical-align: top;
1.347     albertel 6095: }
1.795     www      6096: 
1.425     albertel 6097: table.LC_data_table tr.LC_data_table_highlight td {
                   6098:   background-color: $data_table_darker;
                   6099: }
1.795     www      6100: 
1.639     raeburn  6101: table.LC_data_table tr td.LC_leftcol_header {
                   6102:   background-color: $data_table_head;
                   6103:   font-weight: bold;
                   6104: }
1.795     www      6105: 
1.451     albertel 6106: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6107: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6108:   font-weight: bold;
                   6109:   font-style: italic;
                   6110:   text-align: center;
                   6111:   padding: 8px;
1.347     albertel 6112: }
1.795     www      6113: 
1.1114    raeburn  6114: table.LC_data_table tr.LC_empty_row td,
                   6115: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6116:   background-color: $sidebg;
                   6117: }
                   6118: 
                   6119: table.LC_nested tr.LC_empty_row td {
                   6120:   background-color: #FFFFFF;
                   6121: }
                   6122: 
1.890     droeschl 6123: table.LC_caption {
                   6124: }
                   6125: 
1.507     raeburn  6126: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6127:   padding: 4ex
                   6128: }
1.795     www      6129: 
1.507     raeburn  6130: table.LC_nested_outer tr th {
                   6131:   font-weight: bold;
1.801     tempelho 6132:   color:$fontmenu;
1.507     raeburn  6133:   background-color: $data_table_head;
1.701     harmsja  6134:   font-size: small;
1.507     raeburn  6135:   border-bottom: 1px solid #000000;
                   6136: }
1.795     www      6137: 
1.507     raeburn  6138: table.LC_nested_outer tr td.LC_subheader {
                   6139:   background-color: $data_table_head;
                   6140:   font-weight: bold;
                   6141:   font-size: small;
                   6142:   border-bottom: 1px solid #000000;
                   6143:   text-align: right;
1.451     albertel 6144: }
1.795     www      6145: 
1.507     raeburn  6146: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6147:   background-color: #CCCCCC;
1.451     albertel 6148:   font-weight: bold;
                   6149:   font-size: small;
1.507     raeburn  6150:   text-align: center;
                   6151: }
1.795     www      6152: 
1.589     raeburn  6153: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6154: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6155:   text-align: left;
1.451     albertel 6156: }
1.795     www      6157: 
1.507     raeburn  6158: table.LC_nested td {
1.735     bisitz   6159:   background-color: #FFFFFF;
1.451     albertel 6160:   font-size: small;
1.507     raeburn  6161: }
1.795     www      6162: 
1.507     raeburn  6163: table.LC_nested_outer tr th.LC_right_item,
                   6164: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6165: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6166: table.LC_nested tr td.LC_right_item {
1.451     albertel 6167:   text-align: right;
                   6168: }
                   6169: 
1.507     raeburn  6170: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6171:   background-color: #EEEEEE;
1.451     albertel 6172: }
                   6173: 
1.473     raeburn  6174: table.LC_createuser {
                   6175: }
                   6176: 
                   6177: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6178:   font-size: small;
1.473     raeburn  6179: }
                   6180: 
                   6181: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6182:   background-color: #CCCCCC;
1.473     raeburn  6183:   font-weight: bold;
                   6184:   text-align: center;
                   6185: }
                   6186: 
1.349     albertel 6187: table.LC_calendar {
                   6188:   border: 1px solid #000000;
                   6189:   border-collapse: collapse;
1.917     raeburn  6190:   width: 98%;
1.349     albertel 6191: }
1.795     www      6192: 
1.349     albertel 6193: table.LC_calendar_pickdate {
                   6194:   font-size: xx-small;
                   6195: }
1.795     www      6196: 
1.349     albertel 6197: table.LC_calendar tr td {
                   6198:   border: 1px solid #000000;
                   6199:   vertical-align: top;
1.917     raeburn  6200:   width: 14%;
1.349     albertel 6201: }
1.795     www      6202: 
1.349     albertel 6203: table.LC_calendar tr td.LC_calendar_day_empty {
                   6204:   background-color: $data_table_dark;
                   6205: }
1.795     www      6206: 
1.779     bisitz   6207: table.LC_calendar tr td.LC_calendar_day_current {
                   6208:   background-color: $data_table_highlight;
1.777     tempelho 6209: }
1.795     www      6210: 
1.938     bisitz   6211: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6212:   background-color: $mail_new;
                   6213: }
1.795     www      6214: 
1.938     bisitz   6215: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6216:   background-color: $mail_new_hover;
                   6217: }
1.795     www      6218: 
1.938     bisitz   6219: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6220:   background-color: $mail_read;
                   6221: }
1.795     www      6222: 
1.938     bisitz   6223: /*
                   6224: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6225:   background-color: $mail_read_hover;
                   6226: }
1.938     bisitz   6227: */
1.795     www      6228: 
1.938     bisitz   6229: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6230:   background-color: $mail_replied;
                   6231: }
1.795     www      6232: 
1.938     bisitz   6233: /*
                   6234: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6235:   background-color: $mail_replied_hover;
                   6236: }
1.938     bisitz   6237: */
1.795     www      6238: 
1.938     bisitz   6239: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6240:   background-color: $mail_other;
                   6241: }
1.795     www      6242: 
1.938     bisitz   6243: /*
                   6244: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6245:   background-color: $mail_other_hover;
                   6246: }
1.938     bisitz   6247: */
1.494     raeburn  6248: 
1.777     tempelho 6249: table.LC_data_table tr > td.LC_browser_file,
                   6250: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6251:   background: #AAEE77;
1.389     albertel 6252: }
1.795     www      6253: 
1.777     tempelho 6254: table.LC_data_table tr > td.LC_browser_file_locked,
                   6255: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6256:   background: #FFAA99;
1.387     albertel 6257: }
1.795     www      6258: 
1.777     tempelho 6259: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6260:   background: #888888;
1.779     bisitz   6261: }
1.795     www      6262: 
1.777     tempelho 6263: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6264: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6265:   background: #F8F866;
1.777     tempelho 6266: }
1.795     www      6267: 
1.696     bisitz   6268: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6269:   background: #E0E8FF;
1.387     albertel 6270: }
1.696     bisitz   6271: 
1.707     bisitz   6272: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6273:   /* background: #77FF77; */
1.707     bisitz   6274: }
1.795     www      6275: 
1.707     bisitz   6276: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6277:   border-right: 8px solid #FFFF77;
1.707     bisitz   6278: }
1.795     www      6279: 
1.707     bisitz   6280: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6281:   border-right: 8px solid #FFAA77;
1.707     bisitz   6282: }
1.795     www      6283: 
1.707     bisitz   6284: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6285:   border-right: 8px solid #FF7777;
1.707     bisitz   6286: }
1.795     www      6287: 
1.707     bisitz   6288: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6289:   border-right: 8px solid #AAFF77;
1.707     bisitz   6290: }
1.795     www      6291: 
1.707     bisitz   6292: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6293:   border-right: 8px solid #11CC55;
1.707     bisitz   6294: }
                   6295: 
1.388     albertel 6296: span.LC_current_location {
1.701     harmsja  6297:   font-size:larger;
1.388     albertel 6298:   background: $pgbg;
                   6299: }
1.387     albertel 6300: 
1.1029    www      6301: span.LC_current_nav_location {
                   6302:   font-weight:bold;
                   6303:   background: $sidebg;
                   6304: }
                   6305: 
1.395     albertel 6306: span.LC_parm_menu_item {
                   6307:   font-size: larger;
                   6308: }
1.795     www      6309: 
1.395     albertel 6310: span.LC_parm_scope_all {
                   6311:   color: red;
                   6312: }
1.795     www      6313: 
1.395     albertel 6314: span.LC_parm_scope_folder {
                   6315:   color: green;
                   6316: }
1.795     www      6317: 
1.395     albertel 6318: span.LC_parm_scope_resource {
                   6319:   color: orange;
                   6320: }
1.795     www      6321: 
1.395     albertel 6322: span.LC_parm_part {
                   6323:   color: blue;
                   6324: }
1.795     www      6325: 
1.911     bisitz   6326: span.LC_parm_folder,
                   6327: span.LC_parm_symb {
1.395     albertel 6328:   font-size: x-small;
                   6329:   font-family: $mono;
                   6330:   color: #AAAAAA;
                   6331: }
                   6332: 
1.977     bisitz   6333: ul.LC_parm_parmlist li {
                   6334:   display: inline-block;
                   6335:   padding: 0.3em 0.8em;
                   6336:   vertical-align: top;
                   6337:   width: 150px;
                   6338:   border-top:1px solid $lg_border_color;
                   6339: }
                   6340: 
1.795     www      6341: td.LC_parm_overview_level_menu,
                   6342: td.LC_parm_overview_map_menu,
                   6343: td.LC_parm_overview_parm_selectors,
                   6344: td.LC_parm_overview_restrictions  {
1.396     albertel 6345:   border: 1px solid black;
                   6346:   border-collapse: collapse;
                   6347: }
1.795     www      6348: 
1.396     albertel 6349: table.LC_parm_overview_restrictions td {
                   6350:   border-width: 1px 4px 1px 4px;
                   6351:   border-style: solid;
                   6352:   border-color: $pgbg;
                   6353:   text-align: center;
                   6354: }
1.795     www      6355: 
1.396     albertel 6356: table.LC_parm_overview_restrictions th {
                   6357:   background: $tabbg;
                   6358:   border-width: 1px 4px 1px 4px;
                   6359:   border-style: solid;
                   6360:   border-color: $pgbg;
                   6361: }
1.795     www      6362: 
1.398     albertel 6363: table#LC_helpmenu {
1.803     bisitz   6364:   border: none;
1.398     albertel 6365:   height: 55px;
1.803     bisitz   6366:   border-spacing: 0;
1.398     albertel 6367: }
                   6368: 
                   6369: table#LC_helpmenu fieldset legend {
                   6370:   font-size: larger;
                   6371: }
1.795     www      6372: 
1.397     albertel 6373: table#LC_helpmenu_links {
                   6374:   width: 100%;
                   6375:   border: 1px solid black;
                   6376:   background: $pgbg;
1.803     bisitz   6377:   padding: 0;
1.397     albertel 6378:   border-spacing: 1px;
                   6379: }
1.795     www      6380: 
1.397     albertel 6381: table#LC_helpmenu_links tr td {
                   6382:   padding: 1px;
                   6383:   background: $tabbg;
1.399     albertel 6384:   text-align: center;
                   6385:   font-weight: bold;
1.397     albertel 6386: }
1.396     albertel 6387: 
1.795     www      6388: table#LC_helpmenu_links a:link,
                   6389: table#LC_helpmenu_links a:visited,
1.397     albertel 6390: table#LC_helpmenu_links a:active {
                   6391:   text-decoration: none;
                   6392:   color: $font;
                   6393: }
1.795     www      6394: 
1.397     albertel 6395: table#LC_helpmenu_links a:hover {
                   6396:   text-decoration: underline;
                   6397:   color: $vlink;
                   6398: }
1.396     albertel 6399: 
1.417     albertel 6400: .LC_chrt_popup_exists {
                   6401:   border: 1px solid #339933;
                   6402:   margin: -1px;
                   6403: }
1.795     www      6404: 
1.417     albertel 6405: .LC_chrt_popup_up {
                   6406:   border: 1px solid yellow;
                   6407:   margin: -1px;
                   6408: }
1.795     www      6409: 
1.417     albertel 6410: .LC_chrt_popup {
                   6411:   border: 1px solid #8888FF;
                   6412:   background: #CCCCFF;
                   6413: }
1.795     www      6414: 
1.421     albertel 6415: table.LC_pick_box {
                   6416:   border-collapse: separate;
                   6417:   background: white;
                   6418:   border: 1px solid black;
                   6419:   border-spacing: 1px;
                   6420: }
1.795     www      6421: 
1.421     albertel 6422: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6423:   background: $sidebg;
1.421     albertel 6424:   font-weight: bold;
1.900     bisitz   6425:   text-align: left;
1.740     bisitz   6426:   vertical-align: top;
1.421     albertel 6427:   width: 184px;
                   6428:   padding: 8px;
                   6429: }
1.795     www      6430: 
1.579     raeburn  6431: table.LC_pick_box td.LC_pick_box_value {
                   6432:   text-align: left;
                   6433:   padding: 8px;
                   6434: }
1.795     www      6435: 
1.579     raeburn  6436: table.LC_pick_box td.LC_pick_box_select {
                   6437:   text-align: left;
                   6438:   padding: 8px;
                   6439: }
1.795     www      6440: 
1.424     albertel 6441: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6442:   padding: 0;
1.421     albertel 6443:   height: 1px;
                   6444:   background: black;
                   6445: }
1.795     www      6446: 
1.421     albertel 6447: table.LC_pick_box td.LC_pick_box_submit {
                   6448:   text-align: right;
                   6449: }
1.795     www      6450: 
1.579     raeburn  6451: table.LC_pick_box td.LC_evenrow_value {
                   6452:   text-align: left;
                   6453:   padding: 8px;
                   6454:   background-color: $data_table_light;
                   6455: }
1.795     www      6456: 
1.579     raeburn  6457: table.LC_pick_box td.LC_oddrow_value {
                   6458:   text-align: left;
                   6459:   padding: 8px;
                   6460:   background-color: $data_table_light;
                   6461: }
1.795     www      6462: 
1.579     raeburn  6463: span.LC_helpform_receipt_cat {
                   6464:   font-weight: bold;
                   6465: }
1.795     www      6466: 
1.424     albertel 6467: table.LC_group_priv_box {
                   6468:   background: white;
                   6469:   border: 1px solid black;
                   6470:   border-spacing: 1px;
                   6471: }
1.795     www      6472: 
1.424     albertel 6473: table.LC_group_priv_box td.LC_pick_box_title {
                   6474:   background: $tabbg;
                   6475:   font-weight: bold;
                   6476:   text-align: right;
                   6477:   width: 184px;
                   6478: }
1.795     www      6479: 
1.424     albertel 6480: table.LC_group_priv_box td.LC_groups_fixed {
                   6481:   background: $data_table_light;
                   6482:   text-align: center;
                   6483: }
1.795     www      6484: 
1.424     albertel 6485: table.LC_group_priv_box td.LC_groups_optional {
                   6486:   background: $data_table_dark;
                   6487:   text-align: center;
                   6488: }
1.795     www      6489: 
1.424     albertel 6490: table.LC_group_priv_box td.LC_groups_functionality {
                   6491:   background: $data_table_darker;
                   6492:   text-align: center;
                   6493:   font-weight: bold;
                   6494: }
1.795     www      6495: 
1.424     albertel 6496: table.LC_group_priv td {
                   6497:   text-align: left;
1.803     bisitz   6498:   padding: 0;
1.424     albertel 6499: }
                   6500: 
                   6501: .LC_navbuttons {
                   6502:   margin: 2ex 0ex 2ex 0ex;
                   6503: }
1.795     www      6504: 
1.423     albertel 6505: .LC_topic_bar {
                   6506:   font-weight: bold;
                   6507:   background: $tabbg;
1.918     wenzelju 6508:   margin: 1em 0em 1em 2em;
1.805     bisitz   6509:   padding: 3px;
1.918     wenzelju 6510:   font-size: 1.2em;
1.423     albertel 6511: }
1.795     www      6512: 
1.423     albertel 6513: .LC_topic_bar span {
1.918     wenzelju 6514:   left: 0.5em;
                   6515:   position: absolute;
1.423     albertel 6516:   vertical-align: middle;
1.918     wenzelju 6517:   font-size: 1.2em;
1.423     albertel 6518: }
1.795     www      6519: 
1.423     albertel 6520: table.LC_course_group_status {
                   6521:   margin: 20px;
                   6522: }
1.795     www      6523: 
1.423     albertel 6524: table.LC_status_selector td {
                   6525:   vertical-align: top;
                   6526:   text-align: center;
1.424     albertel 6527:   padding: 4px;
                   6528: }
1.795     www      6529: 
1.599     albertel 6530: div.LC_feedback_link {
1.616     albertel 6531:   clear: both;
1.829     kalberla 6532:   background: $sidebg;
1.779     bisitz   6533:   width: 100%;
1.829     kalberla 6534:   padding-bottom: 10px;
                   6535:   border: 1px $tabbg solid;
1.833     kalberla 6536:   height: 22px;
                   6537:   line-height: 22px;
                   6538:   padding-top: 5px;
                   6539: }
                   6540: 
                   6541: div.LC_feedback_link img {
                   6542:   height: 22px;
1.867     kalberla 6543:   vertical-align:middle;
1.829     kalberla 6544: }
                   6545: 
1.911     bisitz   6546: div.LC_feedback_link a {
1.829     kalberla 6547:   text-decoration: none;
1.489     raeburn  6548: }
1.795     www      6549: 
1.867     kalberla 6550: div.LC_comblock {
1.911     bisitz   6551:   display:inline;
1.867     kalberla 6552:   color:$font;
                   6553:   font-size:90%;
                   6554: }
                   6555: 
                   6556: div.LC_feedback_link div.LC_comblock {
                   6557:   padding-left:5px;
                   6558: }
                   6559: 
                   6560: div.LC_feedback_link div.LC_comblock a {
                   6561:   color:$font;
                   6562: }
                   6563: 
1.489     raeburn  6564: span.LC_feedback_link {
1.858     bisitz   6565:   /* background: $feedback_link_bg; */
1.599     albertel 6566:   font-size: larger;
                   6567: }
1.795     www      6568: 
1.599     albertel 6569: span.LC_message_link {
1.858     bisitz   6570:   /* background: $feedback_link_bg; */
1.599     albertel 6571:   font-size: larger;
                   6572:   position: absolute;
                   6573:   right: 1em;
1.489     raeburn  6574: }
1.421     albertel 6575: 
1.515     albertel 6576: table.LC_prior_tries {
1.524     albertel 6577:   border: 1px solid #000000;
                   6578:   border-collapse: separate;
                   6579:   border-spacing: 1px;
1.515     albertel 6580: }
1.523     albertel 6581: 
1.515     albertel 6582: table.LC_prior_tries td {
1.524     albertel 6583:   padding: 2px;
1.515     albertel 6584: }
1.523     albertel 6585: 
                   6586: .LC_answer_correct {
1.795     www      6587:   background: lightgreen;
                   6588:   color: darkgreen;
                   6589:   padding: 6px;
1.523     albertel 6590: }
1.795     www      6591: 
1.523     albertel 6592: .LC_answer_charged_try {
1.797     www      6593:   background: #FFAAAA;
1.795     www      6594:   color: darkred;
                   6595:   padding: 6px;
1.523     albertel 6596: }
1.795     www      6597: 
1.779     bisitz   6598: .LC_answer_not_charged_try,
1.523     albertel 6599: .LC_answer_no_grade,
                   6600: .LC_answer_late {
1.795     www      6601:   background: lightyellow;
1.523     albertel 6602:   color: black;
1.795     www      6603:   padding: 6px;
1.523     albertel 6604: }
1.795     www      6605: 
1.523     albertel 6606: .LC_answer_previous {
1.795     www      6607:   background: lightblue;
                   6608:   color: darkblue;
                   6609:   padding: 6px;
1.523     albertel 6610: }
1.795     www      6611: 
1.779     bisitz   6612: .LC_answer_no_message {
1.777     tempelho 6613:   background: #FFFFFF;
                   6614:   color: black;
1.795     www      6615:   padding: 6px;
1.779     bisitz   6616: }
1.795     www      6617: 
1.779     bisitz   6618: .LC_answer_unknown {
                   6619:   background: orange;
                   6620:   color: black;
1.795     www      6621:   padding: 6px;
1.777     tempelho 6622: }
1.795     www      6623: 
1.529     albertel 6624: span.LC_prior_numerical,
                   6625: span.LC_prior_string,
                   6626: span.LC_prior_custom,
                   6627: span.LC_prior_reaction,
                   6628: span.LC_prior_math {
1.925     bisitz   6629:   font-family: $mono;
1.523     albertel 6630:   white-space: pre;
                   6631: }
                   6632: 
1.525     albertel 6633: span.LC_prior_string {
1.925     bisitz   6634:   font-family: $mono;
1.525     albertel 6635:   white-space: pre;
                   6636: }
                   6637: 
1.523     albertel 6638: table.LC_prior_option {
                   6639:   width: 100%;
                   6640:   border-collapse: collapse;
                   6641: }
1.795     www      6642: 
1.911     bisitz   6643: table.LC_prior_rank,
1.795     www      6644: table.LC_prior_match {
1.528     albertel 6645:   border-collapse: collapse;
                   6646: }
1.795     www      6647: 
1.528     albertel 6648: table.LC_prior_option tr td,
                   6649: table.LC_prior_rank tr td,
                   6650: table.LC_prior_match tr td {
1.524     albertel 6651:   border: 1px solid #000000;
1.515     albertel 6652: }
                   6653: 
1.855     bisitz   6654: .LC_nobreak {
1.544     albertel 6655:   white-space: nowrap;
1.519     raeburn  6656: }
                   6657: 
1.576     raeburn  6658: span.LC_cusr_emph {
                   6659:   font-style: italic;
                   6660: }
                   6661: 
1.633     raeburn  6662: span.LC_cusr_subheading {
                   6663:   font-weight: normal;
                   6664:   font-size: 85%;
                   6665: }
                   6666: 
1.861     bisitz   6667: div.LC_docs_entry_move {
1.859     bisitz   6668:   border: 1px solid #BBBBBB;
1.545     albertel 6669:   background: #DDDDDD;
1.861     bisitz   6670:   width: 22px;
1.859     bisitz   6671:   padding: 1px;
                   6672:   margin: 0;
1.545     albertel 6673: }
                   6674: 
1.861     bisitz   6675: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6676: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6677:   font-size: x-small;
                   6678: }
1.795     www      6679: 
1.861     bisitz   6680: .LC_docs_entry_parameter {
                   6681:   white-space: nowrap;
                   6682: }
                   6683: 
1.544     albertel 6684: .LC_docs_copy {
1.545     albertel 6685:   color: #000099;
1.544     albertel 6686: }
1.795     www      6687: 
1.544     albertel 6688: .LC_docs_cut {
1.545     albertel 6689:   color: #550044;
1.544     albertel 6690: }
1.795     www      6691: 
1.544     albertel 6692: .LC_docs_rename {
1.545     albertel 6693:   color: #009900;
1.544     albertel 6694: }
1.795     www      6695: 
1.544     albertel 6696: .LC_docs_remove {
1.545     albertel 6697:   color: #990000;
                   6698: }
                   6699: 
1.547     albertel 6700: .LC_docs_reinit_warn,
                   6701: .LC_docs_ext_edit {
                   6702:   font-size: x-small;
                   6703: }
                   6704: 
1.545     albertel 6705: table.LC_docs_adddocs td,
                   6706: table.LC_docs_adddocs th {
                   6707:   border: 1px solid #BBBBBB;
                   6708:   padding: 4px;
                   6709:   background: #DDDDDD;
1.543     albertel 6710: }
                   6711: 
1.584     albertel 6712: table.LC_sty_begin {
                   6713:   background: #BBFFBB;
                   6714: }
1.795     www      6715: 
1.584     albertel 6716: table.LC_sty_end {
                   6717:   background: #FFBBBB;
                   6718: }
                   6719: 
1.589     raeburn  6720: table.LC_double_column {
1.803     bisitz   6721:   border-width: 0;
1.589     raeburn  6722:   border-collapse: collapse;
                   6723:   width: 100%;
                   6724:   padding: 2px;
                   6725: }
                   6726: 
                   6727: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6728:   top: 2px;
1.589     raeburn  6729:   left: 2px;
                   6730:   width: 47%;
                   6731:   vertical-align: top;
                   6732: }
                   6733: 
                   6734: table.LC_double_column tr td.LC_right_col {
                   6735:   top: 2px;
1.779     bisitz   6736:   right: 2px;
1.589     raeburn  6737:   width: 47%;
                   6738:   vertical-align: top;
                   6739: }
                   6740: 
1.591     raeburn  6741: div.LC_left_float {
                   6742:   float: left;
                   6743:   padding-right: 5%;
1.597     albertel 6744:   padding-bottom: 4px;
1.591     raeburn  6745: }
                   6746: 
                   6747: div.LC_clear_float_header {
1.597     albertel 6748:   padding-bottom: 2px;
1.591     raeburn  6749: }
                   6750: 
                   6751: div.LC_clear_float_footer {
1.597     albertel 6752:   padding-top: 10px;
1.591     raeburn  6753:   clear: both;
                   6754: }
                   6755: 
1.597     albertel 6756: div.LC_grade_show_user {
1.941     bisitz   6757: /*  border-left: 5px solid $sidebg; */
                   6758:   border-top: 5px solid #000000;
                   6759:   margin: 50px 0 0 0;
1.936     bisitz   6760:   padding: 15px 0 5px 10px;
1.597     albertel 6761: }
1.795     www      6762: 
1.936     bisitz   6763: div.LC_grade_show_user_odd_row {
1.941     bisitz   6764: /*  border-left: 5px solid #000000; */
                   6765: }
                   6766: 
                   6767: div.LC_grade_show_user div.LC_Box {
                   6768:   margin-right: 50px;
1.597     albertel 6769: }
                   6770: 
                   6771: div.LC_grade_submissions,
                   6772: div.LC_grade_message_center,
1.936     bisitz   6773: div.LC_grade_info_links {
1.597     albertel 6774:   margin: 5px;
                   6775:   width: 99%;
                   6776:   background: #FFFFFF;
                   6777: }
1.795     www      6778: 
1.597     albertel 6779: div.LC_grade_submissions_header,
1.936     bisitz   6780: div.LC_grade_message_center_header {
1.705     tempelho 6781:   font-weight: bold;
                   6782:   font-size: large;
1.597     albertel 6783: }
1.795     www      6784: 
1.597     albertel 6785: div.LC_grade_submissions_body,
1.936     bisitz   6786: div.LC_grade_message_center_body {
1.597     albertel 6787:   border: 1px solid black;
                   6788:   width: 99%;
                   6789:   background: #FFFFFF;
                   6790: }
1.795     www      6791: 
1.613     albertel 6792: table.LC_scantron_action {
                   6793:   width: 100%;
                   6794: }
1.795     www      6795: 
1.613     albertel 6796: table.LC_scantron_action tr th {
1.698     harmsja  6797:   font-weight:bold;
                   6798:   font-style:normal;
1.613     albertel 6799: }
1.795     www      6800: 
1.779     bisitz   6801: .LC_edit_problem_header,
1.614     albertel 6802: div.LC_edit_problem_footer {
1.705     tempelho 6803:   font-weight: normal;
                   6804:   font-size:  medium;
1.602     albertel 6805:   margin: 2px;
1.1060    bisitz   6806:   background-color: $sidebg;
1.600     albertel 6807: }
1.795     www      6808: 
1.600     albertel 6809: div.LC_edit_problem_header,
1.602     albertel 6810: div.LC_edit_problem_header div,
1.614     albertel 6811: div.LC_edit_problem_footer,
                   6812: div.LC_edit_problem_footer div,
1.602     albertel 6813: div.LC_edit_problem_editxml_header,
                   6814: div.LC_edit_problem_editxml_header div {
1.600     albertel 6815:   margin-top: 5px;
1.1205    golterma 6816:   z-index: 100;
1.600     albertel 6817: }
1.795     www      6818: 
1.600     albertel 6819: div.LC_edit_problem_header_title {
1.705     tempelho 6820:   font-weight: bold;
                   6821:   font-size: larger;
1.602     albertel 6822:   background: $tabbg;
                   6823:   padding: 3px;
1.1060    bisitz   6824:   margin: 0 0 5px 0;
1.602     albertel 6825: }
1.795     www      6826: 
1.602     albertel 6827: table.LC_edit_problem_header_title {
                   6828:   width: 100%;
1.600     albertel 6829:   background: $tabbg;
1.602     albertel 6830: }
                   6831: 
                   6832: div.LC_edit_problem_discards {
                   6833:   float: left;
1.1205    golterma 6834: }
                   6835: 
                   6836: div.LC_edit_actionbar {
                   6837:     margin: -5px 0px 0px 0px !important;
                   6838:     background-color: $sidebg;
                   6839:     height: 31px;
1.602     albertel 6840: }
1.795     www      6841: 
1.602     albertel 6842: div.LC_edit_problem_saves {
                   6843:   float: right;
                   6844:   padding-bottom: 5px;
1.600     albertel 6845: }
1.795     www      6846: 
1.1124    bisitz   6847: .LC_edit_opt {
                   6848:   padding-left: 1em;
                   6849:   white-space: nowrap;
                   6850: }
                   6851: 
1.1152    golterma 6852: .LC_edit_problem_latexhelper{
                   6853:     text-align: right;
                   6854: }
                   6855: 
                   6856: #LC_edit_problem_colorful div{
                   6857:     margin-left: 40px;
                   6858: }
                   6859: 
1.1205    golterma 6860: #LC_edit_problem_codemirror div{
                   6861:     margin-left: 0px;
                   6862: }
                   6863: 
1.911     bisitz   6864: img.stift {
1.803     bisitz   6865:   border-width: 0;
                   6866:   vertical-align: middle;
1.677     riegler  6867: }
1.680     riegler  6868: 
1.923     bisitz   6869: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6870:   vertical-align: top;
1.777     tempelho 6871: }
1.795     www      6872: 
1.716     raeburn  6873: div.LC_createcourse {
1.911     bisitz   6874:   margin: 10px 10px 10px 10px;
1.716     raeburn  6875: }
                   6876: 
1.917     raeburn  6877: .LC_dccid {
1.1130    raeburn  6878:   float: right;
1.917     raeburn  6879:   margin: 0.2em 0 0 0;
                   6880:   padding: 0;
                   6881:   font-size: 90%;
                   6882:   display:none;
                   6883: }
                   6884: 
1.897     wenzelju 6885: ol.LC_primary_menu a:hover,
1.721     harmsja  6886: ol#LC_MenuBreadcrumbs a:hover,
                   6887: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6888: ul#LC_secondary_menu a:hover,
1.721     harmsja  6889: .LC_FormSectionClearButton input:hover
1.795     www      6890: ul.LC_TabContent   li:hover a {
1.952     onken    6891:   color:$button_hover;
1.911     bisitz   6892:   text-decoration:none;
1.693     droeschl 6893: }
                   6894: 
1.779     bisitz   6895: h1 {
1.911     bisitz   6896:   padding: 0;
                   6897:   line-height:130%;
1.693     droeschl 6898: }
1.698     harmsja  6899: 
1.911     bisitz   6900: h2,
                   6901: h3,
                   6902: h4,
                   6903: h5,
                   6904: h6 {
                   6905:   margin: 5px 0 5px 0;
                   6906:   padding: 0;
                   6907:   line-height:130%;
1.693     droeschl 6908: }
1.795     www      6909: 
                   6910: .LC_hcell {
1.911     bisitz   6911:   padding:3px 15px 3px 15px;
                   6912:   margin: 0;
                   6913:   background-color:$tabbg;
                   6914:   color:$fontmenu;
                   6915:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6916: }
1.795     www      6917: 
1.840     bisitz   6918: .LC_Box > .LC_hcell {
1.911     bisitz   6919:   margin: 0 -10px 10px -10px;
1.835     bisitz   6920: }
                   6921: 
1.721     harmsja  6922: .LC_noBorder {
1.911     bisitz   6923:   border: 0;
1.698     harmsja  6924: }
1.693     droeschl 6925: 
1.721     harmsja  6926: .LC_FormSectionClearButton input {
1.911     bisitz   6927:   background-color:transparent;
                   6928:   border: none;
                   6929:   cursor:pointer;
                   6930:   text-decoration:underline;
1.693     droeschl 6931: }
1.763     bisitz   6932: 
                   6933: .LC_help_open_topic {
1.911     bisitz   6934:   color: #FFFFFF;
                   6935:   background-color: #EEEEFF;
                   6936:   margin: 1px;
                   6937:   padding: 4px;
                   6938:   border: 1px solid #000033;
                   6939:   white-space: nowrap;
                   6940:   /* vertical-align: middle; */
1.759     neumanie 6941: }
1.693     droeschl 6942: 
1.911     bisitz   6943: dl,
                   6944: ul,
                   6945: div,
                   6946: fieldset {
                   6947:   margin: 10px 10px 10px 0;
                   6948:   /* overflow: hidden; */
1.693     droeschl 6949: }
1.795     www      6950: 
1.1211    raeburn  6951: article.geogebraweb div {
                   6952:     margin: 0;
                   6953: }
                   6954: 
1.838     bisitz   6955: fieldset > legend {
1.911     bisitz   6956:   font-weight: bold;
                   6957:   padding: 0 5px 0 5px;
1.838     bisitz   6958: }
                   6959: 
1.813     bisitz   6960: #LC_nav_bar {
1.911     bisitz   6961:   float: left;
1.995     raeburn  6962:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6963:   margin: 0 0 2px 0;
1.807     droeschl 6964: }
                   6965: 
1.916     droeschl 6966: #LC_realm {
                   6967:   margin: 0.2em 0 0 0;
                   6968:   padding: 0;
                   6969:   font-weight: bold;
                   6970:   text-align: center;
1.995     raeburn  6971:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6972: }
                   6973: 
1.911     bisitz   6974: #LC_nav_bar em {
                   6975:   font-weight: bold;
                   6976:   font-style: normal;
1.807     droeschl 6977: }
                   6978: 
1.897     wenzelju 6979: ol.LC_primary_menu {
1.934     droeschl 6980:   margin: 0;
1.1076    raeburn  6981:   padding: 0;
1.807     droeschl 6982: }
                   6983: 
1.852     droeschl 6984: ol#LC_PathBreadcrumbs {
1.911     bisitz   6985:   margin: 0;
1.693     droeschl 6986: }
                   6987: 
1.897     wenzelju 6988: ol.LC_primary_menu li {
1.1076    raeburn  6989:   color: RGB(80, 80, 80);
                   6990:   vertical-align: middle;
                   6991:   text-align: left;
                   6992:   list-style: none;
1.1205    golterma 6993:   position: relative;
1.1076    raeburn  6994:   float: left;
1.1205    golterma 6995:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   6996:   line-height: 1.5em;
1.1076    raeburn  6997: }
                   6998: 
1.1205    golterma 6999: ol.LC_primary_menu li a,
                   7000: ol.LC_primary_menu li p {
1.1076    raeburn  7001:   display: block;
                   7002:   margin: 0;
                   7003:   padding: 0 5px 0 10px;
                   7004:   text-decoration: none;
                   7005: }
                   7006: 
1.1205    golterma 7007: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7008:   display: inline-block;
                   7009:   width: 95%;
                   7010:   text-align: left;
                   7011: }
                   7012: 
                   7013: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7014:   display: inline-block;	
                   7015:   width: 5%;
                   7016:   float: right;
                   7017:   text-align: right;
                   7018:   font-size: 70%;
                   7019: }
                   7020: 
                   7021: ol.LC_primary_menu ul {
1.1076    raeburn  7022:   display: none;
1.1205    golterma 7023:   width: 15em;
1.1076    raeburn  7024:   background-color: $data_table_light;
1.1205    golterma 7025:   position: absolute;
                   7026:   top: 100%;
1.1076    raeburn  7027: }
                   7028: 
1.1205    golterma 7029: ol.LC_primary_menu ul ul {
                   7030:   left: 100%;
                   7031:   top: 0;
                   7032: }
                   7033: 
                   7034: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7035:   display: block;
                   7036:   position: absolute;
                   7037:   margin: 0;
                   7038:   padding: 0;
1.1078    raeburn  7039:   z-index: 2;
1.1076    raeburn  7040: }
                   7041: 
                   7042: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7043: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7044:   font-size: 90%;
1.911     bisitz   7045:   vertical-align: top;
1.1076    raeburn  7046:   float: none;
1.1079    raeburn  7047:   border-left: 1px solid black;
                   7048:   border-right: 1px solid black;
1.1205    golterma 7049: /* A dark bottom border to visualize different menu options; 
                   7050: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7051:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7052: }
                   7053: 
1.1205    golterma 7054: ol.LC_primary_menu li li p:hover {
                   7055:   color:$button_hover;
                   7056:   text-decoration:none;
                   7057:   background-color:$data_table_dark;
1.1076    raeburn  7058: }
                   7059: 
                   7060: ol.LC_primary_menu li li a:hover {
                   7061:    color:$button_hover;
                   7062:    background-color:$data_table_dark;
1.693     droeschl 7063: }
                   7064: 
1.1205    golterma 7065: /* Font-size equal to the size of the predecessors*/
                   7066: ol.LC_primary_menu li:hover li li {
                   7067:   font-size: 100%;
                   7068: }
                   7069: 
1.897     wenzelju 7070: ol.LC_primary_menu li img {
1.911     bisitz   7071:   vertical-align: bottom;
1.934     droeschl 7072:   height: 1.1em;
1.1077    raeburn  7073:   margin: 0.2em 0 0 0;
1.693     droeschl 7074: }
                   7075: 
1.897     wenzelju 7076: ol.LC_primary_menu a {
1.911     bisitz   7077:   color: RGB(80, 80, 80);
                   7078:   text-decoration: none;
1.693     droeschl 7079: }
1.795     www      7080: 
1.949     droeschl 7081: ol.LC_primary_menu a.LC_new_message {
                   7082:   font-weight:bold;
                   7083:   color: darkred;
                   7084: }
                   7085: 
1.975     raeburn  7086: ol.LC_docs_parameters {
                   7087:   margin-left: 0;
                   7088:   padding: 0;
                   7089:   list-style: none;
                   7090: }
                   7091: 
                   7092: ol.LC_docs_parameters li {
                   7093:   margin: 0;
                   7094:   padding-right: 20px;
                   7095:   display: inline;
                   7096: }
                   7097: 
1.976     raeburn  7098: ol.LC_docs_parameters li:before {
                   7099:   content: "\\002022 \\0020";
                   7100: }
                   7101: 
                   7102: li.LC_docs_parameters_title {
                   7103:   font-weight: bold;
                   7104: }
                   7105: 
                   7106: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7107:   content: "";
                   7108: }
                   7109: 
1.897     wenzelju 7110: ul#LC_secondary_menu {
1.1107    raeburn  7111:   clear: right;
1.911     bisitz   7112:   color: $fontmenu;
                   7113:   background: $tabbg;
                   7114:   list-style: none;
                   7115:   padding: 0;
                   7116:   margin: 0;
                   7117:   width: 100%;
1.995     raeburn  7118:   text-align: left;
1.1107    raeburn  7119:   float: left;
1.808     droeschl 7120: }
                   7121: 
1.897     wenzelju 7122: ul#LC_secondary_menu li {
1.911     bisitz   7123:   font-weight: bold;
                   7124:   line-height: 1.8em;
1.1107    raeburn  7125:   border-right: 1px solid black;
                   7126:   float: left;
                   7127: }
                   7128: 
                   7129: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7130:   background-color: $data_table_light;
                   7131: }
                   7132: 
                   7133: ul#LC_secondary_menu li a {
1.911     bisitz   7134:   padding: 0 0.8em;
1.1107    raeburn  7135: }
                   7136: 
                   7137: ul#LC_secondary_menu li ul {
                   7138:   display: none;
                   7139: }
                   7140: 
                   7141: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7142:   display: block;
                   7143:   position: absolute;
                   7144:   margin: 0;
                   7145:   padding: 0;
                   7146:   list-style:none;
                   7147:   float: none;
                   7148:   background-color: $data_table_light;
                   7149:   z-index: 2;
                   7150:   margin-left: -1px;
                   7151: }
                   7152: 
                   7153: ul#LC_secondary_menu li ul li {
                   7154:   font-size: 90%;
                   7155:   vertical-align: top;
                   7156:   border-left: 1px solid black;
1.911     bisitz   7157:   border-right: 1px solid black;
1.1119    raeburn  7158:   background-color: $data_table_light;
1.1107    raeburn  7159:   list-style:none;
                   7160:   float: none;
                   7161: }
                   7162: 
                   7163: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7164:   background-color: $data_table_dark;
1.807     droeschl 7165: }
                   7166: 
1.847     tempelho 7167: ul.LC_TabContent {
1.911     bisitz   7168:   display:block;
                   7169:   background: $sidebg;
                   7170:   border-bottom: solid 1px $lg_border_color;
                   7171:   list-style:none;
1.1020    raeburn  7172:   margin: -1px -10px 0 -10px;
1.911     bisitz   7173:   padding: 0;
1.693     droeschl 7174: }
                   7175: 
1.795     www      7176: ul.LC_TabContent li,
                   7177: ul.LC_TabContentBigger li {
1.911     bisitz   7178:   float:left;
1.741     harmsja  7179: }
1.795     www      7180: 
1.897     wenzelju 7181: ul#LC_secondary_menu li a {
1.911     bisitz   7182:   color: $fontmenu;
                   7183:   text-decoration: none;
1.693     droeschl 7184: }
1.795     www      7185: 
1.721     harmsja  7186: ul.LC_TabContent {
1.952     onken    7187:   min-height:20px;
1.721     harmsja  7188: }
1.795     www      7189: 
                   7190: ul.LC_TabContent li {
1.911     bisitz   7191:   vertical-align:middle;
1.959     onken    7192:   padding: 0 16px 0 10px;
1.911     bisitz   7193:   background-color:$tabbg;
                   7194:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7195:   border-left: solid 1px $font;
1.721     harmsja  7196: }
1.795     www      7197: 
1.847     tempelho 7198: ul.LC_TabContent .right {
1.911     bisitz   7199:   float:right;
1.847     tempelho 7200: }
                   7201: 
1.911     bisitz   7202: ul.LC_TabContent li a,
                   7203: ul.LC_TabContent li {
                   7204:   color:rgb(47,47,47);
                   7205:   text-decoration:none;
                   7206:   font-size:95%;
                   7207:   font-weight:bold;
1.952     onken    7208:   min-height:20px;
                   7209: }
                   7210: 
1.959     onken    7211: ul.LC_TabContent li a:hover,
                   7212: ul.LC_TabContent li a:focus {
1.952     onken    7213:   color: $button_hover;
1.959     onken    7214:   background:none;
                   7215:   outline:none;
1.952     onken    7216: }
                   7217: 
                   7218: ul.LC_TabContent li:hover {
                   7219:   color: $button_hover;
                   7220:   cursor:pointer;
1.721     harmsja  7221: }
1.795     www      7222: 
1.911     bisitz   7223: ul.LC_TabContent li.active {
1.952     onken    7224:   color: $font;
1.911     bisitz   7225:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7226:   border-bottom:solid 1px #FFFFFF;
                   7227:   cursor: default;
1.744     ehlerst  7228: }
1.795     www      7229: 
1.959     onken    7230: ul.LC_TabContent li.active a {
                   7231:   color:$font;
                   7232:   background:#FFFFFF;
                   7233:   outline: none;
                   7234: }
1.1047    raeburn  7235: 
                   7236: ul.LC_TabContent li.goback {
                   7237:   float: left;
                   7238:   border-left: none;
                   7239: }
                   7240: 
1.870     tempelho 7241: #maincoursedoc {
1.911     bisitz   7242:   clear:both;
1.870     tempelho 7243: }
                   7244: 
                   7245: ul.LC_TabContentBigger {
1.911     bisitz   7246:   display:block;
                   7247:   list-style:none;
                   7248:   padding: 0;
1.870     tempelho 7249: }
                   7250: 
1.795     www      7251: ul.LC_TabContentBigger li {
1.911     bisitz   7252:   vertical-align:bottom;
                   7253:   height: 30px;
                   7254:   font-size:110%;
                   7255:   font-weight:bold;
                   7256:   color: #737373;
1.841     tempelho 7257: }
                   7258: 
1.957     onken    7259: ul.LC_TabContentBigger li.active {
                   7260:   position: relative;
                   7261:   top: 1px;
                   7262: }
                   7263: 
1.870     tempelho 7264: ul.LC_TabContentBigger li a {
1.911     bisitz   7265:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7266:   height: 30px;
                   7267:   line-height: 30px;
                   7268:   text-align: center;
                   7269:   display: block;
                   7270:   text-decoration: none;
1.958     onken    7271:   outline: none;  
1.741     harmsja  7272: }
1.795     www      7273: 
1.870     tempelho 7274: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7275:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7276:   color:$font;
1.744     ehlerst  7277: }
1.795     www      7278: 
1.870     tempelho 7279: ul.LC_TabContentBigger li b {
1.911     bisitz   7280:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7281:   display: block;
                   7282:   float: left;
                   7283:   padding: 0 30px;
1.957     onken    7284:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7285: }
                   7286: 
1.956     onken    7287: ul.LC_TabContentBigger li:hover b {
                   7288:   color:$button_hover;
                   7289: }
                   7290: 
1.870     tempelho 7291: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7292:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7293:   color:$font;
1.957     onken    7294:   border: 0;
1.741     harmsja  7295: }
1.693     droeschl 7296: 
1.870     tempelho 7297: 
1.862     bisitz   7298: ul.LC_CourseBreadcrumbs {
                   7299:   background: $sidebg;
1.1020    raeburn  7300:   height: 2em;
1.862     bisitz   7301:   padding-left: 10px;
1.1020    raeburn  7302:   margin: 0;
1.862     bisitz   7303:   list-style-position: inside;
                   7304: }
                   7305: 
1.911     bisitz   7306: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7307: ol#LC_PathBreadcrumbs {
1.911     bisitz   7308:   padding-left: 10px;
                   7309:   margin: 0;
1.933     droeschl 7310:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7311: }
                   7312: 
1.911     bisitz   7313: ol#LC_MenuBreadcrumbs li,
                   7314: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7315: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7316:   display: inline;
1.933     droeschl 7317:   white-space: normal;  
1.693     droeschl 7318: }
                   7319: 
1.823     bisitz   7320: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7321: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7322:   text-decoration: none;
                   7323:   font-size:90%;
1.693     droeschl 7324: }
1.795     www      7325: 
1.969     droeschl 7326: ol#LC_MenuBreadcrumbs h1 {
                   7327:   display: inline;
                   7328:   font-size: 90%;
                   7329:   line-height: 2.5em;
                   7330:   margin: 0;
                   7331:   padding: 0;
                   7332: }
                   7333: 
1.795     www      7334: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7335:   text-decoration:none;
                   7336:   font-size:100%;
                   7337:   font-weight:bold;
1.693     droeschl 7338: }
1.795     www      7339: 
1.840     bisitz   7340: .LC_Box {
1.911     bisitz   7341:   border: solid 1px $lg_border_color;
                   7342:   padding: 0 10px 10px 10px;
1.746     neumanie 7343: }
1.795     www      7344: 
1.1020    raeburn  7345: .LC_DocsBox {
                   7346:   border: solid 1px $lg_border_color;
                   7347:   padding: 0 0 10px 10px;
                   7348: }
                   7349: 
1.795     www      7350: .LC_AboutMe_Image {
1.911     bisitz   7351:   float:left;
                   7352:   margin-right:10px;
1.747     neumanie 7353: }
1.795     www      7354: 
                   7355: .LC_Clear_AboutMe_Image {
1.911     bisitz   7356:   clear:left;
1.747     neumanie 7357: }
1.795     www      7358: 
1.721     harmsja  7359: dl.LC_ListStyleClean dt {
1.911     bisitz   7360:   padding-right: 5px;
                   7361:   display: table-header-group;
1.693     droeschl 7362: }
                   7363: 
1.721     harmsja  7364: dl.LC_ListStyleClean dd {
1.911     bisitz   7365:   display: table-row;
1.693     droeschl 7366: }
                   7367: 
1.721     harmsja  7368: .LC_ListStyleClean,
                   7369: .LC_ListStyleSimple,
                   7370: .LC_ListStyleNormal,
1.795     www      7371: .LC_ListStyleSpecial {
1.911     bisitz   7372:   /* display:block; */
                   7373:   list-style-position: inside;
                   7374:   list-style-type: none;
                   7375:   overflow: hidden;
                   7376:   padding: 0;
1.693     droeschl 7377: }
                   7378: 
1.721     harmsja  7379: .LC_ListStyleSimple li,
                   7380: .LC_ListStyleSimple dd,
                   7381: .LC_ListStyleNormal li,
                   7382: .LC_ListStyleNormal dd,
                   7383: .LC_ListStyleSpecial li,
1.795     www      7384: .LC_ListStyleSpecial dd {
1.911     bisitz   7385:   margin: 0;
                   7386:   padding: 5px 5px 5px 10px;
                   7387:   clear: both;
1.693     droeschl 7388: }
                   7389: 
1.721     harmsja  7390: .LC_ListStyleClean li,
                   7391: .LC_ListStyleClean dd {
1.911     bisitz   7392:   padding-top: 0;
                   7393:   padding-bottom: 0;
1.693     droeschl 7394: }
                   7395: 
1.721     harmsja  7396: .LC_ListStyleSimple dd,
1.795     www      7397: .LC_ListStyleSimple li {
1.911     bisitz   7398:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7399: }
                   7400: 
1.721     harmsja  7401: .LC_ListStyleSpecial li,
                   7402: .LC_ListStyleSpecial dd {
1.911     bisitz   7403:   list-style-type: none;
                   7404:   background-color: RGB(220, 220, 220);
                   7405:   margin-bottom: 4px;
1.693     droeschl 7406: }
                   7407: 
1.721     harmsja  7408: table.LC_SimpleTable {
1.911     bisitz   7409:   margin:5px;
                   7410:   border:solid 1px $lg_border_color;
1.795     www      7411: }
1.693     droeschl 7412: 
1.721     harmsja  7413: table.LC_SimpleTable tr {
1.911     bisitz   7414:   padding: 0;
                   7415:   border:solid 1px $lg_border_color;
1.693     droeschl 7416: }
1.795     www      7417: 
                   7418: table.LC_SimpleTable thead {
1.911     bisitz   7419:   background:rgb(220,220,220);
1.693     droeschl 7420: }
                   7421: 
1.721     harmsja  7422: div.LC_columnSection {
1.911     bisitz   7423:   display: block;
                   7424:   clear: both;
                   7425:   overflow: hidden;
                   7426:   margin: 0;
1.693     droeschl 7427: }
                   7428: 
1.721     harmsja  7429: div.LC_columnSection>* {
1.911     bisitz   7430:   float: left;
                   7431:   margin: 10px 20px 10px 0;
                   7432:   overflow:hidden;
1.693     droeschl 7433: }
1.721     harmsja  7434: 
1.795     www      7435: table em {
1.911     bisitz   7436:   font-weight: bold;
                   7437:   font-style: normal;
1.748     schulted 7438: }
1.795     www      7439: 
1.779     bisitz   7440: table.LC_tableBrowseRes,
1.795     www      7441: table.LC_tableOfContent {
1.911     bisitz   7442:   border:none;
                   7443:   border-spacing: 1px;
                   7444:   padding: 3px;
                   7445:   background-color: #FFFFFF;
                   7446:   font-size: 90%;
1.753     droeschl 7447: }
1.789     droeschl 7448: 
1.911     bisitz   7449: table.LC_tableOfContent {
                   7450:   border-collapse: collapse;
1.789     droeschl 7451: }
                   7452: 
1.771     droeschl 7453: table.LC_tableBrowseRes a,
1.768     schulted 7454: table.LC_tableOfContent a {
1.911     bisitz   7455:   background-color: transparent;
                   7456:   text-decoration: none;
1.753     droeschl 7457: }
                   7458: 
1.795     www      7459: table.LC_tableOfContent img {
1.911     bisitz   7460:   border: none;
                   7461:   height: 1.3em;
                   7462:   vertical-align: text-bottom;
                   7463:   margin-right: 0.3em;
1.753     droeschl 7464: }
1.757     schulted 7465: 
1.795     www      7466: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7467:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7468: }
                   7469: 
1.795     www      7470: a#LC_content_toolbar_everything {
1.911     bisitz   7471:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7472: }
                   7473: 
1.795     www      7474: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7475:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7476: }
                   7477: 
1.795     www      7478: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7479:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7480: }
                   7481: 
1.795     www      7482: a#LC_content_toolbar_changefolder {
1.911     bisitz   7483:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7484: }
                   7485: 
1.795     www      7486: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7487:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7488: }
                   7489: 
1.1043    raeburn  7490: a#LC_content_toolbar_edittoplevel {
                   7491:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7492: }
                   7493: 
1.795     www      7494: ul#LC_toolbar li a:hover {
1.911     bisitz   7495:   background-position: bottom center;
1.757     schulted 7496: }
                   7497: 
1.795     www      7498: ul#LC_toolbar {
1.911     bisitz   7499:   padding: 0;
                   7500:   margin: 2px;
                   7501:   list-style:none;
                   7502:   position:relative;
                   7503:   background-color:white;
1.1082    raeburn  7504:   overflow: auto;
1.757     schulted 7505: }
                   7506: 
1.795     www      7507: ul#LC_toolbar li {
1.911     bisitz   7508:   border:1px solid white;
                   7509:   padding: 0;
                   7510:   margin: 0;
                   7511:   float: left;
                   7512:   display:inline;
                   7513:   vertical-align:middle;
1.1082    raeburn  7514:   white-space: nowrap;
1.911     bisitz   7515: }
1.757     schulted 7516: 
1.783     amueller 7517: 
1.795     www      7518: a.LC_toolbarItem {
1.911     bisitz   7519:   display:block;
                   7520:   padding: 0;
                   7521:   margin: 0;
                   7522:   height: 32px;
                   7523:   width: 32px;
                   7524:   color:white;
                   7525:   border: none;
                   7526:   background-repeat:no-repeat;
                   7527:   background-color:transparent;
1.757     schulted 7528: }
                   7529: 
1.915     droeschl 7530: ul.LC_funclist {
                   7531:     margin: 0;
                   7532:     padding: 0.5em 1em 0.5em 0;
                   7533: }
                   7534: 
1.933     droeschl 7535: ul.LC_funclist > li:first-child {
                   7536:     font-weight:bold; 
                   7537:     margin-left:0.8em;
                   7538: }
                   7539: 
1.915     droeschl 7540: ul.LC_funclist + ul.LC_funclist {
                   7541:     /* 
                   7542:        left border as a seperator if we have more than
                   7543:        one list 
                   7544:     */
                   7545:     border-left: 1px solid $sidebg;
                   7546:     /* 
                   7547:        this hides the left border behind the border of the 
                   7548:        outer box if element is wrapped to the next 'line' 
                   7549:     */
                   7550:     margin-left: -1px;
                   7551: }
                   7552: 
1.843     bisitz   7553: ul.LC_funclist li {
1.915     droeschl 7554:   display: inline;
1.782     bisitz   7555:   white-space: nowrap;
1.915     droeschl 7556:   margin: 0 0 0 25px;
                   7557:   line-height: 150%;
1.782     bisitz   7558: }
                   7559: 
1.974     wenzelju 7560: .LC_hidden {
                   7561:   display: none;
                   7562: }
                   7563: 
1.1030    www      7564: .LCmodal-overlay {
                   7565: 		position:fixed;
                   7566: 		top:0;
                   7567: 		right:0;
                   7568: 		bottom:0;
                   7569: 		left:0;
                   7570: 		height:100%;
                   7571: 		width:100%;
                   7572: 		margin:0;
                   7573: 		padding:0;
                   7574: 		background:#999;
                   7575: 		opacity:.75;
                   7576: 		filter: alpha(opacity=75);
                   7577: 		-moz-opacity: 0.75;
                   7578: 		z-index:101;
                   7579: }
                   7580: 
                   7581: * html .LCmodal-overlay {   
                   7582: 		position: absolute;
                   7583: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7584: }
                   7585: 
                   7586: .LCmodal-window {
                   7587: 		position:fixed;
                   7588: 		top:50%;
                   7589: 		left:50%;
                   7590: 		margin:0;
                   7591: 		padding:0;
                   7592: 		z-index:102;
                   7593: 	}
                   7594: 
                   7595: * html .LCmodal-window {
                   7596: 		position:absolute;
                   7597: }
                   7598: 
                   7599: .LCclose-window {
                   7600: 		position:absolute;
                   7601: 		width:32px;
                   7602: 		height:32px;
                   7603: 		right:8px;
                   7604: 		top:8px;
                   7605: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7606: 		text-indent:-99999px;
                   7607: 		overflow:hidden;
                   7608: 		cursor:pointer;
                   7609: }
                   7610: 
1.1100    raeburn  7611: /*
                   7612:   styles used by TTH when "Default set of options to pass to tth/m
                   7613:   when converting TeX" in course settings has been set
                   7614: 
                   7615:   option passed: -t
                   7616: 
                   7617: */
                   7618: 
                   7619: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7620: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7621: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7622: td div.norm {line-height:normal;}
                   7623: 
                   7624: /*
                   7625:   option passed -y3
                   7626: */
                   7627: 
                   7628: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7629: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7630: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7631: 
1.343     albertel 7632: END
                   7633: }
                   7634: 
1.306     albertel 7635: =pod
                   7636: 
                   7637: =item * &headtag()
                   7638: 
                   7639: Returns a uniform footer for LON-CAPA web pages.
                   7640: 
1.307     albertel 7641: Inputs: $title - optional title for the head
                   7642:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7643:         $args - optional arguments
1.319     albertel 7644:             force_register - if is true call registerurl so the remote is 
                   7645:                              informed
1.415     albertel 7646:             redirect       -> array ref of
                   7647:                                    1- seconds before redirect occurs
                   7648:                                    2- url to redirect to
                   7649:                                    3- whether the side effect should occur
1.315     albertel 7650:                            (side effect of setting 
                   7651:                                $env{'internal.head.redirect'} to the url 
                   7652:                                redirected too)
1.352     albertel 7653:             domain         -> force to color decorate a page for a specific
                   7654:                                domain
                   7655:             function       -> force usage of a specific rolish color scheme
                   7656:             bgcolor        -> override the default page bgcolor
1.460     albertel 7657:             no_auto_mt_title
                   7658:                            -> prevent &mt()ing the title arg
1.464     albertel 7659: 
1.306     albertel 7660: =cut
                   7661: 
                   7662: sub headtag {
1.313     albertel 7663:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7664:     
1.363     albertel 7665:     my $function = $args->{'function'} || &get_users_function();
                   7666:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7667:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7668:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7669:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7670: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7671: 		   #time(),
1.418     albertel 7672: 		   $env{'environment.color.timestamp'},
1.363     albertel 7673: 		   $function,$domain,$bgcolor);
                   7674: 
1.369     www      7675:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7676: 
1.308     albertel 7677:     my $result =
                   7678: 	'<head>'.
1.1160    raeburn  7679: 	&font_settings($args);
1.319     albertel 7680: 
1.1188    raeburn  7681:     my $inhibitprint;
                   7682:     if ($args->{'print_suppress'}) {
                   7683:         $inhibitprint = &print_suppression();
                   7684:     }
1.1064    raeburn  7685: 
1.461     albertel 7686:     if (!$args->{'frameset'}) {
                   7687: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7688:     }
1.962     droeschl 7689:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7690:         $result .= Apache::lonxml::display_title();
1.319     albertel 7691:     }
1.436     albertel 7692:     if (!$args->{'no_nav_bar'} 
                   7693: 	&& !$args->{'only_body'}
                   7694: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7695: 	$result .= &help_menu_js($httphost);
1.1032    www      7696:         $result.=&modal_window();
1.1038    www      7697:         $result.=&togglebox_script();
1.1034    www      7698:         $result.=&wishlist_window();
1.1041    www      7699:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7700:     } else {
                   7701:         if ($args->{'add_modal'}) {
                   7702:            $result.=&modal_window();
                   7703:         }
                   7704:         if ($args->{'add_wishlist'}) {
                   7705:            $result.=&wishlist_window();
                   7706:         }
1.1038    www      7707:         if ($args->{'add_togglebox'}) {
                   7708:            $result.=&togglebox_script();
                   7709:         }
1.1041    www      7710:         if ($args->{'add_progressbar'}) {
                   7711:            $result.=&LCprogressbarUpdate_script();
                   7712:         }
1.436     albertel 7713:     }
1.314     albertel 7714:     if (ref($args->{'redirect'})) {
1.414     albertel 7715: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7716: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7717: 	if (!$inhibit_continue) {
                   7718: 	    $env{'internal.head.redirect'} = $url;
                   7719: 	}
1.313     albertel 7720: 	$result.=<<ADDMETA
                   7721: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7722: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7723: ADDMETA
1.1210    raeburn  7724:     } else {
                   7725:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7726:             my $requrl = $env{'request.uri'};
                   7727:             if ($requrl eq '') {
                   7728:                 $requrl = $ENV{'REQUEST_URI'};
                   7729:                 $requrl =~ s/\?.+$//;
                   7730:             }
                   7731:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7732:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7733:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7734:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7735:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7736:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7737:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7738:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7739:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7740:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7741:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7742:                                 my $numsec = 5;
                   7743:                                 my $timeout = $numsec * 1000;
                   7744:                                 my ($newurl,$locknum,%locks,$msg);
                   7745:                                 if ($env{'request.role.adv'}) {
                   7746:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7747:                                 }
                   7748:                                 my $disable_submit = 0;
                   7749:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7750:                                     $disable_submit = 1;
                   7751:                                 }
                   7752:                                 if ($locknum) {
                   7753:                                     my @lockinfo = sort(values(%locks));
                   7754:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7755:                                            join(", ",sort(values(%locks)))."\\n".
                   7756:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7757:                                 } else {
                   7758:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7759:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7760:                                     }
                   7761:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7762:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7763:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7764:                                         $newurl .= '&role='.$env{'request.role'};
                   7765:                                     }
                   7766:                                     if ($env{'request.symb'}) {
                   7767:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7768:                                     } else {
                   7769:                                         $newurl .= '&origurl='.$requrl;
                   7770:                                     }
                   7771:                                 }
                   7772:                                 $result.=<<OFFLOAD
                   7773: <meta http-equiv="pragma" content="no-cache" />
                   7774: <script type="text/javascript">
                   7775: function LC_Offload_Now() {
                   7776:     var dest = "$newurl";
                   7777:     if (dest != '') {
                   7778:         window.location.href="$newurl";
                   7779:     }
                   7780: }
                   7781: window.alert('$msg');
                   7782: if ($disable_submit) {
                   7783:     \$(document).ready(function () {
                   7784:         \$(".LC_hwk_submit").prop("disabled", true);
                   7785:         \$( ".LC_textline" ).prop( "readonly", "readonly");
                   7786:     });
                   7787: }
                   7788: setTimeout('LC_Offload_Now()', $timeout);
                   7789: </script>
                   7790: OFFLOAD
                   7791:                             }
                   7792:                         }
                   7793:                     }
                   7794:                 }
                   7795:             }
                   7796:         }
1.313     albertel 7797:     }
1.306     albertel 7798:     if (!defined($title)) {
                   7799: 	$title = 'The LearningOnline Network with CAPA';
                   7800:     }
1.460     albertel 7801:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7802:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7803: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7804:     if (!$args->{'frameset'}) {
                   7805:         $result .= ' /';
                   7806:     }
                   7807:     $result .= '>' 
1.1064    raeburn  7808:         .$inhibitprint
1.414     albertel 7809: 	.$head_extra;
1.1137    raeburn  7810:     if ($env{'browser.mobile'}) {
                   7811:         $result .= '
                   7812: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7813: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7814:     }
1.962     droeschl 7815:     return $result.'</head>';
1.306     albertel 7816: }
                   7817: 
                   7818: =pod
                   7819: 
1.340     albertel 7820: =item * &font_settings()
                   7821: 
                   7822: Returns neccessary <meta> to set the proper encoding
                   7823: 
1.1160    raeburn  7824: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7825: 
                   7826: =cut
                   7827: 
                   7828: sub font_settings {
1.1160    raeburn  7829:     my ($args) = @_;
1.340     albertel 7830:     my $headerstring='';
1.1160    raeburn  7831:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7832:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7833:         $headerstring.=
                   7834:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7835:         if (!$args->{'frameset'}) {
                   7836: 	    $headerstring.= ' /';
                   7837:         }
                   7838: 	$headerstring .= '>'."\n";
1.340     albertel 7839:     }
                   7840:     return $headerstring;
                   7841: }
                   7842: 
1.341     albertel 7843: =pod
                   7844: 
1.1064    raeburn  7845: =item * &print_suppression()
                   7846: 
                   7847: In course context returns css which causes the body to be blank when media="print",
                   7848: if printout generation is unavailable for the current resource.
                   7849: 
                   7850: This could be because:
                   7851: 
                   7852: (a) printstartdate is in the future
                   7853: 
                   7854: (b) printenddate is in the past
                   7855: 
                   7856: (c) there is an active exam block with "printout"
                   7857: functionality blocked
                   7858: 
                   7859: Users with pav, pfo or evb privileges are exempt.
                   7860: 
                   7861: Inputs: none
                   7862: 
                   7863: =cut
                   7864: 
                   7865: 
                   7866: sub print_suppression {
                   7867:     my $noprint;
                   7868:     if ($env{'request.course.id'}) {
                   7869:         my $scope = $env{'request.course.id'};
                   7870:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7871:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7872:             return;
                   7873:         }
                   7874:         if ($env{'request.course.sec'} ne '') {
                   7875:             $scope .= "/$env{'request.course.sec'}";
                   7876:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7877:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7878:                 return;
1.1064    raeburn  7879:             }
                   7880:         }
                   7881:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7882:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  7883:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7884:         if ($blocked) {
                   7885:             my $checkrole = "cm./$cdom/$cnum";
                   7886:             if ($env{'request.course.sec'} ne '') {
                   7887:                 $checkrole .= "/$env{'request.course.sec'}";
                   7888:             }
                   7889:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7890:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7891:                 $noprint = 1;
                   7892:             }
                   7893:         }
                   7894:         unless ($noprint) {
                   7895:             my $symb = &Apache::lonnet::symbread();
                   7896:             if ($symb ne '') {
                   7897:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7898:                 if (ref($navmap)) {
                   7899:                     my $res = $navmap->getBySymb($symb);
                   7900:                     if (ref($res)) {
                   7901:                         if (!$res->resprintable()) {
                   7902:                             $noprint = 1;
                   7903:                         }
                   7904:                     }
                   7905:                 }
                   7906:             }
                   7907:         }
                   7908:         if ($noprint) {
                   7909:             return <<"ENDSTYLE";
                   7910: <style type="text/css" media="print">
                   7911:     body { display:none }
                   7912: </style>
                   7913: ENDSTYLE
                   7914:         }
                   7915:     }
                   7916:     return;
                   7917: }
                   7918: 
                   7919: =pod
                   7920: 
1.341     albertel 7921: =item * &xml_begin()
                   7922: 
                   7923: Returns the needed doctype and <html>
                   7924: 
                   7925: Inputs: none
                   7926: 
                   7927: =cut
                   7928: 
                   7929: sub xml_begin {
1.1168    raeburn  7930:     my ($is_frameset) = @_;
1.341     albertel 7931:     my $output='';
                   7932: 
                   7933:     if ($env{'browser.mathml'}) {
                   7934: 	$output='<?xml version="1.0"?>'
                   7935:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7936: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7937:             
                   7938: #	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" [<!ENTITY mathns "http://www.w3.org/1998/Math/MathML">] >'
                   7939: 	    .'<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1 plus MathML 2.0 plus SVG 1.1//EN" "http://www.w3.org/2002/04/xhtml-math-svg/xhtml-math-svg.dtd">'
                   7940:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7941: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  7942:     } elsif ($is_frameset) {
                   7943:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7944:                 '<html>'."\n";
1.341     albertel 7945:     } else {
1.1168    raeburn  7946: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7947:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7948:     }
                   7949:     return $output;
                   7950: }
1.340     albertel 7951: 
                   7952: =pod
                   7953: 
1.306     albertel 7954: =item * &start_page()
                   7955: 
                   7956: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7957: 
1.648     raeburn  7958: Inputs:
                   7959: 
                   7960: =over 4
                   7961: 
                   7962: $title - optional title for the page
                   7963: 
                   7964: $head_extra - optional extra HTML to incude inside the <head>
                   7965: 
                   7966: $args - additional optional args supported are:
                   7967: 
                   7968: =over 8
                   7969: 
                   7970:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7971:                                     arg on
1.814     bisitz   7972:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7973:              add_entries    -> additional attributes to add to the  <body>
                   7974:              domain         -> force to color decorate a page for a 
1.317     albertel 7975:                                     specific domain
1.648     raeburn  7976:              function       -> force usage of a specific rolish color
1.317     albertel 7977:                                     scheme
1.648     raeburn  7978:              redirect       -> see &headtag()
                   7979:              bgcolor        -> override the default page bg color
                   7980:              js_ready       -> return a string ready for being used in 
1.317     albertel 7981:                                     a javascript writeln
1.648     raeburn  7982:              html_encode    -> return a string ready for being used in 
1.320     albertel 7983:                                     a html attribute
1.648     raeburn  7984:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7985:                                     $forcereg arg
1.648     raeburn  7986:              frameset       -> if true will start with a <frameset>
1.330     albertel 7987:                                     rather than <body>
1.648     raeburn  7988:              skip_phases    -> hash ref of 
1.338     albertel 7989:                                     head -> skip the <html><head> generation
                   7990:                                     body -> skip all <body> generation
1.648     raeburn  7991:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7992:              inherit_jsmath -> when creating popup window in a page,
                   7993:                                     should it have jsmath forced on by the
                   7994:                                     current page
1.867     kalberla 7995:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7996:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7997:              group          -> includes the current group, if page is for a 
                   7998:                                specific group  
1.361     albertel 7999: 
1.648     raeburn  8000: =back
1.460     albertel 8001: 
1.648     raeburn  8002: =back
1.562     albertel 8003: 
1.306     albertel 8004: =cut
                   8005: 
                   8006: sub start_page {
1.309     albertel 8007:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8008:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8009: 
1.315     albertel 8010:     $env{'internal.start_page'}++;
1.1096    raeburn  8011:     my ($result,@advtools);
1.964     droeschl 8012: 
1.338     albertel 8013:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8014:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8015:     }
                   8016:     
                   8017:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8018: 	if ($args->{'frameset'}) {
                   8019: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8020: 						$args->{'add_entries'});
                   8021: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8022:         } else {
                   8023:             $result .=
                   8024:                 &bodytag($title, 
                   8025:                          $args->{'function'},       $args->{'add_entries'},
                   8026:                          $args->{'only_body'},      $args->{'domain'},
                   8027:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8028:                          $args->{'bgcolor'},        $args,
                   8029:                          \@advtools);
1.831     bisitz   8030:         }
1.330     albertel 8031:     }
1.338     albertel 8032: 
1.315     albertel 8033:     if ($args->{'js_ready'}) {
1.713     kaisler  8034: 		$result = &js_ready($result);
1.315     albertel 8035:     }
1.320     albertel 8036:     if ($args->{'html_encode'}) {
1.713     kaisler  8037: 		$result = &html_encode($result);
                   8038:     }
                   8039: 
1.813     bisitz   8040:     # Preparation for new and consistent functionlist at top of screen
                   8041:     # if ($args->{'functionlist'}) {
                   8042:     #            $result .= &build_functionlist();
                   8043:     #}
                   8044: 
1.964     droeschl 8045:     # Don't add anything more if only_body wanted or in const space
                   8046:     return $result if    $args->{'only_body'} 
                   8047:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8048: 
                   8049:     #Breadcrumbs
1.758     kaisler  8050:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8051: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8052: 		#if any br links exists, add them to the breadcrumbs
                   8053: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8054: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8055: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8056: 			}
                   8057: 		}
1.1096    raeburn  8058:                 # if @advtools array contains items add then to the breadcrumbs
                   8059:                 if (@advtools > 0) {
                   8060:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8061:                 }
1.758     kaisler  8062: 
                   8063: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8064: 		if(exists($args->{'bread_crumbs_component'})){
                   8065: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8066: 		}else{
                   8067: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8068: 		}
1.320     albertel 8069:     }
1.315     albertel 8070:     return $result;
1.306     albertel 8071: }
                   8072: 
                   8073: sub end_page {
1.315     albertel 8074:     my ($args) = @_;
                   8075:     $env{'internal.end_page'}++;
1.330     albertel 8076:     my $result;
1.335     albertel 8077:     if ($args->{'discussion'}) {
                   8078: 	my ($target,$parser);
                   8079: 	if (ref($args->{'discussion'})) {
                   8080: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8081: 				$args->{'discussion'}{'parser'});
                   8082: 	}
                   8083: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8084:     }
1.330     albertel 8085:     if ($args->{'frameset'}) {
                   8086: 	$result .= '</frameset>';
                   8087:     } else {
1.635     raeburn  8088: 	$result .= &endbodytag($args);
1.330     albertel 8089:     }
1.1080    raeburn  8090:     unless ($args->{'notbody'}) {
                   8091:         $result .= "\n</html>";
                   8092:     }
1.330     albertel 8093: 
1.315     albertel 8094:     if ($args->{'js_ready'}) {
1.317     albertel 8095: 	$result = &js_ready($result);
1.315     albertel 8096:     }
1.335     albertel 8097: 
1.320     albertel 8098:     if ($args->{'html_encode'}) {
                   8099: 	$result = &html_encode($result);
                   8100:     }
1.335     albertel 8101: 
1.315     albertel 8102:     return $result;
                   8103: }
                   8104: 
1.1034    www      8105: sub wishlist_window {
                   8106:     return(<<'ENDWISHLIST');
1.1046    raeburn  8107: <script type="text/javascript">
1.1034    www      8108: // <![CDATA[
                   8109: // <!-- BEGIN LON-CAPA Internal
                   8110: function set_wishlistlink(title, path) {
                   8111:     if (!title) {
                   8112:         title = document.title;
                   8113:         title = title.replace(/^LON-CAPA /,'');
                   8114:     }
1.1175    raeburn  8115:     title = encodeURIComponent(title);
1.1203    raeburn  8116:     title = title.replace("'","\\\'");
1.1034    www      8117:     if (!path) {
                   8118:         path = location.pathname;
                   8119:     }
1.1175    raeburn  8120:     path = encodeURIComponent(path);
1.1203    raeburn  8121:     path = path.replace("'","\\\'");
1.1034    www      8122:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8123:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8124: }
                   8125: // END LON-CAPA Internal -->
                   8126: // ]]>
                   8127: </script>
                   8128: ENDWISHLIST
                   8129: }
                   8130: 
1.1030    www      8131: sub modal_window {
                   8132:     return(<<'ENDMODAL');
1.1046    raeburn  8133: <script type="text/javascript">
1.1030    www      8134: // <![CDATA[
                   8135: // <!-- BEGIN LON-CAPA Internal
                   8136: var modalWindow = {
                   8137: 	parent:"body",
                   8138: 	windowId:null,
                   8139: 	content:null,
                   8140: 	width:null,
                   8141: 	height:null,
                   8142: 	close:function()
                   8143: 	{
                   8144: 	        $(".LCmodal-window").remove();
                   8145: 	        $(".LCmodal-overlay").remove();
                   8146: 	},
                   8147: 	open:function()
                   8148: 	{
                   8149: 		var modal = "";
                   8150: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8151: 		modal += "<div id=\"" + this.windowId + "\" class=\"LCmodal-window\" style=\"width:" + this.width + "px; height:" + this.height + "px; margin-top:-" + (this.height / 2) + "px; margin-left:-" + (this.width / 2) + "px;\">";
                   8152: 		modal += this.content;
                   8153: 		modal += "</div>";	
                   8154: 
                   8155: 		$(this.parent).append(modal);
                   8156: 
                   8157: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8158: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8159: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8160: 	}
                   8161: };
1.1140    raeburn  8162: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8163: 	{
1.1203    raeburn  8164:                 source = source.replace("'","&#39;");
1.1030    www      8165: 		modalWindow.windowId = "myModal";
                   8166: 		modalWindow.width = width;
                   8167: 		modalWindow.height = height;
1.1196    raeburn  8168: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8169: 		modalWindow.open();
1.1208    raeburn  8170: 	};
1.1030    www      8171: // END LON-CAPA Internal -->
                   8172: // ]]>
                   8173: </script>
                   8174: ENDMODAL
                   8175: }
                   8176: 
                   8177: sub modal_link {
1.1140    raeburn  8178:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8179:     unless ($width) { $width=480; }
                   8180:     unless ($height) { $height=400; }
1.1031    www      8181:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8182:     unless ($transparency) { $transparency='true'; }
                   8183: 
1.1074    raeburn  8184:     my $target_attr;
                   8185:     if (defined($target)) {
                   8186:         $target_attr = 'target="'.$target.'"';
                   8187:     }
                   8188:     return <<"ENDLINK";
1.1140    raeburn  8189: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8190:            $linktext</a>
                   8191: ENDLINK
1.1030    www      8192: }
                   8193: 
1.1032    www      8194: sub modal_adhoc_script {
                   8195:     my ($funcname,$width,$height,$content)=@_;
                   8196:     return (<<ENDADHOC);
1.1046    raeburn  8197: <script type="text/javascript">
1.1032    www      8198: // <![CDATA[
                   8199:         var $funcname = function()
                   8200:         {
                   8201:                 modalWindow.windowId = "myModal";
                   8202:                 modalWindow.width = $width;
                   8203:                 modalWindow.height = $height;
                   8204:                 modalWindow.content = '$content';
                   8205:                 modalWindow.open();
                   8206:         };  
                   8207: // ]]>
                   8208: </script>
                   8209: ENDADHOC
                   8210: }
                   8211: 
1.1041    www      8212: sub modal_adhoc_inner {
                   8213:     my ($funcname,$width,$height,$content)=@_;
                   8214:     my $innerwidth=$width-20;
                   8215:     $content=&js_ready(
1.1140    raeburn  8216:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8217:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8218:                  $content.
1.1041    www      8219:                  &end_scrollbox().
1.1140    raeburn  8220:                  &end_page()
1.1041    www      8221:              );
                   8222:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8223: }
                   8224: 
                   8225: sub modal_adhoc_window {
                   8226:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8227:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8228:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8229: }
                   8230: 
                   8231: sub modal_adhoc_launch {
                   8232:     my ($funcname,$width,$height,$content)=@_;
                   8233:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8234: <script type="text/javascript">
                   8235: // <![CDATA[
                   8236: $funcname();
                   8237: // ]]>
                   8238: </script>
                   8239: ENDLAUNCH
                   8240: }
                   8241: 
                   8242: sub modal_adhoc_close {
                   8243:     return (<<ENDCLOSE);
                   8244: <script type="text/javascript">
                   8245: // <![CDATA[
                   8246: modalWindow.close();
                   8247: // ]]>
                   8248: </script>
                   8249: ENDCLOSE
                   8250: }
                   8251: 
1.1038    www      8252: sub togglebox_script {
                   8253:    return(<<ENDTOGGLE);
                   8254: <script type="text/javascript"> 
                   8255: // <![CDATA[
                   8256: function LCtoggleDisplay(id,hidetext,showtext) {
                   8257:    link = document.getElementById(id + "link").childNodes[0];
                   8258:    with (document.getElementById(id).style) {
                   8259:       if (display == "none" ) {
                   8260:           display = "inline";
                   8261:           link.nodeValue = hidetext;
                   8262:         } else {
                   8263:           display = "none";
                   8264:           link.nodeValue = showtext;
                   8265:        }
                   8266:    }
                   8267: }
                   8268: // ]]>
                   8269: </script>
                   8270: ENDTOGGLE
                   8271: }
                   8272: 
1.1039    www      8273: sub start_togglebox {
                   8274:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8275:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8276:     unless ($showtext) { $showtext=&mt('show'); }
                   8277:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8278:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8279:     return &start_data_table().
                   8280:            &start_data_table_header_row().
                   8281:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8282:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8283:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8284:            &end_data_table_header_row().
                   8285:            '<tr id="'.$id.'" style="display:none""><td>';
                   8286: }
                   8287: 
                   8288: sub end_togglebox {
                   8289:     return '</td></tr>'.&end_data_table();
                   8290: }
                   8291: 
1.1041    www      8292: sub LCprogressbar_script {
1.1045    www      8293:    my ($id)=@_;
1.1041    www      8294:    return(<<ENDPROGRESS);
                   8295: <script type="text/javascript">
                   8296: // <![CDATA[
1.1045    www      8297: \$('#progressbar$id').progressbar({
1.1041    www      8298:   value: 0,
                   8299:   change: function(event, ui) {
                   8300:     var newVal = \$(this).progressbar('option', 'value');
                   8301:     \$('.pblabel', this).text(LCprogressTxt);
                   8302:   }
                   8303: });
                   8304: // ]]>
                   8305: </script>
                   8306: ENDPROGRESS
                   8307: }
                   8308: 
                   8309: sub LCprogressbarUpdate_script {
                   8310:    return(<<ENDPROGRESSUPDATE);
                   8311: <style type="text/css">
                   8312: .ui-progressbar { position:relative; }
                   8313: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8314: </style>
                   8315: <script type="text/javascript">
                   8316: // <![CDATA[
1.1045    www      8317: var LCprogressTxt='---';
                   8318: 
                   8319: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8320:    LCprogressTxt=progresstext;
1.1045    www      8321:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8322: }
                   8323: // ]]>
                   8324: </script>
                   8325: ENDPROGRESSUPDATE
                   8326: }
                   8327: 
1.1042    www      8328: my $LClastpercent;
1.1045    www      8329: my $LCidcnt;
                   8330: my $LCcurrentid;
1.1042    www      8331: 
1.1041    www      8332: sub LCprogressbar {
1.1042    www      8333:     my ($r)=(@_);
                   8334:     $LClastpercent=0;
1.1045    www      8335:     $LCidcnt++;
                   8336:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8337:     my $starting=&mt('Starting');
                   8338:     my $content=(<<ENDPROGBAR);
1.1045    www      8339:   <div id="progressbar$LCcurrentid">
1.1041    www      8340:     <span class="pblabel">$starting</span>
                   8341:   </div>
                   8342: ENDPROGBAR
1.1045    www      8343:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8344: }
                   8345: 
                   8346: sub LCprogressbarUpdate {
1.1042    www      8347:     my ($r,$val,$text)=@_;
                   8348:     unless ($val) { 
                   8349:        if ($LClastpercent) {
                   8350:            $val=$LClastpercent;
                   8351:        } else {
                   8352:            $val=0;
                   8353:        }
                   8354:     }
1.1041    www      8355:     if ($val<0) { $val=0; }
                   8356:     if ($val>100) { $val=0; }
1.1042    www      8357:     $LClastpercent=$val;
1.1041    www      8358:     unless ($text) { $text=$val.'%'; }
                   8359:     $text=&js_ready($text);
1.1044    www      8360:     &r_print($r,<<ENDUPDATE);
1.1041    www      8361: <script type="text/javascript">
                   8362: // <![CDATA[
1.1045    www      8363: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8364: // ]]>
                   8365: </script>
                   8366: ENDUPDATE
1.1035    www      8367: }
                   8368: 
1.1042    www      8369: sub LCprogressbarClose {
                   8370:     my ($r)=@_;
                   8371:     $LClastpercent=0;
1.1044    www      8372:     &r_print($r,<<ENDCLOSE);
1.1042    www      8373: <script type="text/javascript">
                   8374: // <![CDATA[
1.1045    www      8375: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8376: // ]]>
                   8377: </script>
                   8378: ENDCLOSE
1.1044    www      8379: }
                   8380: 
                   8381: sub r_print {
                   8382:     my ($r,$to_print)=@_;
                   8383:     if ($r) {
                   8384:       $r->print($to_print);
                   8385:       $r->rflush();
                   8386:     } else {
                   8387:       print($to_print);
                   8388:     }
1.1042    www      8389: }
                   8390: 
1.320     albertel 8391: sub html_encode {
                   8392:     my ($result) = @_;
                   8393: 
1.322     albertel 8394:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8395:     
                   8396:     return $result;
                   8397: }
1.1044    www      8398: 
1.317     albertel 8399: sub js_ready {
                   8400:     my ($result) = @_;
                   8401: 
1.323     albertel 8402:     $result =~ s/[\n\r]/ /xmsg;
                   8403:     $result =~ s/\\/\\\\/xmsg;
                   8404:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8405:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8406:     
                   8407:     return $result;
                   8408: }
                   8409: 
1.315     albertel 8410: sub validate_page {
                   8411:     if (  exists($env{'internal.start_page'})
1.316     albertel 8412: 	  &&     $env{'internal.start_page'} > 1) {
                   8413: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8414: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8415: 				 $ENV{'request.filename'});
1.315     albertel 8416:     }
                   8417:     if (  exists($env{'internal.end_page'})
1.316     albertel 8418: 	  &&     $env{'internal.end_page'} > 1) {
                   8419: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8420: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8421: 				 $env{'request.filename'});
1.315     albertel 8422:     }
                   8423:     if (     exists($env{'internal.start_page'})
                   8424: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8425: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8426: 				 $env{'request.filename'});
1.315     albertel 8427:     }
                   8428:     if (   ! exists($env{'internal.start_page'})
                   8429: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8430: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8431: 				 $env{'request.filename'});
1.315     albertel 8432:     }
1.306     albertel 8433: }
1.315     albertel 8434: 
1.996     www      8435: 
                   8436: sub start_scrollbox {
1.1140    raeburn  8437:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8438:     unless ($outerwidth) { $outerwidth='520px'; }
                   8439:     unless ($width) { $width='500px'; }
                   8440:     unless ($height) { $height='200px'; }
1.1075    raeburn  8441:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8442:     if ($id ne '') {
1.1140    raeburn  8443:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8444:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8445:     }
1.1075    raeburn  8446:     if ($bgcolor ne '') {
                   8447:         $tdcol = "background-color: $bgcolor;";
                   8448:     }
1.1137    raeburn  8449:     my $nicescroll_js;
                   8450:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8451:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8452:     }
                   8453:     return <<"END";
                   8454: $nicescroll_js
                   8455: 
                   8456: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8457: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8458: END
                   8459: }
                   8460: 
                   8461: sub end_scrollbox {
                   8462:     return '</div></td></tr></table>';
                   8463: }
                   8464: 
                   8465: sub nicescroll_javascript {
                   8466:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8467:     my %options;
                   8468:     if (ref($cursor) eq 'HASH') {
                   8469:         %options = %{$cursor};
                   8470:     }
                   8471:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8472:         $options{'railalign'} = 'left';
                   8473:     }
                   8474:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8475:         my $function  = &get_users_function();
                   8476:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8477:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8478:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8479:         }
1.1140    raeburn  8480:     }
                   8481:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8482:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8483:             $options{'cursoropacity'}='1.0';
                   8484:         }
1.1140    raeburn  8485:     } else {
                   8486:         $options{'cursoropacity'}='1.0';
                   8487:     }
                   8488:     if ($options{'cursorfixedheight'} eq 'none') {
                   8489:         delete($options{'cursorfixedheight'});
                   8490:     } else {
                   8491:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8492:     }
                   8493:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8494:         delete($options{'railoffset'});
                   8495:     }
                   8496:     my @niceoptions;
                   8497:     while (my($key,$value) = each(%options)) {
                   8498:         if ($value =~ /^\{.+\}$/) {
                   8499:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8500:         } else {
1.1140    raeburn  8501:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8502:         }
1.1140    raeburn  8503:     }
                   8504:     my $nicescroll_js = '
1.1137    raeburn  8505: $(document).ready(
1.1140    raeburn  8506:       function() {
                   8507:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8508:       }
1.1137    raeburn  8509: );
                   8510: ';
1.1140    raeburn  8511:     if ($framecheck) {
                   8512:         $nicescroll_js .= '
                   8513: function expand_div(caller) {
                   8514:     if (top === self) {
                   8515:         document.getElementById("'.$id.'").style.width = "auto";
                   8516:         document.getElementById("'.$id.'").style.height = "auto";
                   8517:     } else {
                   8518:         try {
                   8519:             if (parent.frames) {
                   8520:                 if (parent.frames.length > 1) {
                   8521:                     var framesrc = parent.frames[1].location.href;
                   8522:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8523:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8524:                         document.getElementById("'.$id.'").style.width = "auto";
                   8525:                         document.getElementById("'.$id.'").style.height = "auto";
                   8526:                     }
                   8527:                 }
                   8528:             }
                   8529:         } catch (e) {
                   8530:             return;
                   8531:         }
1.1137    raeburn  8532:     }
1.1140    raeburn  8533:     return;
1.996     www      8534: }
1.1140    raeburn  8535: ';
                   8536:     }
                   8537:     if ($needjsready) {
                   8538:         $nicescroll_js = '
                   8539: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8540:     } else {
                   8541:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8542:     }
                   8543:     return $nicescroll_js;
1.996     www      8544: }
                   8545: 
1.318     albertel 8546: sub simple_error_page {
1.1150    bisitz   8547:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8548:     if (ref($args) eq 'HASH') {
                   8549:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8550:     } else {
                   8551:         $msg = &mt($msg);
                   8552:     }
1.1150    bisitz   8553: 
1.318     albertel 8554:     my $page =
                   8555: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8556: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8557: 	&Apache::loncommon::end_page();
                   8558:     if (ref($r)) {
                   8559: 	$r->print($page);
1.327     albertel 8560: 	return;
1.318     albertel 8561:     }
                   8562:     return $page;
                   8563: }
1.347     albertel 8564: 
                   8565: {
1.610     albertel 8566:     my @row_count;
1.961     onken    8567: 
                   8568:     sub start_data_table_count {
                   8569:         unshift(@row_count, 0);
                   8570:         return;
                   8571:     }
                   8572: 
                   8573:     sub end_data_table_count {
                   8574:         shift(@row_count);
                   8575:         return;
                   8576:     }
                   8577: 
1.347     albertel 8578:     sub start_data_table {
1.1018    raeburn  8579: 	my ($add_class,$id) = @_;
1.422     albertel 8580: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8581:         my $table_id;
                   8582:         if (defined($id)) {
                   8583:             $table_id = ' id="'.$id.'"';
                   8584:         }
1.961     onken    8585: 	&start_data_table_count();
1.1018    raeburn  8586: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8587:     }
                   8588: 
                   8589:     sub end_data_table {
1.961     onken    8590: 	&end_data_table_count();
1.389     albertel 8591: 	return '</table>'."\n";;
1.347     albertel 8592:     }
                   8593: 
                   8594:     sub start_data_table_row {
1.974     wenzelju 8595: 	my ($add_class, $id) = @_;
1.610     albertel 8596: 	$row_count[0]++;
                   8597: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8598: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8599:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8600:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8601:     }
1.471     banghart 8602:     
                   8603:     sub continue_data_table_row {
1.974     wenzelju 8604: 	my ($add_class, $id) = @_;
1.610     albertel 8605: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8606: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8607:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8608:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8609:     }
1.347     albertel 8610: 
                   8611:     sub end_data_table_row {
1.389     albertel 8612: 	return '</tr>'."\n";;
1.347     albertel 8613:     }
1.367     www      8614: 
1.421     albertel 8615:     sub start_data_table_empty_row {
1.707     bisitz   8616: #	$row_count[0]++;
1.421     albertel 8617: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8618:     }
                   8619: 
                   8620:     sub end_data_table_empty_row {
                   8621: 	return '</tr>'."\n";;
                   8622:     }
                   8623: 
1.367     www      8624:     sub start_data_table_header_row {
1.389     albertel 8625: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8626:     }
                   8627: 
                   8628:     sub end_data_table_header_row {
1.389     albertel 8629: 	return '</tr>'."\n";;
1.367     www      8630:     }
1.890     droeschl 8631: 
                   8632:     sub data_table_caption {
                   8633:         my $caption = shift;
                   8634:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8635:     }
1.347     albertel 8636: }
                   8637: 
1.548     albertel 8638: =pod
                   8639: 
                   8640: =item * &inhibit_menu_check($arg)
                   8641: 
                   8642: Checks for a inhibitmenu state and generates output to preserve it
                   8643: 
                   8644: Inputs:         $arg - can be any of
                   8645:                      - undef - in which case the return value is a string 
                   8646:                                to add  into arguments list of a uri
                   8647:                      - 'input' - in which case the return value is a HTML
                   8648:                                  <form> <input> field of type hidden to
                   8649:                                  preserve the value
                   8650:                      - a url - in which case the return value is the url with
                   8651:                                the neccesary cgi args added to preserve the
                   8652:                                inhibitmenu state
                   8653:                      - a ref to a url - no return value, but the string is
                   8654:                                         updated to include the neccessary cgi
                   8655:                                         args to preserve the inhibitmenu state
                   8656: 
                   8657: =cut
                   8658: 
                   8659: sub inhibit_menu_check {
                   8660:     my ($arg) = @_;
                   8661:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8662:     if ($arg eq 'input') {
                   8663: 	if ($env{'form.inhibitmenu'}) {
                   8664: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8665: 	} else {
                   8666: 	    return
                   8667: 	}
                   8668:     }
                   8669:     if ($env{'form.inhibitmenu'}) {
                   8670: 	if (ref($arg)) {
                   8671: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8672: 	} elsif ($arg eq '') {
                   8673: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8674: 	} else {
                   8675: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8676: 	}
                   8677:     }
                   8678:     if (!ref($arg)) {
                   8679: 	return $arg;
                   8680:     }
                   8681: }
                   8682: 
1.251     albertel 8683: ###############################################
1.182     matthew  8684: 
                   8685: =pod
                   8686: 
1.549     albertel 8687: =back
                   8688: 
                   8689: =head1 User Information Routines
                   8690: 
                   8691: =over 4
                   8692: 
1.405     albertel 8693: =item * &get_users_function()
1.182     matthew  8694: 
                   8695: Used by &bodytag to determine the current users primary role.
                   8696: Returns either 'student','coordinator','admin', or 'author'.
                   8697: 
                   8698: =cut
                   8699: 
                   8700: ###############################################
                   8701: sub get_users_function {
1.815     tempelho 8702:     my $function = 'norole';
1.818     tempelho 8703:     if ($env{'request.role'}=~/^(st)/) {
                   8704:         $function='student';
                   8705:     }
1.907     raeburn  8706:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8707:         $function='coordinator';
                   8708:     }
1.258     albertel 8709:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8710:         $function='admin';
                   8711:     }
1.826     bisitz   8712:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8713:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8714:         $function='author';
                   8715:     }
                   8716:     return $function;
1.54      www      8717: }
1.99      www      8718: 
                   8719: ###############################################
                   8720: 
1.233     raeburn  8721: =pod
                   8722: 
1.821     raeburn  8723: =item * &show_course()
                   8724: 
                   8725: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8726: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8727: 
                   8728: Inputs:
                   8729: None
                   8730: 
                   8731: Outputs:
                   8732: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8733: 
                   8734: =cut
                   8735: 
                   8736: ###############################################
                   8737: sub show_course {
                   8738:     my $course = !$env{'user.adv'};
                   8739:     if (!$env{'user.adv'}) {
                   8740:         foreach my $env (keys(%env)) {
                   8741:             next if ($env !~ m/^user\.priv\./);
                   8742:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8743:                 $course = 0;
                   8744:                 last;
                   8745:             }
                   8746:         }
                   8747:     }
                   8748:     return $course;
                   8749: }
                   8750: 
                   8751: ###############################################
                   8752: 
                   8753: =pod
                   8754: 
1.542     raeburn  8755: =item * &check_user_status()
1.274     raeburn  8756: 
                   8757: Determines current status of supplied role for a
                   8758: specific user. Roles can be active, previous or future.
                   8759: 
                   8760: Inputs: 
                   8761: user's domain, user's username, course's domain,
1.375     raeburn  8762: course's number, optional section ID.
1.274     raeburn  8763: 
                   8764: Outputs:
                   8765: role status: active, previous or future. 
                   8766: 
                   8767: =cut
                   8768: 
                   8769: sub check_user_status {
1.412     raeburn  8770:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8771:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8772:     my @uroles = keys(%userinfo);
1.274     raeburn  8773:     my $srchstr;
                   8774:     my $active_chk = 'none';
1.412     raeburn  8775:     my $now = time;
1.274     raeburn  8776:     if (@uroles > 0) {
1.908     raeburn  8777:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8778:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8779:         } else {
1.412     raeburn  8780:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8781:         }
                   8782:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8783:             my $role_end = 0;
                   8784:             my $role_start = 0;
                   8785:             $active_chk = 'active';
1.412     raeburn  8786:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8787:                 $role_end = $1;
                   8788:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8789:                     $role_start = $1;
1.274     raeburn  8790:                 }
                   8791:             }
                   8792:             if ($role_start > 0) {
1.412     raeburn  8793:                 if ($now < $role_start) {
1.274     raeburn  8794:                     $active_chk = 'future';
                   8795:                 }
                   8796:             }
                   8797:             if ($role_end > 0) {
1.412     raeburn  8798:                 if ($now > $role_end) {
1.274     raeburn  8799:                     $active_chk = 'previous';
                   8800:                 }
                   8801:             }
                   8802:         }
                   8803:     }
                   8804:     return $active_chk;
                   8805: }
                   8806: 
                   8807: ###############################################
                   8808: 
                   8809: =pod
                   8810: 
1.405     albertel 8811: =item * &get_sections()
1.233     raeburn  8812: 
                   8813: Determines all the sections for a course including
                   8814: sections with students and sections containing other roles.
1.419     raeburn  8815: Incoming parameters: 
                   8816: 
                   8817: 1. domain
                   8818: 2. course number 
                   8819: 3. reference to array containing roles for which sections should 
                   8820: be gathered (optional).
                   8821: 4. reference to array containing status types for which sections 
                   8822: should be gathered (optional).
                   8823: 
                   8824: If the third argument is undefined, sections are gathered for any role. 
                   8825: If the fourth argument is undefined, sections are gathered for any status.
                   8826: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8827:  
1.374     raeburn  8828: Returns section hash (keys are section IDs, values are
                   8829: number of users in each section), subject to the
1.419     raeburn  8830: optional roles filter, optional status filter 
1.233     raeburn  8831: 
                   8832: =cut
                   8833: 
                   8834: ###############################################
                   8835: sub get_sections {
1.419     raeburn  8836:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8837:     if (!defined($cdom) || !defined($cnum)) {
                   8838:         my $cid =  $env{'request.course.id'};
                   8839: 
                   8840: 	return if (!defined($cid));
                   8841: 
                   8842:         $cdom = $env{'course.'.$cid.'.domain'};
                   8843:         $cnum = $env{'course.'.$cid.'.num'};
                   8844:     }
                   8845: 
                   8846:     my %sectioncount;
1.419     raeburn  8847:     my $now = time;
1.240     albertel 8848: 
1.1118    raeburn  8849:     my $check_students = 1;
                   8850:     my $only_students = 0;
                   8851:     if (ref($possible_roles) eq 'ARRAY') {
                   8852:         if (grep(/^st$/,@{$possible_roles})) {
                   8853:             if (@{$possible_roles} == 1) {
                   8854:                 $only_students = 1;
                   8855:             }
                   8856:         } else {
                   8857:             $check_students = 0;
                   8858:         }
                   8859:     }
                   8860: 
                   8861:     if ($check_students) { 
1.276     albertel 8862: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8863: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8864: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8865:         my $start_index = &Apache::loncoursedata::CL_START();
                   8866:         my $end_index = &Apache::loncoursedata::CL_END();
                   8867:         my $status;
1.366     albertel 8868: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8869: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8870: 				                     $data->[$status_index],
                   8871:                                                      $data->[$start_index],
                   8872:                                                      $data->[$end_index]);
                   8873:             if ($stu_status eq 'Active') {
                   8874:                 $status = 'active';
                   8875:             } elsif ($end < $now) {
                   8876:                 $status = 'previous';
                   8877:             } elsif ($start > $now) {
                   8878:                 $status = 'future';
                   8879:             } 
                   8880: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8881:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8882:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8883: 		    $sectioncount{$section}++;
                   8884:                 }
1.240     albertel 8885: 	    }
                   8886: 	}
                   8887:     }
1.1118    raeburn  8888:     if ($only_students) {
                   8889:         return %sectioncount;
                   8890:     }
1.240     albertel 8891:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8892:     foreach my $user (sort(keys(%courseroles))) {
                   8893: 	if ($user !~ /^(\w{2})/) { next; }
                   8894: 	my ($role) = ($user =~ /^(\w{2})/);
                   8895: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8896: 	my ($section,$status);
1.240     albertel 8897: 	if ($role eq 'cr' &&
                   8898: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8899: 	    $section=$1;
                   8900: 	}
                   8901: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8902: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8903:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8904:         if ($end == -1 && $start == -1) {
                   8905:             next; #deleted role
                   8906:         }
                   8907:         if (!defined($possible_status)) { 
                   8908:             $sectioncount{$section}++;
                   8909:         } else {
                   8910:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8911:                 $status = 'active';
                   8912:             } elsif ($end < $now) {
                   8913:                 $status = 'future';
                   8914:             } elsif ($start > $now) {
                   8915:                 $status = 'previous';
                   8916:             }
                   8917:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8918:                 $sectioncount{$section}++;
                   8919:             }
                   8920:         }
1.233     raeburn  8921:     }
1.366     albertel 8922:     return %sectioncount;
1.233     raeburn  8923: }
                   8924: 
1.274     raeburn  8925: ###############################################
1.294     raeburn  8926: 
                   8927: =pod
1.405     albertel 8928: 
                   8929: =item * &get_course_users()
                   8930: 
1.275     raeburn  8931: Retrieves usernames:domains for users in the specified course
                   8932: with specific role(s), and access status. 
                   8933: 
                   8934: Incoming parameters:
1.277     albertel 8935: 1. course domain
                   8936: 2. course number
                   8937: 3. access status: users must have - either active, 
1.275     raeburn  8938: previous, future, or all.
1.277     albertel 8939: 4. reference to array of permissible roles
1.288     raeburn  8940: 5. reference to array of section restrictions (optional)
                   8941: 6. reference to results object (hash of hashes).
                   8942: 7. reference to optional userdata hash
1.609     raeburn  8943: 8. reference to optional statushash
1.630     raeburn  8944: 9. flag if privileged users (except those set to unhide in
                   8945:    course settings) should be excluded    
1.609     raeburn  8946: Keys of top level results hash are roles.
1.275     raeburn  8947: Keys of inner hashes are username:domain, with 
                   8948: values set to access type.
1.288     raeburn  8949: Optional userdata hash returns an array with arguments in the 
                   8950: same order as loncoursedata::get_classlist() for student data.
                   8951: 
1.609     raeburn  8952: Optional statushash returns
                   8953: 
1.288     raeburn  8954: Entries for end, start, section and status are blank because
                   8955: of the possibility of multiple values for non-student roles.
                   8956: 
1.275     raeburn  8957: =cut
1.405     albertel 8958: 
1.275     raeburn  8959: ###############################################
1.405     albertel 8960: 
1.275     raeburn  8961: sub get_course_users {
1.630     raeburn  8962:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8963:     my %idx = ();
1.419     raeburn  8964:     my %seclists;
1.288     raeburn  8965: 
                   8966:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8967:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8968:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8969:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8970:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8971:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8972:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8973:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8974: 
1.290     albertel 8975:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8976:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8977:         my $now = time;
1.277     albertel 8978:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8979:             my $match = 0;
1.412     raeburn  8980:             my $secmatch = 0;
1.419     raeburn  8981:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8982:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8983:             if ($section eq '') {
                   8984:                 $section = 'none';
                   8985:             }
1.291     albertel 8986:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8987:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8988:                     $secmatch = 1;
                   8989:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8990:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8991:                         $secmatch = 1;
                   8992:                     }
                   8993:                 } else {  
1.419     raeburn  8994: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8995: 		        $secmatch = 1;
                   8996:                     }
1.290     albertel 8997: 		}
1.412     raeburn  8998:                 if (!$secmatch) {
                   8999:                     next;
                   9000:                 }
1.419     raeburn  9001:             }
1.275     raeburn  9002:             if (defined($$types{'active'})) {
1.288     raeburn  9003:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9004:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9005:                     $match = 1;
1.275     raeburn  9006:                 }
                   9007:             }
                   9008:             if (defined($$types{'previous'})) {
1.609     raeburn  9009:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9010:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9011:                     $match = 1;
1.275     raeburn  9012:                 }
                   9013:             }
                   9014:             if (defined($$types{'future'})) {
1.609     raeburn  9015:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9016:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9017:                     $match = 1;
1.275     raeburn  9018:                 }
                   9019:             }
1.609     raeburn  9020:             if ($match) {
                   9021:                 push(@{$seclists{$student}},$section);
                   9022:                 if (ref($userdata) eq 'HASH') {
                   9023:                     $$userdata{$student} = $$classlist{$student};
                   9024:                 }
                   9025:                 if (ref($statushash) eq 'HASH') {
                   9026:                     $statushash->{$student}{'st'}{$section} = $status;
                   9027:                 }
1.288     raeburn  9028:             }
1.275     raeburn  9029:         }
                   9030:     }
1.412     raeburn  9031:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9032:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9033:         my $now = time;
1.609     raeburn  9034:         my %displaystatus = ( previous => 'Expired',
                   9035:                               active   => 'Active',
                   9036:                               future   => 'Future',
                   9037:                             );
1.1121    raeburn  9038:         my (%nothide,@possdoms);
1.630     raeburn  9039:         if ($hidepriv) {
                   9040:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9041:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9042:                 if ($user !~ /:/) {
                   9043:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9044:                 } else {
                   9045:                     $nothide{$user} = 1;
                   9046:                 }
                   9047:             }
1.1121    raeburn  9048:             my @possdoms = ($cdom);
                   9049:             if ($coursehash{'checkforpriv'}) {
                   9050:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9051:             }
1.630     raeburn  9052:         }
1.439     raeburn  9053:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9054:             my $match = 0;
1.412     raeburn  9055:             my $secmatch = 0;
1.439     raeburn  9056:             my $status;
1.412     raeburn  9057:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9058:             $user =~ s/:$//;
1.439     raeburn  9059:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9060:             if ($end == -1 || $start == -1) {
                   9061:                 next;
                   9062:             }
                   9063:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9064:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9065:                 my ($uname,$udom) = split(/:/,$user);
                   9066:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9067:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9068:                         $secmatch = 1;
                   9069:                     } elsif ($usec eq '') {
1.420     albertel 9070:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9071:                             $secmatch = 1;
                   9072:                         }
                   9073:                     } else {
                   9074:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9075:                             $secmatch = 1;
                   9076:                         }
                   9077:                     }
                   9078:                     if (!$secmatch) {
                   9079:                         next;
                   9080:                     }
1.288     raeburn  9081:                 }
1.419     raeburn  9082:                 if ($usec eq '') {
                   9083:                     $usec = 'none';
                   9084:                 }
1.275     raeburn  9085:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9086:                     if ($hidepriv) {
1.1121    raeburn  9087:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9088:                             (!$nothide{$uname.':'.$udom})) {
                   9089:                             next;
                   9090:                         }
                   9091:                     }
1.503     raeburn  9092:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9093:                         $status = 'previous';
                   9094:                     } elsif ($start > $now) {
                   9095:                         $status = 'future';
                   9096:                     } else {
                   9097:                         $status = 'active';
                   9098:                     }
1.277     albertel 9099:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9100:                         if ($status eq $type) {
1.420     albertel 9101:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9102:                                 push(@{$$users{$role}{$user}},$type);
                   9103:                             }
1.288     raeburn  9104:                             $match = 1;
                   9105:                         }
                   9106:                     }
1.419     raeburn  9107:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9108:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9109: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9110:                         }
1.420     albertel 9111:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9112:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9113:                         }
1.609     raeburn  9114:                         if (ref($statushash) eq 'HASH') {
                   9115:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9116:                         }
1.275     raeburn  9117:                     }
                   9118:                 }
                   9119:             }
                   9120:         }
1.290     albertel 9121:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9122:             if ((defined($cdom)) && (defined($cnum))) {
                   9123:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9124:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9125:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9126:                     next if ($owner eq '');
                   9127:                     my ($ownername,$ownerdom);
                   9128:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9129:                         $ownername = $1;
                   9130:                         $ownerdom = $2;
                   9131:                     } else {
                   9132:                         $ownername = $owner;
                   9133:                         $ownerdom = $cdom;
                   9134:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9135:                     }
                   9136:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9137:                     if (defined($userdata) && 
1.609     raeburn  9138: 			!exists($$userdata{$owner})) {
                   9139: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9140:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9141:                             push(@{$seclists{$owner}},'none');
                   9142:                         }
                   9143:                         if (ref($statushash) eq 'HASH') {
                   9144:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9145:                         }
1.290     albertel 9146: 		    }
1.279     raeburn  9147:                 }
                   9148:             }
                   9149:         }
1.419     raeburn  9150:         foreach my $user (keys(%seclists)) {
                   9151:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9152:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9153:         }
1.275     raeburn  9154:     }
                   9155:     return;
                   9156: }
                   9157: 
1.288     raeburn  9158: sub get_user_info {
                   9159:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9160:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9161: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9162:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9163:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9164:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9165:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9166:     return;
                   9167: }
1.275     raeburn  9168: 
1.472     raeburn  9169: ###############################################
                   9170: 
                   9171: =pod
                   9172: 
                   9173: =item * &get_user_quota()
                   9174: 
1.1134    raeburn  9175: Retrieves quota assigned for storage of user files.
                   9176: Default is to report quota for portfolio files.
1.472     raeburn  9177: 
                   9178: Incoming parameters:
                   9179: 1. user's username
                   9180: 2. user's domain
1.1134    raeburn  9181: 3. quota name - portfolio, author, or course
1.1136    raeburn  9182:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  9183: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  9184:    course
1.472     raeburn  9185: 
                   9186: Returns:
1.1163    raeburn  9187: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9188: 2. (Optional) Type of setting: custom or default
                   9189:    (individually assigned or default for user's 
                   9190:    institutional status).
                   9191: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9192:    or student - types as defined in localenroll::inst_usertypes 
                   9193:    for user's domain, which determines default quota for user.
                   9194: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9195: 
                   9196: If a value has been stored in the user's environment, 
1.536     raeburn  9197: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9198: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9199: 
                   9200: =cut
                   9201: 
                   9202: ###############################################
                   9203: 
                   9204: 
                   9205: sub get_user_quota {
1.1136    raeburn  9206:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9207:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9208:     if (!defined($udom)) {
                   9209:         $udom = $env{'user.domain'};
                   9210:     }
                   9211:     if (!defined($uname)) {
                   9212:         $uname = $env{'user.name'};
                   9213:     }
                   9214:     if (($udom eq '' || $uname eq '') ||
                   9215:         ($udom eq 'public') && ($uname eq 'public')) {
                   9216:         $quota = 0;
1.536     raeburn  9217:         $quotatype = 'default';
                   9218:         $defquota = 0; 
1.472     raeburn  9219:     } else {
1.536     raeburn  9220:         my $inststatus;
1.1134    raeburn  9221:         if ($quotaname eq 'course') {
                   9222:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9223:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9224:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9225:             } else {
                   9226:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9227:                 $quota = $cenv{'internal.uploadquota'};
                   9228:             }
1.536     raeburn  9229:         } else {
1.1134    raeburn  9230:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9231:                 if ($quotaname eq 'author') {
                   9232:                     $quota = $env{'environment.authorquota'};
                   9233:                 } else {
                   9234:                     $quota = $env{'environment.portfolioquota'};
                   9235:                 }
                   9236:                 $inststatus = $env{'environment.inststatus'};
                   9237:             } else {
                   9238:                 my %userenv = 
                   9239:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9240:                                          'authorquota','inststatus'],$udom,$uname);
                   9241:                 my ($tmp) = keys(%userenv);
                   9242:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9243:                     if ($quotaname eq 'author') {
                   9244:                         $quota = $userenv{'authorquota'};
                   9245:                     } else {
                   9246:                         $quota = $userenv{'portfolioquota'};
                   9247:                     }
                   9248:                     $inststatus = $userenv{'inststatus'};
                   9249:                 } else {
                   9250:                     undef(%userenv);
                   9251:                 }
                   9252:             }
                   9253:         }
                   9254:         if ($quota eq '' || wantarray) {
                   9255:             if ($quotaname eq 'course') {
                   9256:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9257:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   9258:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  9259:                     $defquota = $domdefs{$crstype.'quota'};
                   9260:                 }
                   9261:                 if ($defquota eq '') {
                   9262:                     $defquota = 500;
                   9263:                 }
1.1134    raeburn  9264:             } else {
                   9265:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9266:             }
                   9267:             if ($quota eq '') {
                   9268:                 $quota = $defquota;
                   9269:                 $quotatype = 'default';
                   9270:             } else {
                   9271:                 $quotatype = 'custom';
                   9272:             }
1.472     raeburn  9273:         }
                   9274:     }
1.536     raeburn  9275:     if (wantarray) {
                   9276:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9277:     } else {
                   9278:         return $quota;
                   9279:     }
1.472     raeburn  9280: }
                   9281: 
                   9282: ###############################################
                   9283: 
                   9284: =pod
                   9285: 
                   9286: =item * &default_quota()
                   9287: 
1.536     raeburn  9288: Retrieves default quota assigned for storage of user portfolio files,
                   9289: given an (optional) user's institutional status.
1.472     raeburn  9290: 
                   9291: Incoming parameters:
1.1142    raeburn  9292: 
1.472     raeburn  9293: 1. domain
1.536     raeburn  9294: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9295:    status types (e.g., faculty, staff, student etc.)
                   9296:    which apply to the user for whom the default is being retrieved.
                   9297:    If the institutional status string in undefined, the domain
1.1134    raeburn  9298:    default quota will be returned.
                   9299: 3.  quota name - portfolio, author, or course
                   9300:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9301: 
                   9302: Returns:
1.1142    raeburn  9303: 
1.1163    raeburn  9304: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9305: 2. (Optional) institutional type which determined the value of the
                   9306:    default quota.
1.472     raeburn  9307: 
                   9308: If a value has been stored in the domain's configuration db,
                   9309: it will return that, otherwise it returns 20 (for backwards 
                   9310: compatibility with domains which have not set up a configuration
1.1163    raeburn  9311: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9312: 
1.536     raeburn  9313: If the user's status includes multiple types (e.g., staff and student),
                   9314: the largest default quota which applies to the user determines the
                   9315: default quota returned.
                   9316: 
1.472     raeburn  9317: =cut
                   9318: 
                   9319: ###############################################
                   9320: 
                   9321: 
                   9322: sub default_quota {
1.1134    raeburn  9323:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9324:     my ($defquota,$settingstatus);
                   9325:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9326:                                             ['quotas'],$udom);
1.1134    raeburn  9327:     my $key = 'defaultquota';
                   9328:     if ($quotaname eq 'author') {
                   9329:         $key = 'authorquota';
                   9330:     }
1.622     raeburn  9331:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9332:         if ($inststatus ne '') {
1.765     raeburn  9333:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9334:             foreach my $item (@statuses) {
1.1134    raeburn  9335:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9336:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9337:                         if ($defquota eq '') {
1.1134    raeburn  9338:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9339:                             $settingstatus = $item;
1.1134    raeburn  9340:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9341:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9342:                             $settingstatus = $item;
                   9343:                         }
                   9344:                     }
1.1134    raeburn  9345:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9346:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9347:                         if ($defquota eq '') {
                   9348:                             $defquota = $quotahash{'quotas'}{$item};
                   9349:                             $settingstatus = $item;
                   9350:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9351:                             $defquota = $quotahash{'quotas'}{$item};
                   9352:                             $settingstatus = $item;
                   9353:                         }
1.536     raeburn  9354:                     }
                   9355:                 }
                   9356:             }
                   9357:         }
                   9358:         if ($defquota eq '') {
1.1134    raeburn  9359:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9360:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9361:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9362:                 $defquota = $quotahash{'quotas'}{'default'};
                   9363:             }
1.536     raeburn  9364:             $settingstatus = 'default';
1.1139    raeburn  9365:             if ($defquota eq '') {
                   9366:                 if ($quotaname eq 'author') {
                   9367:                     $defquota = 500;
                   9368:                 }
                   9369:             }
1.536     raeburn  9370:         }
                   9371:     } else {
                   9372:         $settingstatus = 'default';
1.1134    raeburn  9373:         if ($quotaname eq 'author') {
                   9374:             $defquota = 500;
                   9375:         } else {
                   9376:             $defquota = 20;
                   9377:         }
1.536     raeburn  9378:     }
                   9379:     if (wantarray) {
                   9380:         return ($defquota,$settingstatus);
1.472     raeburn  9381:     } else {
1.536     raeburn  9382:         return $defquota;
1.472     raeburn  9383:     }
                   9384: }
                   9385: 
1.1135    raeburn  9386: ###############################################
                   9387: 
                   9388: =pod
                   9389: 
1.1136    raeburn  9390: =item * &excess_filesize_warning()
1.1135    raeburn  9391: 
                   9392: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9393: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9394: space to be exceeded.
1.1136    raeburn  9395: 
                   9396: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9397: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9398: 
1.1165    raeburn  9399: Inputs: 7 
1.1136    raeburn  9400: 1. username or coursenum
1.1135    raeburn  9401: 2. domain
1.1136    raeburn  9402: 3. context ('author' or 'course')
1.1135    raeburn  9403: 4. filename of file for which action is being requested
                   9404: 5. filesize (kB) of file
                   9405: 6. action being taken: copy or upload.
1.1165    raeburn  9406: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  9407: 
                   9408: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9409:          otherwise return null.
                   9410: 
                   9411: =back
1.1135    raeburn  9412: 
                   9413: =cut
                   9414: 
1.1136    raeburn  9415: sub excess_filesize_warning {
1.1165    raeburn  9416:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9417:     my $current_disk_usage = 0;
1.1165    raeburn  9418:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9419:     if ($context eq 'author') {
                   9420:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9421:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9422:     } else {
                   9423:         foreach my $subdir ('docs','supplemental') {
                   9424:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9425:         }
                   9426:     }
1.1135    raeburn  9427:     $disk_quota = int($disk_quota * 1000);
                   9428:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9429:         return '<p class="LC_warning">'.
1.1135    raeburn  9430:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9431:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9432:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9433:                             $disk_quota,$current_disk_usage).
                   9434:                '</p>';
                   9435:     }
                   9436:     return;
                   9437: }
                   9438: 
                   9439: ###############################################
                   9440: 
                   9441: 
1.1136    raeburn  9442: 
                   9443: 
1.384     raeburn  9444: sub get_secgrprole_info {
                   9445:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9446:     my %sections_count = &get_sections($cdom,$cnum);
                   9447:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9448:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9449:     my @groups = sort(keys(%curr_groups));
                   9450:     my $allroles = [];
                   9451:     my $rolehash;
                   9452:     my $accesshash = {
                   9453:                      active => 'Currently has access',
                   9454:                      future => 'Will have future access',
                   9455:                      previous => 'Previously had access',
                   9456:                   };
                   9457:     if ($needroles) {
                   9458:         $rolehash = {'all' => 'all'};
1.385     albertel 9459:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9460: 	if (&Apache::lonnet::error(%user_roles)) {
                   9461: 	    undef(%user_roles);
                   9462: 	}
                   9463:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9464:             my ($role)=split(/\:/,$item,2);
                   9465:             if ($role eq 'cr') { next; }
                   9466:             if ($role =~ /^cr/) {
                   9467:                 $$rolehash{$role} = (split('/',$role))[3];
                   9468:             } else {
                   9469:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9470:             }
                   9471:         }
                   9472:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9473:             push(@{$allroles},$key);
                   9474:         }
                   9475:         push (@{$allroles},'st');
                   9476:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9477:     }
                   9478:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9479: }
                   9480: 
1.555     raeburn  9481: sub user_picker {
1.994     raeburn  9482:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9483:     my $currdom = $dom;
                   9484:     my %curr_selected = (
                   9485:                         srchin => 'dom',
1.580     raeburn  9486:                         srchby => 'lastname',
1.555     raeburn  9487:                       );
                   9488:     my $srchterm;
1.625     raeburn  9489:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9490:         if ($srch->{'srchby'} ne '') {
                   9491:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9492:         }
                   9493:         if ($srch->{'srchin'} ne '') {
                   9494:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9495:         }
                   9496:         if ($srch->{'srchtype'} ne '') {
                   9497:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9498:         }
                   9499:         if ($srch->{'srchdomain'} ne '') {
                   9500:             $currdom = $srch->{'srchdomain'};
                   9501:         }
                   9502:         $srchterm = $srch->{'srchterm'};
                   9503:     }
                   9504:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9505:                     'usr'       => 'Search criteria',
1.563     raeburn  9506:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9507:                     'uname'     => 'username',
                   9508:                     'lastname'  => 'last name',
1.555     raeburn  9509:                     'lastfirst' => 'last name, first name',
1.558     albertel 9510:                     'crs'       => 'in this course',
1.576     raeburn  9511:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9512:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9513:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9514:                     'exact'     => 'is',
                   9515:                     'contains'  => 'contains',
1.569     raeburn  9516:                     'begins'    => 'begins with',
1.571     raeburn  9517:                     'youm'      => "You must include some text to search for.",
                   9518:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9519:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9520:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9521:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9522:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9523:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9524:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9525:                                        );
1.563     raeburn  9526:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9527:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9528: 
                   9529:     my @srchins = ('crs','dom','alc','instd');
                   9530: 
                   9531:     foreach my $option (@srchins) {
                   9532:         # FIXME 'alc' option unavailable until 
                   9533:         #       loncreateuser::print_user_query_page()
                   9534:         #       has been completed.
                   9535:         next if ($option eq 'alc');
1.880     raeburn  9536:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9537:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9538:         if ($curr_selected{'srchin'} eq $option) {
                   9539:             $srchinsel .= ' 
                   9540:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9541:         } else {
                   9542:             $srchinsel .= '
                   9543:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9544:         }
1.555     raeburn  9545:     }
1.563     raeburn  9546:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9547: 
                   9548:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9549:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9550:         if ($curr_selected{'srchby'} eq $option) {
                   9551:             $srchbysel .= '
                   9552:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9553:         } else {
                   9554:             $srchbysel .= '
                   9555:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9556:          }
                   9557:     }
                   9558:     $srchbysel .= "\n  </select>\n";
                   9559: 
                   9560:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9561:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9562:         if ($curr_selected{'srchtype'} eq $option) {
                   9563:             $srchtypesel .= '
                   9564:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9565:         } else {
                   9566:             $srchtypesel .= '
                   9567:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9568:         }
                   9569:     }
                   9570:     $srchtypesel .= "\n  </select>\n";
                   9571: 
1.558     albertel 9572:     my ($newuserscript,$new_user_create);
1.994     raeburn  9573:     my $context_dom = $env{'request.role.domain'};
                   9574:     if ($context eq 'requestcrs') {
                   9575:         if ($env{'form.coursedom'} ne '') { 
                   9576:             $context_dom = $env{'form.coursedom'};
                   9577:         }
                   9578:     }
1.556     raeburn  9579:     if ($forcenewuser) {
1.576     raeburn  9580:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9581:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9582:                 if ($cancreate) {
                   9583:                     $new_user_create = '<p> <input type="submit" name="forcenew" value="'.&HTML::Entities::encode(&mt('Make new user "[_1]"',$srchterm),'<>&"').'" onclick="javascript:setSearch(\'1\','.$caller.');" /> </p>';
                   9584:                 } else {
1.799     bisitz   9585:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9586:                     my %usertypetext = (
                   9587:                         official   => 'institutional',
                   9588:                         unofficial => 'non-institutional',
                   9589:                     );
1.799     bisitz   9590:                     $new_user_create = '<p class="LC_warning">'
                   9591:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9592:                                       .' '
                   9593:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9594:                                           ,'<a href="'.$helplink.'">','</a>')
                   9595:                                       .'</p><br />';
1.627     raeburn  9596:                 }
1.576     raeburn  9597:             }
                   9598:         }
                   9599: 
1.556     raeburn  9600:         $newuserscript = <<"ENDSCRIPT";
                   9601: 
1.570     raeburn  9602: function setSearch(createnew,callingForm) {
1.556     raeburn  9603:     if (createnew == 1) {
1.570     raeburn  9604:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9605:             if (callingForm.srchby.options[i].value == 'uname') {
                   9606:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9607:             }
                   9608:         }
1.570     raeburn  9609:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9610:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9611: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9612:             }
                   9613:         }
1.570     raeburn  9614:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9615:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9616:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9617:             }
                   9618:         }
1.570     raeburn  9619:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9620:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9621:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9622:             }
                   9623:         }
                   9624:     }
                   9625: }
                   9626: ENDSCRIPT
1.558     albertel 9627: 
1.556     raeburn  9628:     }
                   9629: 
1.555     raeburn  9630:     my $output = <<"END_BLOCK";
1.556     raeburn  9631: <script type="text/javascript">
1.824     bisitz   9632: // <![CDATA[
1.570     raeburn  9633: function validateEntry(callingForm) {
1.558     albertel 9634: 
1.556     raeburn  9635:     var checkok = 1;
1.558     albertel 9636:     var srchin;
1.570     raeburn  9637:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9638: 	if ( callingForm.srchin[i].checked ) {
                   9639: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9640: 	}
                   9641:     }
                   9642: 
1.570     raeburn  9643:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9644:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9645:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9646:     var srchterm =  callingForm.srchterm.value;
                   9647:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9648:     var msg = "";
                   9649: 
                   9650:     if (srchterm == "") {
                   9651:         checkok = 0;
1.571     raeburn  9652:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9653:     }
                   9654: 
1.569     raeburn  9655:     if (srchtype== 'begins') {
                   9656:         if (srchterm.length < 2) {
                   9657:             checkok = 0;
1.571     raeburn  9658:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9659:         }
                   9660:     }
                   9661: 
1.556     raeburn  9662:     if (srchtype== 'contains') {
                   9663:         if (srchterm.length < 3) {
                   9664:             checkok = 0;
1.571     raeburn  9665:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9666:         }
                   9667:     }
                   9668:     if (srchin == 'instd') {
                   9669:         if (srchdomain == '') {
                   9670:             checkok = 0;
1.571     raeburn  9671:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9672:         }
                   9673:     }
                   9674:     if (srchin == 'dom') {
                   9675:         if (srchdomain == '') {
                   9676:             checkok = 0;
1.571     raeburn  9677:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9678:         }
                   9679:     }
                   9680:     if (srchby == 'lastfirst') {
                   9681:         if (srchterm.indexOf(",") == -1) {
                   9682:             checkok = 0;
1.571     raeburn  9683:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9684:         }
                   9685:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9686:             checkok = 0;
1.571     raeburn  9687:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9688:         }
                   9689:     }
                   9690:     if (checkok == 0) {
1.571     raeburn  9691:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9692:         return;
                   9693:     }
                   9694:     if (checkok == 1) {
1.570     raeburn  9695:         callingForm.submit();
1.556     raeburn  9696:     }
                   9697: }
                   9698: 
                   9699: $newuserscript
                   9700: 
1.824     bisitz   9701: // ]]>
1.556     raeburn  9702: </script>
1.558     albertel 9703: 
                   9704: $new_user_create
                   9705: 
1.555     raeburn  9706: END_BLOCK
1.558     albertel 9707: 
1.876     raeburn  9708:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9709:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9710:                $domform.
                   9711:                &Apache::lonhtmlcommon::row_closure().
                   9712:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9713:                $srchbysel.
                   9714:                $srchtypesel. 
                   9715:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9716:                $srchinsel.
                   9717:                &Apache::lonhtmlcommon::row_closure(1). 
                   9718:                &Apache::lonhtmlcommon::end_pick_box().
                   9719:                '<br />';
1.555     raeburn  9720:     return $output;
                   9721: }
                   9722: 
1.612     raeburn  9723: sub user_rule_check {
1.615     raeburn  9724:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9725:     my $response;
                   9726:     if (ref($usershash) eq 'HASH') {
                   9727:         foreach my $user (keys(%{$usershash})) {
                   9728:             my ($uname,$udom) = split(/:/,$user);
                   9729:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9730:             my ($id,$newuser);
1.612     raeburn  9731:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9732:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9733:                 $id = $usershash->{$user}->{'id'};
                   9734:             }
                   9735:             my $inst_response;
                   9736:             if (ref($checks) eq 'HASH') {
                   9737:                 if (defined($checks->{'username'})) {
1.615     raeburn  9738:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9739:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9740:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9741:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9742:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9743:                 }
1.615     raeburn  9744:             } else {
                   9745:                 ($inst_response,%{$inst_results->{$user}}) =
                   9746:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9747:                 return;
1.612     raeburn  9748:             }
1.615     raeburn  9749:             if (!$got_rules->{$udom}) {
1.612     raeburn  9750:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9751:                                                   ['usercreation'],$udom);
                   9752:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9753:                     foreach my $item ('username','id') {
1.612     raeburn  9754:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9755:                             $$curr_rules{$udom}{$item} = 
                   9756:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9757:                         }
                   9758:                     }
                   9759:                 }
1.615     raeburn  9760:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9761:             }
1.612     raeburn  9762:             foreach my $item (keys(%{$checks})) {
                   9763:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9764:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9765:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9766:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9767:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9768:                                 if ($rule_check{$rule}) {
                   9769:                                     $$rulematch{$user}{$item} = $rule;
                   9770:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9771:                                         if (ref($inst_results) eq 'HASH') {
                   9772:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9773:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9774:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9775:                                                 }
1.612     raeburn  9776:                                             }
                   9777:                                         }
1.615     raeburn  9778:                                     }
                   9779:                                     last;
1.585     raeburn  9780:                                 }
                   9781:                             }
                   9782:                         }
                   9783:                     }
                   9784:                 }
                   9785:             }
                   9786:         }
                   9787:     }
1.612     raeburn  9788:     return;
                   9789: }
                   9790: 
                   9791: sub user_rule_formats {
                   9792:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9793:     my %text = ( 
                   9794:                  'username' => 'Usernames',
                   9795:                  'id'       => 'IDs',
                   9796:                );
                   9797:     my $output;
                   9798:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9799:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9800:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9801:             $output = '<br />'.
                   9802:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9803:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9804:                       ' <ul>';
1.612     raeburn  9805:             foreach my $rule (@{$ruleorder}) {
                   9806:                 if (ref($curr_rules) eq 'ARRAY') {
                   9807:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9808:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9809:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9810:                                         $rules->{$rule}{'desc'}.'</li>';
                   9811:                         }
                   9812:                     }
                   9813:                 }
                   9814:             }
                   9815:             $output .= '</ul>';
                   9816:         }
                   9817:     }
                   9818:     return $output;
                   9819: }
                   9820: 
                   9821: sub instrule_disallow_msg {
1.615     raeburn  9822:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9823:     my $response;
                   9824:     my %text = (
                   9825:                   item   => 'username',
                   9826:                   items  => 'usernames',
                   9827:                   match  => 'matches',
                   9828:                   do     => 'does',
                   9829:                   action => 'a username',
                   9830:                   one    => 'one',
                   9831:                );
                   9832:     if ($count > 1) {
                   9833:         $text{'item'} = 'usernames';
                   9834:         $text{'match'} ='match';
                   9835:         $text{'do'} = 'do';
                   9836:         $text{'action'} = 'usernames',
                   9837:         $text{'one'} = 'ones';
                   9838:     }
                   9839:     if ($checkitem eq 'id') {
                   9840:         $text{'items'} = 'IDs';
                   9841:         $text{'item'} = 'ID';
                   9842:         $text{'action'} = 'an ID';
1.615     raeburn  9843:         if ($count > 1) {
                   9844:             $text{'item'} = 'IDs';
                   9845:             $text{'action'} = 'IDs';
                   9846:         }
1.612     raeburn  9847:     }
1.674     bisitz   9848:     $response = &mt("The $text{'item'} you chose $text{'match'} the format of $text{'items'} defined for [_1], but the $text{'item'} $text{'do'} not exist in the institutional directory.",'<span class="LC_cusr_emph">'.$domdesc.'</span>').'<br />';
1.615     raeburn  9849:     if ($mode eq 'upload') {
                   9850:         if ($checkitem eq 'username') {
                   9851:             $response .= &mt("You will need to modify your upload file so it will include $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9852:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9853:             $response .= &mt("Either upload a file which includes $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or when associating fields with data columns, omit an association for the Student/Employee ID field.");
1.615     raeburn  9854:         }
1.669     raeburn  9855:     } elsif ($mode eq 'selfcreate') {
                   9856:         if ($checkitem eq 'id') {
                   9857:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
                   9858:         }
1.615     raeburn  9859:     } else {
                   9860:         if ($checkitem eq 'username') {
                   9861:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9862:         } elsif ($checkitem eq 'id') {
                   9863:             $response .= &mt("You must either choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}, or leave the ID field blank.");
                   9864:         }
1.612     raeburn  9865:     }
                   9866:     return $response;
1.585     raeburn  9867: }
                   9868: 
1.624     raeburn  9869: sub personal_data_fieldtitles {
                   9870:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9871:                         id => 'Student/Employee ID',
                   9872:                         permanentemail => 'E-mail address',
                   9873:                         lastname => 'Last Name',
                   9874:                         firstname => 'First Name',
                   9875:                         middlename => 'Middle Name',
                   9876:                         generation => 'Generation',
                   9877:                         gen => 'Generation',
1.765     raeburn  9878:                         inststatus => 'Affiliation',
1.624     raeburn  9879:                    );
                   9880:     return %fieldtitles;
                   9881: }
                   9882: 
1.642     raeburn  9883: sub sorted_inst_types {
                   9884:     my ($dom) = @_;
1.1185    raeburn  9885:     my ($usertypes,$order);
                   9886:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9887:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9888:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9889:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9890:     } else {
                   9891:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9892:     }
1.642     raeburn  9893:     my $othertitle = &mt('All users');
                   9894:     if ($env{'request.course.id'}) {
1.668     raeburn  9895:         $othertitle  = &mt('Any users');
1.642     raeburn  9896:     }
                   9897:     my @types;
                   9898:     if (ref($order) eq 'ARRAY') {
                   9899:         @types = @{$order};
                   9900:     }
                   9901:     if (@types == 0) {
                   9902:         if (ref($usertypes) eq 'HASH') {
                   9903:             @types = sort(keys(%{$usertypes}));
                   9904:         }
                   9905:     }
                   9906:     if (keys(%{$usertypes}) > 0) {
                   9907:         $othertitle = &mt('Other users');
                   9908:     }
                   9909:     return ($othertitle,$usertypes,\@types);
                   9910: }
                   9911: 
1.645     raeburn  9912: sub get_institutional_codes {
                   9913:     my ($settings,$allcourses,$LC_code) = @_;
                   9914: # Get complete list of course sections to update
                   9915:     my @currsections = ();
                   9916:     my @currxlists = ();
                   9917:     my $coursecode = $$settings{'internal.coursecode'};
                   9918: 
                   9919:     if ($$settings{'internal.sectionnums'} ne '') {
                   9920:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9921:     }
                   9922: 
                   9923:     if ($$settings{'internal.crosslistings'} ne '') {
                   9924:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9925:     }
                   9926: 
                   9927:     if (@currxlists > 0) {
                   9928:         foreach (@currxlists) {
                   9929:             if (m/^([^:]+):(\w*)$/) {
                   9930:                 unless (grep/^$1$/,@{$allcourses}) {
                   9931:                     push @{$allcourses},$1;
                   9932:                     $$LC_code{$1} = $2;
                   9933:                 }
                   9934:             }
                   9935:         }
                   9936:     }
                   9937:  
                   9938:     if (@currsections > 0) {
                   9939:         foreach (@currsections) {
                   9940:             if (m/^(\w+):(\w*)$/) {
                   9941:                 my $sec = $coursecode.$1;
                   9942:                 my $lc_sec = $2;
                   9943:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9944:                     push @{$allcourses},$sec;
                   9945:                     $$LC_code{$sec} = $lc_sec;
                   9946:                 }
                   9947:             }
                   9948:         }
                   9949:     }
                   9950:     return;
                   9951: }
                   9952: 
1.971     raeburn  9953: sub get_standard_codeitems {
                   9954:     return ('Year','Semester','Department','Number','Section');
                   9955: }
                   9956: 
1.112     bowersj2 9957: =pod
                   9958: 
1.780     raeburn  9959: =head1 Slot Helpers
                   9960: 
                   9961: =over 4
                   9962: 
                   9963: =item * sorted_slots()
                   9964: 
1.1040    raeburn  9965: Sorts an array of slot names in order of an optional sort key,
                   9966: default sort is by slot start time (earliest first). 
1.780     raeburn  9967: 
                   9968: Inputs:
                   9969: 
                   9970: =over 4
                   9971: 
                   9972: slotsarr  - Reference to array of unsorted slot names.
                   9973: 
                   9974: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9975: 
1.1040    raeburn  9976: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9977: 
1.549     albertel 9978: =back
                   9979: 
1.780     raeburn  9980: Returns:
                   9981: 
                   9982: =over 4
                   9983: 
1.1040    raeburn  9984: sorted   - An array of slot names sorted by a specified sort key 
                   9985:            (default sort key is start time of the slot).
1.780     raeburn  9986: 
                   9987: =back
                   9988: 
                   9989: =cut
                   9990: 
                   9991: 
                   9992: sub sorted_slots {
1.1040    raeburn  9993:     my ($slotsarr,$slots,$sortkey) = @_;
                   9994:     if ($sortkey eq '') {
                   9995:         $sortkey = 'starttime';
                   9996:     }
1.780     raeburn  9997:     my @sorted;
                   9998:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9999:         @sorted =
                   10000:             sort {
                   10001:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10002:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10003:                      }
                   10004:                      if (ref($slots->{$a})) { return -1;}
                   10005:                      if (ref($slots->{$b})) { return 1;}
                   10006:                      return 0;
                   10007:                  } @{$slotsarr};
                   10008:     }
                   10009:     return @sorted;
                   10010: }
                   10011: 
1.1040    raeburn  10012: =pod
                   10013: 
                   10014: =item * get_future_slots()
                   10015: 
                   10016: Inputs:
                   10017: 
                   10018: =over 4
                   10019: 
                   10020: cnum - course number
                   10021: 
                   10022: cdom - course domain
                   10023: 
                   10024: now - current UNIX time
                   10025: 
                   10026: symb - optional symb
                   10027: 
                   10028: =back
                   10029: 
                   10030: Returns:
                   10031: 
                   10032: =over 4
                   10033: 
                   10034: sorted_reservable - ref to array of student_schedulable slots currently 
                   10035:                     reservable, ordered by end date of reservation period.
                   10036: 
                   10037: reservable_now - ref to hash of student_schedulable slots currently
                   10038:                  reservable.
                   10039: 
                   10040:     Keys in inner hash are:
                   10041:     (a) symb: either blank or symb to which slot use is restricted.
                   10042:     (b) endreserve: end date of reservation period. 
                   10043: 
                   10044: sorted_future - ref to array of student_schedulable slots reservable in
                   10045:                 the future, ordered by start date of reservation period.
                   10046: 
                   10047: future_reservable - ref to hash of student_schedulable slots reservable
                   10048:                     in the future.
                   10049: 
                   10050:     Keys in inner hash are:
                   10051:     (a) symb: either blank or symb to which slot use is restricted.
                   10052:     (b) startreserve:  start date of reservation period.
                   10053: 
                   10054: =back
                   10055: 
                   10056: =cut
                   10057: 
                   10058: sub get_future_slots {
                   10059:     my ($cnum,$cdom,$now,$symb) = @_;
                   10060:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10061:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10062:     foreach my $slot (keys(%slots)) {
                   10063:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10064:         if ($symb) {
                   10065:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10066:                      ($slots{$slot}->{'symb'} ne $symb));
                   10067:         }
                   10068:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10069:             ($slots{$slot}->{'endtime'} > $now)) {
                   10070:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10071:                 my $userallowed = 0;
                   10072:                 if ($slots{$slot}->{'allowedsections'}) {
                   10073:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10074:                     if (!defined($env{'request.role.sec'})
                   10075:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10076:                         $userallowed=1;
                   10077:                     } else {
                   10078:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10079:                             $userallowed=1;
                   10080:                         }
                   10081:                     }
                   10082:                     unless ($userallowed) {
                   10083:                         if (defined($env{'request.course.groups'})) {
                   10084:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10085:                             foreach my $group (@groups) {
                   10086:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10087:                                     $userallowed=1;
                   10088:                                     last;
                   10089:                                 }
                   10090:                             }
                   10091:                         }
                   10092:                     }
                   10093:                 }
                   10094:                 if ($slots{$slot}->{'allowedusers'}) {
                   10095:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10096:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10097:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10098:                         $userallowed = 1;
                   10099:                     }
                   10100:                 }
                   10101:                 next unless($userallowed);
                   10102:             }
                   10103:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10104:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10105:             my $symb = $slots{$slot}->{'symb'};
                   10106:             if (($startreserve < $now) &&
                   10107:                 (!$endreserve || $endreserve > $now)) {
                   10108:                 my $lastres = $endreserve;
                   10109:                 if (!$lastres) {
                   10110:                     $lastres = $slots{$slot}->{'starttime'};
                   10111:                 }
                   10112:                 $reservable_now{$slot} = {
                   10113:                                            symb       => $symb,
                   10114:                                            endreserve => $lastres
                   10115:                                          };
                   10116:             } elsif (($startreserve > $now) &&
                   10117:                      (!$endreserve || $endreserve > $startreserve)) {
                   10118:                 $future_reservable{$slot} = {
                   10119:                                               symb         => $symb,
                   10120:                                               startreserve => $startreserve
                   10121:                                             };
                   10122:             }
                   10123:         }
                   10124:     }
                   10125:     my @unsorted_reservable = keys(%reservable_now);
                   10126:     if (@unsorted_reservable > 0) {
                   10127:         @sorted_reservable = 
                   10128:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10129:     }
                   10130:     my @unsorted_future = keys(%future_reservable);
                   10131:     if (@unsorted_future > 0) {
                   10132:         @sorted_future =
                   10133:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10134:     }
                   10135:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10136: }
1.780     raeburn  10137: 
                   10138: =pod
                   10139: 
1.1057    foxr     10140: =back
                   10141: 
1.549     albertel 10142: =head1 HTTP Helpers
                   10143: 
                   10144: =over 4
                   10145: 
1.648     raeburn  10146: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10147: 
1.258     albertel 10148: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10149: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10150: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10151: 
                   10152: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10153: $possible_names is an ref to an array of form element names.  As an example:
                   10154: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10155: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10156: 
                   10157: =cut
1.1       albertel 10158: 
1.6       albertel 10159: sub get_unprocessed_cgi {
1.25      albertel 10160:   my ($query,$possible_names)= @_;
1.26      matthew  10161:   # $Apache::lonxml::debug=1;
1.356     albertel 10162:   foreach my $pair (split(/&/,$query)) {
                   10163:     my ($name, $value) = split(/=/,$pair);
1.369     www      10164:     $name = &unescape($name);
1.25      albertel 10165:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10166:       $value =~ tr/+/ /;
                   10167:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10168:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10169:     }
1.16      harris41 10170:   }
1.6       albertel 10171: }
                   10172: 
1.112     bowersj2 10173: =pod
                   10174: 
1.648     raeburn  10175: =item * &cacheheader() 
1.112     bowersj2 10176: 
                   10177: returns cache-controlling header code
                   10178: 
                   10179: =cut
                   10180: 
1.7       albertel 10181: sub cacheheader {
1.258     albertel 10182:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10183:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10184:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10185:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10186:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10187:     return $output;
1.7       albertel 10188: }
                   10189: 
1.112     bowersj2 10190: =pod
                   10191: 
1.648     raeburn  10192: =item * &no_cache($r) 
1.112     bowersj2 10193: 
                   10194: specifies header code to not have cache
                   10195: 
                   10196: =cut
                   10197: 
1.9       albertel 10198: sub no_cache {
1.216     albertel 10199:     my ($r) = @_;
                   10200:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10201: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10202:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10203:     $r->no_cache(1);
                   10204:     $r->header_out("Expires" => $date);
                   10205:     $r->header_out("Pragma" => "no-cache");
1.123     www      10206: }
                   10207: 
                   10208: sub content_type {
1.181     albertel 10209:     my ($r,$type,$charset) = @_;
1.299     foxr     10210:     if ($r) {
                   10211: 	#  Note that printout.pl calls this with undef for $r.
                   10212: 	&no_cache($r);
                   10213:     }
1.258     albertel 10214:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10215:     unless ($charset) {
                   10216: 	$charset=&Apache::lonlocal::current_encoding;
                   10217:     }
                   10218:     if ($charset) { $type.='; charset='.$charset; }
                   10219:     if ($r) {
                   10220: 	$r->content_type($type);
                   10221:     } else {
                   10222: 	print("Content-type: $type\n\n");
                   10223:     }
1.9       albertel 10224: }
1.25      albertel 10225: 
1.112     bowersj2 10226: =pod
                   10227: 
1.648     raeburn  10228: =item * &add_to_env($name,$value) 
1.112     bowersj2 10229: 
1.258     albertel 10230: adds $name to the %env hash with value
1.112     bowersj2 10231: $value, if $name already exists, the entry is converted to an array
                   10232: reference and $value is added to the array.
                   10233: 
                   10234: =cut
                   10235: 
1.25      albertel 10236: sub add_to_env {
                   10237:   my ($name,$value)=@_;
1.258     albertel 10238:   if (defined($env{$name})) {
                   10239:     if (ref($env{$name})) {
1.25      albertel 10240:       #already have multiple values
1.258     albertel 10241:       push(@{ $env{$name} },$value);
1.25      albertel 10242:     } else {
                   10243:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10244:       my $first=$env{$name};
                   10245:       undef($env{$name});
                   10246:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10247:     }
                   10248:   } else {
1.258     albertel 10249:     $env{$name}=$value;
1.25      albertel 10250:   }
1.31      albertel 10251: }
1.149     albertel 10252: 
                   10253: =pod
                   10254: 
1.648     raeburn  10255: =item * &get_env_multiple($name) 
1.149     albertel 10256: 
1.258     albertel 10257: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10258: values may be defined and end up as an array ref.
                   10259: 
                   10260: returns an array of values
                   10261: 
                   10262: =cut
                   10263: 
                   10264: sub get_env_multiple {
                   10265:     my ($name) = @_;
                   10266:     my @values;
1.258     albertel 10267:     if (defined($env{$name})) {
1.149     albertel 10268:         # exists is it an array
1.258     albertel 10269:         if (ref($env{$name})) {
                   10270:             @values=@{ $env{$name} };
1.149     albertel 10271:         } else {
1.258     albertel 10272:             $values[0]=$env{$name};
1.149     albertel 10273:         }
                   10274:     }
                   10275:     return(@values);
                   10276: }
                   10277: 
1.660     raeburn  10278: sub ask_for_embedded_content {
                   10279:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10280:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10281:         %currsubfile,%unused,$rem);
1.1071    raeburn  10282:     my $counter = 0;
                   10283:     my $numnew = 0;
1.987     raeburn  10284:     my $numremref = 0;
                   10285:     my $numinvalid = 0;
                   10286:     my $numpathchg = 0;
                   10287:     my $numexisting = 0;
1.1071    raeburn  10288:     my $numunused = 0;
                   10289:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10290:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10291:     my $heading = &mt('Upload embedded files');
                   10292:     my $buttontext = &mt('Upload');
                   10293: 
1.1085    raeburn  10294:     if ($env{'request.course.id'}) {
1.1123    raeburn  10295:         if ($actionurl eq '/adm/dependencies') {
                   10296:             $navmap = Apache::lonnavmaps::navmap->new();
                   10297:         }
                   10298:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10299:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10300:     }
1.1123    raeburn  10301:     if (($actionurl eq '/adm/portfolio') || 
                   10302:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10303:         my $current_path='/';
                   10304:         if ($env{'form.currentpath'}) {
                   10305:             $current_path = $env{'form.currentpath'};
                   10306:         }
                   10307:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10308:             $udom = $cdom;
                   10309:             $uname = $cnum;
1.984     raeburn  10310:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10311:         } else {
                   10312:             $udom = $env{'user.domain'};
                   10313:             $uname = $env{'user.name'};
                   10314:             $url = '/userfiles/portfolio';
                   10315:         }
1.987     raeburn  10316:         $toplevel = $url.'/';
1.984     raeburn  10317:         $url .= $current_path;
                   10318:         $getpropath = 1;
1.987     raeburn  10319:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10320:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10321:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10322:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10323:         $toplevel = $url;
1.984     raeburn  10324:         if ($rest ne '') {
1.987     raeburn  10325:             $url .= $rest;
                   10326:         }
                   10327:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10328:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10329:             $url = $args->{'docs_url'};
                   10330:             $toplevel = $url;
1.1084    raeburn  10331:             if ($args->{'context'} eq 'paste') {
                   10332:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10333:                 ($path) = 
                   10334:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10335:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10336:                 $fileloc =~ s{^/}{};
                   10337:             }
1.1071    raeburn  10338:         }
1.1084    raeburn  10339:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10340:         if ($env{'request.course.id'} ne '') {
                   10341:             if (ref($args) eq 'HASH') {
                   10342:                 $url = $args->{'docs_url'};
                   10343:                 $title = $args->{'docs_title'};
1.1126    raeburn  10344:                 $toplevel = $url; 
                   10345:                 unless ($toplevel =~ m{^/}) {
                   10346:                     $toplevel = "/$url";
                   10347:                 }
1.1085    raeburn  10348:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10349:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10350:                     $path = $1;
                   10351:                 } else {
                   10352:                     ($path) =
                   10353:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10354:                 }
1.1195    raeburn  10355:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10356:                     $fileloc = $toplevel;
                   10357:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10358:                     my ($udom,$uname,$fname) =
                   10359:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10360:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10361:                 } else {
                   10362:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10363:                 }
1.1071    raeburn  10364:                 $fileloc =~ s{^/}{};
                   10365:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10366:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10367:             }
1.987     raeburn  10368:         }
1.1123    raeburn  10369:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10370:         $udom = $cdom;
                   10371:         $uname = $cnum;
                   10372:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10373:         $toplevel = $url;
                   10374:         $path = $url;
                   10375:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10376:         $fileloc =~ s{^/}{};
1.987     raeburn  10377:     }
1.1126    raeburn  10378:     foreach my $file (keys(%{$allfiles})) {
                   10379:         my $embed_file;
                   10380:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10381:             $embed_file = $1;
                   10382:         } else {
                   10383:             $embed_file = $file;
                   10384:         }
1.1158    raeburn  10385:         my ($absolutepath,$cleaned_file);
                   10386:         if ($embed_file =~ m{^\w+://}) {
                   10387:             $cleaned_file = $embed_file;
1.1147    raeburn  10388:             $newfiles{$cleaned_file} = 1;
                   10389:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10390:         } else {
1.1158    raeburn  10391:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10392:             if ($embed_file =~ m{^/}) {
                   10393:                 $absolutepath = $embed_file;
                   10394:             }
1.1147    raeburn  10395:             if ($cleaned_file =~ m{/}) {
                   10396:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10397:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10398:                 my $item = $fname;
                   10399:                 if ($path ne '') {
                   10400:                     $item = $path.'/'.$fname;
                   10401:                     $subdependencies{$path}{$fname} = 1;
                   10402:                 } else {
                   10403:                     $dependencies{$item} = 1;
                   10404:                 }
                   10405:                 if ($absolutepath) {
                   10406:                     $mapping{$item} = $absolutepath;
                   10407:                 } else {
                   10408:                     $mapping{$item} = $embed_file;
                   10409:                 }
                   10410:             } else {
                   10411:                 $dependencies{$embed_file} = 1;
                   10412:                 if ($absolutepath) {
1.1147    raeburn  10413:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10414:                 } else {
1.1147    raeburn  10415:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10416:                 }
                   10417:             }
1.984     raeburn  10418:         }
                   10419:     }
1.1071    raeburn  10420:     my $dirptr = 16384;
1.984     raeburn  10421:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10422:         $currsubfile{$path} = {};
1.1123    raeburn  10423:         if (($actionurl eq '/adm/portfolio') || 
                   10424:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10425:             my ($sublistref,$listerror) =
                   10426:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10427:             if (ref($sublistref) eq 'ARRAY') {
                   10428:                 foreach my $line (@{$sublistref}) {
                   10429:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10430:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10431:                 }
1.984     raeburn  10432:             }
1.987     raeburn  10433:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10434:             if (opendir(my $dir,$url.'/'.$path)) {
                   10435:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10436:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10437:             }
1.1084    raeburn  10438:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10439:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10440:                   ($args->{'context'} eq 'paste')) ||
                   10441:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10442:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10443:                 my $dir;
                   10444:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10445:                     $dir = $fileloc;
                   10446:                 } else {
                   10447:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10448:                 }
1.1071    raeburn  10449:                 if ($dir ne '') {
                   10450:                     my ($sublistref,$listerror) =
                   10451:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10452:                     if (ref($sublistref) eq 'ARRAY') {
                   10453:                         foreach my $line (@{$sublistref}) {
                   10454:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10455:                                 undef,$mtime)=split(/\&/,$line,12);
                   10456:                             unless (($testdir&$dirptr) ||
                   10457:                                     ($file_name =~ /^\.\.?$/)) {
                   10458:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10459:                             }
                   10460:                         }
                   10461:                     }
                   10462:                 }
1.984     raeburn  10463:             }
                   10464:         }
                   10465:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10466:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10467:                 my $item = $path.'/'.$file;
                   10468:                 unless ($mapping{$item} eq $item) {
                   10469:                     $pathchanges{$item} = 1;
                   10470:                 }
                   10471:                 $existing{$item} = 1;
                   10472:                 $numexisting ++;
                   10473:             } else {
                   10474:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10475:             }
                   10476:         }
1.1071    raeburn  10477:         if ($actionurl eq '/adm/dependencies') {
                   10478:             foreach my $path (keys(%currsubfile)) {
                   10479:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10480:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10481:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10482:                              next if (($rem ne '') &&
                   10483:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10484:                                        (ref($navmap) &&
                   10485:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10486:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10487:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10488:                              $unused{$path.'/'.$file} = 1; 
                   10489:                          }
                   10490:                     }
                   10491:                 }
                   10492:             }
                   10493:         }
1.984     raeburn  10494:     }
1.987     raeburn  10495:     my %currfile;
1.1123    raeburn  10496:     if (($actionurl eq '/adm/portfolio') ||
                   10497:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10498:         my ($dirlistref,$listerror) =
                   10499:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10500:         if (ref($dirlistref) eq 'ARRAY') {
                   10501:             foreach my $line (@{$dirlistref}) {
                   10502:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10503:                 $currfile{$file_name} = 1;
                   10504:             }
1.984     raeburn  10505:         }
1.987     raeburn  10506:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10507:         if (opendir(my $dir,$url)) {
1.987     raeburn  10508:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10509:             map {$currfile{$_} = 1;} @dir_list;
                   10510:         }
1.1084    raeburn  10511:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10512:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10513:               ($args->{'context'} eq 'paste')) ||
                   10514:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10515:         if ($env{'request.course.id'} ne '') {
                   10516:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10517:             if ($dir ne '') {
                   10518:                 my ($dirlistref,$listerror) =
                   10519:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10520:                 if (ref($dirlistref) eq 'ARRAY') {
                   10521:                     foreach my $line (@{$dirlistref}) {
                   10522:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10523:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10524:                         unless (($testdir&$dirptr) ||
                   10525:                                 ($file_name =~ /^\.\.?$/)) {
                   10526:                             $currfile{$file_name} = [$size,$mtime];
                   10527:                         }
                   10528:                     }
                   10529:                 }
                   10530:             }
                   10531:         }
1.984     raeburn  10532:     }
                   10533:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10534:         if (exists($currfile{$file})) {
1.987     raeburn  10535:             unless ($mapping{$file} eq $file) {
                   10536:                 $pathchanges{$file} = 1;
                   10537:             }
                   10538:             $existing{$file} = 1;
                   10539:             $numexisting ++;
                   10540:         } else {
1.984     raeburn  10541:             $newfiles{$file} = 1;
                   10542:         }
                   10543:     }
1.1071    raeburn  10544:     foreach my $file (keys(%currfile)) {
                   10545:         unless (($file eq $filename) ||
                   10546:                 ($file eq $filename.'.bak') ||
                   10547:                 ($dependencies{$file})) {
1.1085    raeburn  10548:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10549:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10550:                     next if (($rem ne '') &&
                   10551:                              (($env{"httpref.$rem".$file} ne '') ||
                   10552:                               (ref($navmap) &&
                   10553:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10554:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10555:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10556:                 }
1.1085    raeburn  10557:             }
1.1071    raeburn  10558:             $unused{$file} = 1;
                   10559:         }
                   10560:     }
1.1084    raeburn  10561:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10562:         ($args->{'context'} eq 'paste')) {
                   10563:         $counter = scalar(keys(%existing));
                   10564:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10565:         return ($output,$counter,$numpathchg,\%existing);
                   10566:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10567:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10568:         $counter = scalar(keys(%existing));
                   10569:         $numpathchg = scalar(keys(%pathchanges));
                   10570:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10571:     }
1.984     raeburn  10572:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10573:         if ($actionurl eq '/adm/dependencies') {
                   10574:             next if ($embed_file =~ m{^\w+://});
                   10575:         }
1.660     raeburn  10576:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10577:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10578:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10579:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10580:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10581:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10582:         }
1.1123    raeburn  10583:         $upload_output .= '</td>';
1.1071    raeburn  10584:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10585:             $upload_output.='<td align="right">'.
                   10586:                             '<span class="LC_info LC_fontsize_medium">'.
                   10587:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10588:             $numremref++;
1.660     raeburn  10589:         } elsif ($args->{'error_on_invalid_names'}
                   10590:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10591:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10592:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10593:             $numinvalid++;
1.660     raeburn  10594:         } else {
1.1123    raeburn  10595:             $upload_output .= '<td>'.
                   10596:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10597:                                                      $embed_file,\%mapping,
1.1071    raeburn  10598:                                                      $allfiles,$codebase,'upload');
                   10599:             $counter ++;
                   10600:             $numnew ++;
1.987     raeburn  10601:         }
                   10602:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10603:     }
                   10604:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10605:         if ($actionurl eq '/adm/dependencies') {
                   10606:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10607:             $modify_output .= &start_data_table_row().
                   10608:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10609:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10610:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10611:                               '<td>'.$size.'</td>'.
                   10612:                               '<td>'.$mtime.'</td>'.
                   10613:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10614:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10615:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10616:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10617:                               &embedded_file_element('upload_embedded',$counter,
                   10618:                                                      $embed_file,\%mapping,
                   10619:                                                      $allfiles,$codebase,'modify').
                   10620:                               '</div></td>'.
                   10621:                               &end_data_table_row()."\n";
                   10622:             $counter ++;
                   10623:         } else {
                   10624:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10625:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10626:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10627:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10628:                               &Apache::loncommon::end_data_table_row()."\n";
                   10629:         }
                   10630:     }
                   10631:     my $delidx = $counter;
                   10632:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10633:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10634:         $delete_output .= &start_data_table_row().
                   10635:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10636:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10637:                           '<td>'.$size.'</td>'.
                   10638:                           '<td>'.$mtime.'</td>'.
                   10639:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10640:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10641:                           &embedded_file_element('upload_embedded',$delidx,
                   10642:                                                  $oldfile,\%mapping,$allfiles,
                   10643:                                                  $codebase,'delete').'</td>'.
                   10644:                           &end_data_table_row()."\n"; 
                   10645:         $numunused ++;
                   10646:         $delidx ++;
1.987     raeburn  10647:     }
                   10648:     if ($upload_output) {
                   10649:         $upload_output = &start_data_table().
                   10650:                          $upload_output.
                   10651:                          &end_data_table()."\n";
                   10652:     }
1.1071    raeburn  10653:     if ($modify_output) {
                   10654:         $modify_output = &start_data_table().
                   10655:                          &start_data_table_header_row().
                   10656:                          '<th>'.&mt('File').'</th>'.
                   10657:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10658:                          '<th>'.&mt('Modified').'</th>'.
                   10659:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10660:                          &end_data_table_header_row().
                   10661:                          $modify_output.
                   10662:                          &end_data_table()."\n";
                   10663:     }
                   10664:     if ($delete_output) {
                   10665:         $delete_output = &start_data_table().
                   10666:                          &start_data_table_header_row().
                   10667:                          '<th>'.&mt('File').'</th>'.
                   10668:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10669:                          '<th>'.&mt('Modified').'</th>'.
                   10670:                          '<th>'.&mt('Delete?').'</th>'.
                   10671:                          &end_data_table_header_row().
                   10672:                          $delete_output.
                   10673:                          &end_data_table()."\n";
                   10674:     }
1.987     raeburn  10675:     my $applies = 0;
                   10676:     if ($numremref) {
                   10677:         $applies ++;
                   10678:     }
                   10679:     if ($numinvalid) {
                   10680:         $applies ++;
                   10681:     }
                   10682:     if ($numexisting) {
                   10683:         $applies ++;
                   10684:     }
1.1071    raeburn  10685:     if ($counter || $numunused) {
1.987     raeburn  10686:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10687:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10688:                   $state.'<h3>'.$heading.'</h3>'; 
                   10689:         if ($actionurl eq '/adm/dependencies') {
                   10690:             if ($numnew) {
                   10691:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10692:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10693:                            $upload_output.'<br />'."\n";
                   10694:             }
                   10695:             if ($numexisting) {
                   10696:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10697:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10698:                            $modify_output.'<br />'."\n";
                   10699:                            $buttontext = &mt('Save changes');
                   10700:             }
                   10701:             if ($numunused) {
                   10702:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10703:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10704:                            $delete_output.'<br />'."\n";
                   10705:                            $buttontext = &mt('Save changes');
                   10706:             }
                   10707:         } else {
                   10708:             $output .= $upload_output.'<br />'."\n";
                   10709:         }
                   10710:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10711:                    $counter.'" />'."\n";
                   10712:         if ($actionurl eq '/adm/dependencies') { 
                   10713:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10714:                        $numnew.'" />'."\n";
                   10715:         } elsif ($actionurl eq '') {
1.987     raeburn  10716:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10717:         }
                   10718:     } elsif ($applies) {
                   10719:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10720:         if ($applies > 1) {
                   10721:             $output .=  
1.1123    raeburn  10722:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10723:             if ($numremref) {
                   10724:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10725:             }
                   10726:             if ($numinvalid) {
                   10727:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10728:             }
                   10729:             if ($numexisting) {
                   10730:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10731:             }
                   10732:             $output .= '</ul><br />';
                   10733:         } elsif ($numremref) {
                   10734:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10735:         } elsif ($numinvalid) {
                   10736:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10737:         } elsif ($numexisting) {
                   10738:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10739:         }
                   10740:         $output .= $upload_output.'<br />';
                   10741:     }
                   10742:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10743:     $chgcount = $counter;
1.987     raeburn  10744:     if (keys(%pathchanges) > 0) {
                   10745:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10746:             if ($counter) {
1.987     raeburn  10747:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10748:                                                   $embed_file,\%mapping,
1.1071    raeburn  10749:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10750:             } else {
                   10751:                 $pathchange_output .= 
                   10752:                     &start_data_table_row().
                   10753:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10754:                     $chgcount.'" checked="checked" /></td>'.
                   10755:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10756:                     '<td>'.$embed_file.
                   10757:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10758:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10759:                     '</td>'.&end_data_table_row();
1.660     raeburn  10760:             }
1.987     raeburn  10761:             $numpathchg ++;
                   10762:             $chgcount ++;
1.660     raeburn  10763:         }
                   10764:     }
1.1127    raeburn  10765:     if (($counter) || ($numunused)) {
1.987     raeburn  10766:         if ($numpathchg) {
                   10767:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10768:                        $numpathchg.'" />'."\n";
                   10769:         }
                   10770:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10771:             ($actionurl eq '/adm/imsimport')) {
                   10772:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10773:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10774:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10775:         } elsif ($actionurl eq '/adm/dependencies') {
                   10776:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10777:         }
1.1123    raeburn  10778:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10779:     } elsif ($numpathchg) {
                   10780:         my %pathchange = ();
                   10781:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10782:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10783:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  10784:         }
1.987     raeburn  10785:     }
1.1071    raeburn  10786:     return ($output,$counter,$numpathchg);
1.987     raeburn  10787: }
                   10788: 
1.1147    raeburn  10789: =pod
                   10790: 
                   10791: =item * clean_path($name)
                   10792: 
                   10793: Performs clean-up of directories, subdirectories and filename in an
                   10794: embedded object, referenced in an HTML file which is being uploaded
                   10795: to a course or portfolio, where 
                   10796: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10797: checked.
                   10798: 
                   10799: Clean-up is similar to replacements in lonnet::clean_filename()
                   10800: except each / between sub-directory and next level is preserved.
                   10801: 
                   10802: =cut
                   10803: 
                   10804: sub clean_path {
                   10805:     my ($embed_file) = @_;
                   10806:     $embed_file =~s{^/+}{};
                   10807:     my @contents;
                   10808:     if ($embed_file =~ m{/}) {
                   10809:         @contents = split(/\//,$embed_file);
                   10810:     } else {
                   10811:         @contents = ($embed_file);
                   10812:     }
                   10813:     my $lastidx = scalar(@contents)-1;
                   10814:     for (my $i=0; $i<=$lastidx; $i++) { 
                   10815:         $contents[$i]=~s{\\}{/}g;
                   10816:         $contents[$i]=~s/\s+/\_/g;
                   10817:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10818:         if ($i == $lastidx) {
                   10819:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10820:         }
                   10821:     }
                   10822:     if ($lastidx > 0) {
                   10823:         return join('/',@contents);
                   10824:     } else {
                   10825:         return $contents[0];
                   10826:     }
                   10827: }
                   10828: 
1.987     raeburn  10829: sub embedded_file_element {
1.1071    raeburn  10830:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10831:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10832:                    (ref($codebase) eq 'HASH'));
                   10833:     my $output;
1.1071    raeburn  10834:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10835:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10836:     }
                   10837:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10838:                &escape($embed_file).'" />';
                   10839:     unless (($context eq 'upload_embedded') && 
                   10840:             ($mapping->{$embed_file} eq $embed_file)) {
                   10841:         $output .='
                   10842:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10843:     }
                   10844:     my $attrib;
                   10845:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10846:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10847:     }
                   10848:     $output .=
                   10849:         "\n\t\t".
                   10850:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10851:         $attrib.'" />';
                   10852:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10853:         $output .=
                   10854:             "\n\t\t".
                   10855:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10856:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10857:     }
1.987     raeburn  10858:     return $output;
1.660     raeburn  10859: }
                   10860: 
1.1071    raeburn  10861: sub get_dependency_details {
                   10862:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10863:     my ($size,$mtime,$showsize,$showmtime);
                   10864:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10865:         if ($embed_file =~ m{/}) {
                   10866:             my ($path,$fname) = split(/\//,$embed_file);
                   10867:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10868:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10869:             }
                   10870:         } else {
                   10871:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10872:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10873:             }
                   10874:         }
                   10875:         $showsize = $size/1024.0;
                   10876:         $showsize = sprintf("%.1f",$showsize);
                   10877:         if ($mtime > 0) {
                   10878:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10879:         }
                   10880:     }
                   10881:     return ($showsize,$showmtime);
                   10882: }
                   10883: 
                   10884: sub ask_embedded_js {
                   10885:     return <<"END";
                   10886: <script type="text/javascript"">
                   10887: // <![CDATA[
                   10888: function toggleBrowse(counter) {
                   10889:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10890:     var fileid = document.getElementById('embedded_item_'+counter);
                   10891:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10892:     if (chkboxid.checked == true) {
                   10893:         uploaddivid.style.display='block';
                   10894:     } else {
                   10895:         uploaddivid.style.display='none';
                   10896:         fileid.value = '';
                   10897:     }
                   10898: }
                   10899: // ]]>
                   10900: </script>
                   10901: 
                   10902: END
                   10903: }
                   10904: 
1.661     raeburn  10905: sub upload_embedded {
                   10906:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10907:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10908:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10909:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10910:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10911:         my $orig_uploaded_filename =
                   10912:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10913:         foreach my $type ('orig','ref','attrib','codebase') {
                   10914:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10915:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10916:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10917:             }
                   10918:         }
1.661     raeburn  10919:         my ($path,$fname) =
                   10920:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10921:         # no path, whole string is fname
                   10922:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10923:         $fname = &Apache::lonnet::clean_filename($fname);
                   10924:         # See if there is anything left
                   10925:         next if ($fname eq '');
                   10926: 
                   10927:         # Check if file already exists as a file or directory.
                   10928:         my ($state,$msg);
                   10929:         if ($context eq 'portfolio') {
                   10930:             my $port_path = $dirpath;
                   10931:             if ($group ne '') {
                   10932:                 $port_path = "groups/$group/$port_path";
                   10933:             }
1.987     raeburn  10934:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10935:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10936:                                               $dir_root,$port_path,$disk_quota,
                   10937:                                               $current_disk_usage,$uname,$udom);
                   10938:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10939:                 || $state eq 'file_locked') {
1.661     raeburn  10940:                 $output .= $msg;
                   10941:                 next;
                   10942:             }
                   10943:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10944:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10945:             if ($state eq 'exists') {
                   10946:                 $output .= $msg;
                   10947:                 next;
                   10948:             }
                   10949:         }
                   10950:         # Check if extension is valid
                   10951:         if (($fname =~ /\.(\w+)$/) &&
                   10952:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   10953:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10954:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10955:             next;
                   10956:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10957:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10958:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10959:             next;
                   10960:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10961:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10962:             next;
                   10963:         }
                   10964:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  10965:         my $subdir = $path;
                   10966:         $subdir =~ s{/+$}{};
1.661     raeburn  10967:         if ($context eq 'portfolio') {
1.984     raeburn  10968:             my $result;
                   10969:             if ($state eq 'existingfile') {
                   10970:                 $result=
                   10971:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  10972:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10973:             } else {
1.984     raeburn  10974:                 $result=
                   10975:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10976:                                                     $dirpath.
1.1123    raeburn  10977:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10978:                 if ($result !~ m|^/uploaded/|) {
                   10979:                     $output .= '<span class="LC_error">'
                   10980:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10981:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10982:                                .'</span><br />';
                   10983:                     next;
                   10984:                 } else {
1.987     raeburn  10985:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10986:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10987:                 }
1.661     raeburn  10988:             }
1.1123    raeburn  10989:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  10990:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10991:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10992:             my $result =
1.1126    raeburn  10993:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10994:             if ($result !~ m|^/uploaded/|) {
                   10995:                 $output .= '<span class="LC_error">'
                   10996:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10997:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10998:                            .'</span><br />';
                   10999:                     next;
                   11000:             } else {
                   11001:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11002:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11003:                 if ($context eq 'syllabus') {
                   11004:                     &Apache::lonnet::make_public_indefinitely($result);
                   11005:                 }
1.987     raeburn  11006:             }
1.661     raeburn  11007:         } else {
                   11008: # Save the file
                   11009:             my $target = $env{'form.embedded_item_'.$i};
                   11010:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11011:             my $dest = $fullpath.$fname;
                   11012:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11013:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11014:             my $count;
                   11015:             my $filepath = $dir_root;
1.1027    raeburn  11016:             foreach my $subdir (@parts) {
                   11017:                 $filepath .= "/$subdir";
                   11018:                 if (!-e $filepath) {
1.661     raeburn  11019:                     mkdir($filepath,0770);
                   11020:                 }
                   11021:             }
                   11022:             my $fh;
                   11023:             if (!open($fh,'>'.$dest)) {
                   11024:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11025:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11026:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11027:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11028:                            '</span><br />';
                   11029:             } else {
                   11030:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11031:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11032:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11033:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11034:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11035:                               '</span><br />';
                   11036:                 } else {
1.987     raeburn  11037:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11038:                                $url.'</span>').'<br />';
                   11039:                     unless ($context eq 'testbank') {
                   11040:                         $footer .= &mt('View embedded file: [_1]',
                   11041:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11042:                     }
                   11043:                 }
                   11044:                 close($fh);
                   11045:             }
                   11046:         }
                   11047:         if ($env{'form.embedded_ref_'.$i}) {
                   11048:             $pathchange{$i} = 1;
                   11049:         }
                   11050:     }
                   11051:     if ($output) {
                   11052:         $output = '<p>'.$output.'</p>';
                   11053:     }
                   11054:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11055:     $returnflag = 'ok';
1.1071    raeburn  11056:     my $numpathchgs = scalar(keys(%pathchange));
                   11057:     if ($numpathchgs > 0) {
1.987     raeburn  11058:         if ($context eq 'portfolio') {
                   11059:             $output .= '<p>'.&mt('or').'</p>';
                   11060:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11061:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11062:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11063:             $returnflag = 'modify_orightml';
                   11064:         }
                   11065:     }
1.1071    raeburn  11066:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11067: }
                   11068: 
                   11069: sub modify_html_form {
                   11070:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11071:     my $end = 0;
                   11072:     my $modifyform;
                   11073:     if ($context eq 'upload_embedded') {
                   11074:         return unless (ref($pathchange) eq 'HASH');
                   11075:         if ($env{'form.number_embedded_items'}) {
                   11076:             $end += $env{'form.number_embedded_items'};
                   11077:         }
                   11078:         if ($env{'form.number_pathchange_items'}) {
                   11079:             $end += $env{'form.number_pathchange_items'};
                   11080:         }
                   11081:         if ($end) {
                   11082:             for (my $i=0; $i<$end; $i++) {
                   11083:                 if ($i < $env{'form.number_embedded_items'}) {
                   11084:                     next unless($pathchange->{$i});
                   11085:                 }
                   11086:                 $modifyform .=
                   11087:                     &start_data_table_row().
                   11088:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11089:                     'checked="checked" /></td>'.
                   11090:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11091:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11092:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11093:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11094:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11095:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11096:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11097:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11098:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11099:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11100:                     &end_data_table_row();
1.1071    raeburn  11101:             }
1.987     raeburn  11102:         }
                   11103:     } else {
                   11104:         $modifyform = $pathchgtable;
                   11105:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11106:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11107:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11108:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11109:         }
                   11110:     }
                   11111:     if ($modifyform) {
1.1071    raeburn  11112:         if ($actionurl eq '/adm/dependencies') {
                   11113:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11114:         }
1.987     raeburn  11115:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11116:                '<p>'.&mt('Changes need to be made to the reference(s) used for one or more of the dependencies, if your HTML file is to work correctly:').'<ol>'."\n".
                   11117:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11118:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11119:                '</ol></p>'."\n".'<p>'.
                   11120:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11121:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11122:                &start_data_table()."\n".
                   11123:                &start_data_table_header_row().
                   11124:                '<th>'.&mt('Change?').'</th>'.
                   11125:                '<th>'.&mt('Current reference').'</th>'.
                   11126:                '<th>'.&mt('Required reference').'</th>'.
                   11127:                &end_data_table_header_row()."\n".
                   11128:                $modifyform.
                   11129:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11130:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11131:                '</form>'."\n";
                   11132:     }
                   11133:     return;
                   11134: }
                   11135: 
                   11136: sub modify_html_refs {
1.1123    raeburn  11137:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11138:     my $container;
                   11139:     if ($context eq 'portfolio') {
                   11140:         $container = $env{'form.container'};
                   11141:     } elsif ($context eq 'coursedoc') {
                   11142:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11143:     } elsif ($context eq 'manage_dependencies') {
                   11144:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11145:         $container = "/$container";
1.1123    raeburn  11146:     } elsif ($context eq 'syllabus') {
                   11147:         $container = $url;
1.987     raeburn  11148:     } else {
1.1027    raeburn  11149:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11150:     }
                   11151:     my (%allfiles,%codebase,$output,$content);
                   11152:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11153:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11154:         if (wantarray) {
                   11155:             return ('',0,0); 
                   11156:         } else {
                   11157:             return;
                   11158:         }
                   11159:     }
                   11160:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11161:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11162:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11163:             if (wantarray) {
                   11164:                 return ('',0,0);
                   11165:             } else {
                   11166:                 return;
                   11167:             }
                   11168:         } 
1.987     raeburn  11169:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11170:         if ($content eq '-1') {
                   11171:             if (wantarray) {
                   11172:                 return ('',0,0);
                   11173:             } else {
                   11174:                 return;
                   11175:             }
                   11176:         }
1.987     raeburn  11177:     } else {
1.1071    raeburn  11178:         unless ($container =~ /^\Q$dir_root\E/) {
                   11179:             if (wantarray) {
                   11180:                 return ('',0,0);
                   11181:             } else {
                   11182:                 return;
                   11183:             }
                   11184:         } 
1.987     raeburn  11185:         if (open(my $fh,"<$container")) {
                   11186:             $content = join('', <$fh>);
                   11187:             close($fh);
                   11188:         } else {
1.1071    raeburn  11189:             if (wantarray) {
                   11190:                 return ('',0,0);
                   11191:             } else {
                   11192:                 return;
                   11193:             }
1.987     raeburn  11194:         }
                   11195:     }
                   11196:     my ($count,$codebasecount) = (0,0);
                   11197:     my $mm = new File::MMagic;
                   11198:     my $mime_type = $mm->checktype_contents($content);
                   11199:     if ($mime_type eq 'text/html') {
                   11200:         my $parse_result = 
                   11201:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11202:                                                     \%codebase,\$content);
                   11203:         if ($parse_result eq 'ok') {
                   11204:             foreach my $i (@changes) {
                   11205:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11206:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11207:                 if ($allfiles{$ref}) {
                   11208:                     my $newname =  $orig;
                   11209:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11210:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11211:                     if ($attrib_regexp =~ /:/) {
                   11212:                         $attrib_regexp =~ s/\:/|/g;
                   11213:                     }
                   11214:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11215:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11216:                         $count += $numchg;
1.1123    raeburn  11217:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11218:                         delete($allfiles{$ref});
1.987     raeburn  11219:                     }
                   11220:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11221:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11222:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11223:                         $codebasecount ++;
                   11224:                     }
                   11225:                 }
                   11226:             }
1.1123    raeburn  11227:             my $skiprewrites;
1.987     raeburn  11228:             if ($count || $codebasecount) {
                   11229:                 my $saveresult;
1.1071    raeburn  11230:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11231:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11232:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11233:                     if ($url eq $container) {
                   11234:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11235:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11236:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11237:                                             $fname.'</span>').'</p>';
1.987     raeburn  11238:                     } else {
                   11239:                          $output = '<p class="LC_error">'.
                   11240:                                    &mt('Error: update failed for: [_1].',
                   11241:                                    '<span class="LC_filename">'.
                   11242:                                    $container.'</span>').'</p>';
                   11243:                     }
1.1123    raeburn  11244:                     if ($context eq 'syllabus') {
                   11245:                         unless ($saveresult eq 'ok') {
                   11246:                             $skiprewrites = 1;
                   11247:                         }
                   11248:                     }
1.987     raeburn  11249:                 } else {
                   11250:                     if (open(my $fh,">$container")) {
                   11251:                         print $fh $content;
                   11252:                         close($fh);
                   11253:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11254:                                   $count,'<span class="LC_filename">'.
                   11255:                                   $container.'</span>').'</p>';
1.661     raeburn  11256:                     } else {
1.987     raeburn  11257:                          $output = '<p class="LC_error">'.
                   11258:                                    &mt('Error: could not update [_1].',
                   11259:                                    '<span class="LC_filename">'.
                   11260:                                    $container.'</span>').'</p>';
1.661     raeburn  11261:                     }
                   11262:                 }
                   11263:             }
1.1123    raeburn  11264:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11265:                 my ($actionurl,$state);
                   11266:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11267:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11268:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11269:                                               \%codebase,
                   11270:                                               {'context' => 'rewrites',
                   11271:                                                'ignore_remote_references' => 1,});
                   11272:                 if (ref($mapping) eq 'HASH') {
                   11273:                     my $rewrites = 0;
                   11274:                     foreach my $key (keys(%{$mapping})) {
                   11275:                         next if ($key =~ m{^https?://});
                   11276:                         my $ref = $mapping->{$key};
                   11277:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11278:                         my $attrib;
                   11279:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11280:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11281:                         }
                   11282:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11283:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11284:                             $rewrites += $numchg;
                   11285:                         }
                   11286:                     }
                   11287:                     if ($rewrites) {
                   11288:                         my $saveresult; 
                   11289:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11290:                         if ($url eq $container) {
                   11291:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11292:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11293:                                             $count,'<span class="LC_filename">'.
                   11294:                                             $fname.'</span>').'</p>';
                   11295:                         } else {
                   11296:                             $output .= '<p class="LC_error">'.
                   11297:                                        &mt('Error: could not update links in [_1].',
                   11298:                                        '<span class="LC_filename">'.
                   11299:                                        $container.'</span>').'</p>';
                   11300: 
                   11301:                         }
                   11302:                     }
                   11303:                 }
                   11304:             }
1.987     raeburn  11305:         } else {
                   11306:             &logthis('Failed to parse '.$container.
                   11307:                      ' to modify references: '.$parse_result);
1.661     raeburn  11308:         }
                   11309:     }
1.1071    raeburn  11310:     if (wantarray) {
                   11311:         return ($output,$count,$codebasecount);
                   11312:     } else {
                   11313:         return $output;
                   11314:     }
1.661     raeburn  11315: }
                   11316: 
                   11317: sub check_for_existing {
                   11318:     my ($path,$fname,$element) = @_;
                   11319:     my ($state,$msg);
                   11320:     if (-d $path.'/'.$fname) {
                   11321:         $state = 'exists';
                   11322:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11323:     } elsif (-e $path.'/'.$fname) {
                   11324:         $state = 'exists';
                   11325:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11326:     }
                   11327:     if ($state eq 'exists') {
                   11328:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11329:     }
                   11330:     return ($state,$msg);
                   11331: }
                   11332: 
                   11333: sub check_for_upload {
                   11334:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11335:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11336:     my $filesize = length($env{'form.'.$element});
                   11337:     if (!$filesize) {
                   11338:         my $msg = '<span class="LC_error">'.
                   11339:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11340:                       '<span class="LC_filename">'.$fname.'</span>',
                   11341:                       $filesize).'<br />'.
1.1007    raeburn  11342:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11343:                   '</span>';
                   11344:         return ('zero_bytes',$msg);
                   11345:     }
                   11346:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11347:     my $getpropath = 1;
1.1021    raeburn  11348:     my ($dirlistref,$listerror) =
                   11349:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11350:     my $found_file = 0;
                   11351:     my $locked_file = 0;
1.991     raeburn  11352:     my @lockers;
                   11353:     my $navmap;
                   11354:     if ($env{'request.course.id'}) {
                   11355:         $navmap = Apache::lonnavmaps::navmap->new();
                   11356:     }
1.1021    raeburn  11357:     if (ref($dirlistref) eq 'ARRAY') {
                   11358:         foreach my $line (@{$dirlistref}) {
                   11359:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11360:             if ($file_name eq $fname){
                   11361:                 $file_name = $path.$file_name;
                   11362:                 if ($group ne '') {
                   11363:                     $file_name = $group.$file_name;
                   11364:                 }
                   11365:                 $found_file = 1;
                   11366:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11367:                     foreach my $lock (@lockers) {
                   11368:                         if (ref($lock) eq 'ARRAY') {
                   11369:                             my ($symb,$crsid) = @{$lock};
                   11370:                             if ($crsid eq $env{'request.course.id'}) {
                   11371:                                 if (ref($navmap)) {
                   11372:                                     my $res = $navmap->getBySymb($symb);
                   11373:                                     foreach my $part (@{$res->parts()}) { 
                   11374:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11375:                                         unless (($slot_status == $res->RESERVED) ||
                   11376:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11377:                                             $locked_file = 1;
                   11378:                                         }
1.991     raeburn  11379:                                     }
1.1021    raeburn  11380:                                 } else {
                   11381:                                     $locked_file = 1;
1.991     raeburn  11382:                                 }
                   11383:                             } else {
                   11384:                                 $locked_file = 1;
                   11385:                             }
                   11386:                         }
1.1021    raeburn  11387:                    }
                   11388:                 } else {
                   11389:                     my @info = split(/\&/,$rest);
                   11390:                     my $currsize = $info[6]/1000;
                   11391:                     if ($currsize < $filesize) {
                   11392:                         my $extra = $filesize - $currsize;
                   11393:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11394:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11395:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1179    bisitz   11396:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11397:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11398:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11399:                             return ('will_exceed_quota',$msg);
                   11400:                         }
1.984     raeburn  11401:                     }
                   11402:                 }
1.661     raeburn  11403:             }
                   11404:         }
                   11405:     }
                   11406:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11407:         my $msg = '<p class="LC_warning">'.
                   11408:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11409:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11410:         return ('will_exceed_quota',$msg);
                   11411:     } elsif ($found_file) {
                   11412:         if ($locked_file) {
1.1179    bisitz   11413:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11414:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1179    bisitz   11415:             $msg .= '</p>';
1.661     raeburn  11416:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11417:             return ('file_locked',$msg);
                   11418:         } else {
1.1179    bisitz   11419:             my $msg = '<p class="LC_error">';
1.984     raeburn  11420:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   11421:             $msg .= '</p>';
1.984     raeburn  11422:             return ('existingfile',$msg);
1.661     raeburn  11423:         }
                   11424:     }
                   11425: }
                   11426: 
1.987     raeburn  11427: sub check_for_traversal {
                   11428:     my ($path,$url,$toplevel) = @_;
                   11429:     my @parts=split(/\//,$path);
                   11430:     my $cleanpath;
                   11431:     my $fullpath = $url;
                   11432:     for (my $i=0;$i<@parts;$i++) {
                   11433:         next if ($parts[$i] eq '.');
                   11434:         if ($parts[$i] eq '..') {
                   11435:             $fullpath =~ s{([^/]+/)$}{};
                   11436:         } else {
                   11437:             $fullpath .= $parts[$i].'/';
                   11438:         }
                   11439:     }
                   11440:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11441:         $cleanpath = $1;
                   11442:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11443:         my $curr_toprel = $1;
                   11444:         my @parts = split(/\//,$curr_toprel);
                   11445:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11446:         my @urlparts = split(/\//,$url_toprel);
                   11447:         my $doubledots;
                   11448:         my $startdiff = -1;
                   11449:         for (my $i=0; $i<@urlparts; $i++) {
                   11450:             if ($startdiff == -1) {
                   11451:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11452:                     $startdiff = $i;
                   11453:                     $doubledots .= '../';
                   11454:                 }
                   11455:             } else {
                   11456:                 $doubledots .= '../';
                   11457:             }
                   11458:         }
                   11459:         if ($startdiff > -1) {
                   11460:             $cleanpath = $doubledots;
                   11461:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11462:                 $cleanpath .= $parts[$i].'/';
                   11463:             }
                   11464:         }
                   11465:     }
                   11466:     $cleanpath =~ s{(/)$}{};
                   11467:     return $cleanpath;
                   11468: }
1.31      albertel 11469: 
1.1053    raeburn  11470: sub is_archive_file {
                   11471:     my ($mimetype) = @_;
                   11472:     if (($mimetype eq 'application/octet-stream') ||
                   11473:         ($mimetype eq 'application/x-stuffit') ||
                   11474:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11475:         return 1;
                   11476:     }
                   11477:     return;
                   11478: }
                   11479: 
                   11480: sub decompress_form {
1.1065    raeburn  11481:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11482:     my %lt = &Apache::lonlocal::texthash (
                   11483:         this => 'This file is an archive file.',
1.1067    raeburn  11484:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11485:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11486:         youm => 'You may wish to extract its contents.',
                   11487:         extr => 'Extract contents',
1.1067    raeburn  11488:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11489:         proa => 'Process automatically?',
1.1053    raeburn  11490:         yes  => 'Yes',
                   11491:         no   => 'No',
1.1067    raeburn  11492:         fold => 'Title for folder containing movie',
                   11493:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11494:     );
1.1065    raeburn  11495:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11496:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11497:     my $info = &list_archive_contents($fileloc,\@paths);
                   11498:     if (@paths) {
                   11499:         foreach my $path (@paths) {
                   11500:             $path =~ s{^/}{};
1.1067    raeburn  11501:             if ($path =~ m{^([^/]+)/$}) {
                   11502:                 $topdir = $1;
                   11503:             }
1.1065    raeburn  11504:             if ($path =~ m{^([^/]+)/}) {
                   11505:                 $toplevel{$1} = $path;
                   11506:             } else {
                   11507:                 $toplevel{$path} = $path;
                   11508:             }
                   11509:         }
                   11510:     }
1.1067    raeburn  11511:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11512:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11513:                         "$topdir/media/",
                   11514:                         "$topdir/media/$topdir.mp4",
                   11515:                         "$topdir/media/FirstFrame.png",
                   11516:                         "$topdir/media/player.swf",
                   11517:                         "$topdir/media/swfobject.js",
                   11518:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11519:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11520:                          "$topdir/$topdir.mp4",
                   11521:                          "$topdir/$topdir\_config.xml",
                   11522:                          "$topdir/$topdir\_controller.swf",
                   11523:                          "$topdir/$topdir\_embed.css",
                   11524:                          "$topdir/$topdir\_First_Frame.png",
                   11525:                          "$topdir/$topdir\_player.html",
                   11526:                          "$topdir/$topdir\_Thumbnails.png",
                   11527:                          "$topdir/playerProductInstall.swf",
                   11528:                          "$topdir/scripts/",
                   11529:                          "$topdir/scripts/config_xml.js",
                   11530:                          "$topdir/scripts/handlebars.js",
                   11531:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11532:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11533:                          "$topdir/scripts/modernizr.js",
                   11534:                          "$topdir/scripts/player-min.js",
                   11535:                          "$topdir/scripts/swfobject.js",
                   11536:                          "$topdir/skins/",
                   11537:                          "$topdir/skins/configuration_express.xml",
                   11538:                          "$topdir/skins/express_show/",
                   11539:                          "$topdir/skins/express_show/player-min.css",
                   11540:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11541:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11542:                          "$topdir/$topdir.mp4",
                   11543:                          "$topdir/$topdir\_config.xml",
                   11544:                          "$topdir/$topdir\_controller.swf",
                   11545:                          "$topdir/$topdir\_embed.css",
                   11546:                          "$topdir/$topdir\_First_Frame.png",
                   11547:                          "$topdir/$topdir\_player.html",
                   11548:                          "$topdir/$topdir\_Thumbnails.png",
                   11549:                          "$topdir/playerProductInstall.swf",
                   11550:                          "$topdir/scripts/",
                   11551:                          "$topdir/scripts/config_xml.js",
                   11552:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11553:                          "$topdir/skins/",
                   11554:                          "$topdir/skins/configuration_express.xml",
                   11555:                          "$topdir/skins/express_show/",
                   11556:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11557:                          "$topdir/skins/express_show/spritesheet.png",
                   11558:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11559:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11560:         if (@diffs == 0) {
1.1164    raeburn  11561:             $is_camtasia = 6;
                   11562:         } else {
1.1197    raeburn  11563:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11564:             if (@diffs == 0) {
                   11565:                 $is_camtasia = 8;
1.1197    raeburn  11566:             } else {
                   11567:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11568:                 if (@diffs == 0) {
                   11569:                     $is_camtasia = 8;
                   11570:                 }
1.1164    raeburn  11571:             }
1.1067    raeburn  11572:         }
                   11573:     }
                   11574:     my $output;
                   11575:     if ($is_camtasia) {
                   11576:         $output = <<"ENDCAM";
                   11577: <script type="text/javascript" language="Javascript">
                   11578: // <![CDATA[
                   11579: 
                   11580: function camtasiaToggle() {
                   11581:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11582:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11583:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11584:                 document.getElementById('camtasia_titles').style.display='block';
                   11585:             } else {
                   11586:                 document.getElementById('camtasia_titles').style.display='none';
                   11587:             }
                   11588:         }
                   11589:     }
                   11590:     return;
                   11591: }
                   11592: 
                   11593: // ]]>
                   11594: </script>
                   11595: <p>$lt{'camt'}</p>
                   11596: ENDCAM
1.1065    raeburn  11597:     } else {
1.1067    raeburn  11598:         $output = '<p>'.$lt{'this'};
                   11599:         if ($info eq '') {
                   11600:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11601:         } else {
                   11602:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11603:                        '<div><pre>'.$info.'</pre></div>';
                   11604:         }
1.1065    raeburn  11605:     }
1.1067    raeburn  11606:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11607:     my $duplicates;
                   11608:     my $num = 0;
                   11609:     if (ref($dirlist) eq 'ARRAY') {
                   11610:         foreach my $item (@{$dirlist}) {
                   11611:             if (ref($item) eq 'ARRAY') {
                   11612:                 if (exists($toplevel{$item->[0]})) {
                   11613:                     $duplicates .= 
                   11614:                         &start_data_table_row().
                   11615:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11616:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11617:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11618:                         'value="1" />'.&mt('Yes').'</label>'.
                   11619:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11620:                         '<td>'.$item->[0].'</td>';
                   11621:                     if ($item->[2]) {
                   11622:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11623:                     } else {
                   11624:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11625:                     }
                   11626:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11627:                                    '<td>'.
                   11628:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11629:                                    '</td>'.
                   11630:                                    &end_data_table_row();
                   11631:                     $num ++;
                   11632:                 }
                   11633:             }
                   11634:         }
                   11635:     }
                   11636:     my $itemcount;
                   11637:     if (@paths > 0) {
                   11638:         $itemcount = scalar(@paths);
                   11639:     } else {
                   11640:         $itemcount = 1;
                   11641:     }
1.1067    raeburn  11642:     if ($is_camtasia) {
                   11643:         $output .= $lt{'auto'}.'<br />'.
                   11644:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11645:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11646:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11647:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11648:                    $lt{'no'}.'</label></span><br />'.
                   11649:                    '<div id="camtasia_titles" style="display:block">'.
                   11650:                    &Apache::lonhtmlcommon::start_pick_box().
                   11651:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11652:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11653:                    &Apache::lonhtmlcommon::row_closure().
                   11654:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11655:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11656:                    &Apache::lonhtmlcommon::row_closure(1).
                   11657:                    &Apache::lonhtmlcommon::end_pick_box().
                   11658:                    '</div>';
                   11659:     }
1.1065    raeburn  11660:     $output .= 
                   11661:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11662:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11663:         "\n";
1.1065    raeburn  11664:     if ($duplicates ne '') {
                   11665:         $output .= '<p><span class="LC_warning">'.
                   11666:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11667:                    &start_data_table().
                   11668:                    &start_data_table_header_row().
                   11669:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11670:                    '<th>'.&mt('Name').'</th>'.
                   11671:                    '<th>'.&mt('Type').'</th>'.
                   11672:                    '<th>'.&mt('Size').'</th>'.
                   11673:                    '<th>'.&mt('Last modified').'</th>'.
                   11674:                    &end_data_table_header_row().
                   11675:                    $duplicates.
                   11676:                    &end_data_table().
                   11677:                    '</p>';
                   11678:     }
1.1067    raeburn  11679:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11680:     if (ref($hiddenelements) eq 'HASH') {
                   11681:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11682:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11683:         }
                   11684:     }
                   11685:     $output .= <<"END";
1.1067    raeburn  11686: <br />
1.1053    raeburn  11687: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11688: </form>
                   11689: $noextract
                   11690: END
                   11691:     return $output;
                   11692: }
                   11693: 
1.1065    raeburn  11694: sub decompression_utility {
                   11695:     my ($program) = @_;
                   11696:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11697:     my $location;
                   11698:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11699:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11700:                          '/usr/sbin/') {
                   11701:             if (-x $dir.$program) {
                   11702:                 $location = $dir.$program;
                   11703:                 last;
                   11704:             }
                   11705:         }
                   11706:     }
                   11707:     return $location;
                   11708: }
                   11709: 
                   11710: sub list_archive_contents {
                   11711:     my ($file,$pathsref) = @_;
                   11712:     my (@cmd,$output);
                   11713:     my $needsregexp;
                   11714:     if ($file =~ /\.zip$/) {
                   11715:         @cmd = (&decompression_utility('unzip'),"-l");
                   11716:         $needsregexp = 1;
                   11717:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11718:              ($file =~ /\.tgz$/)) {
                   11719:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11720:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11721:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11722:     } elsif ($file =~ m|\.tar$|) {
                   11723:         @cmd = (&decompression_utility('tar'),"-tf");
                   11724:     }
                   11725:     if (@cmd) {
                   11726:         undef($!);
                   11727:         undef($@);
                   11728:         if (open(my $fh,"-|", @cmd, $file)) {
                   11729:             while (my $line = <$fh>) {
                   11730:                 $output .= $line;
                   11731:                 chomp($line);
                   11732:                 my $item;
                   11733:                 if ($needsregexp) {
                   11734:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11735:                 } else {
                   11736:                     $item = $line;
                   11737:                 }
                   11738:                 if ($item ne '') {
                   11739:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11740:                         push(@{$pathsref},$item);
                   11741:                     } 
                   11742:                 }
                   11743:             }
                   11744:             close($fh);
                   11745:         }
                   11746:     }
                   11747:     return $output;
                   11748: }
                   11749: 
1.1053    raeburn  11750: sub decompress_uploaded_file {
                   11751:     my ($file,$dir) = @_;
                   11752:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11753:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11754:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11755:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11756:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11757:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11758:     my $decompressed = $env{'cgi.decompressed'};
                   11759:     &Apache::lonnet::delenv('cgi.file');
                   11760:     &Apache::lonnet::delenv('cgi.dir');
                   11761:     &Apache::lonnet::delenv('cgi.decompressed');
                   11762:     return ($decompressed,$result);
                   11763: }
                   11764: 
1.1055    raeburn  11765: sub process_decompression {
                   11766:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11767:     my ($dir,$error,$warning,$output);
1.1180    raeburn  11768:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   11769:         $error = &mt('Filename not a supported archive file type.').
                   11770:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11771:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11772:     } else {
                   11773:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11774:         if ($docuhome eq 'no_host') {
                   11775:             $error = &mt('Could not determine home server for course.');
                   11776:         } else {
                   11777:             my @ids=&Apache::lonnet::current_machine_ids();
                   11778:             my $currdir = "$dir_root/$destination";
                   11779:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11780:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11781:                        "$dir_root/$destination";
                   11782:             } else {
                   11783:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11784:                        "$dir_root/$docudom/$docuname/$destination";
                   11785:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11786:                     $error = &mt('Archive file not found.');
                   11787:                 }
                   11788:             }
1.1065    raeburn  11789:             my (@to_overwrite,@to_skip);
                   11790:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11791:                 my $total = $env{'form.archive_overwrite_total'};
                   11792:                 for (my $i=0; $i<$total; $i++) {
                   11793:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11794:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11795:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11796:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11797:                     }
                   11798:                 }
                   11799:             }
                   11800:             my $numskip = scalar(@to_skip);
                   11801:             if (($numskip > 0) && 
                   11802:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11803:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11804:             } elsif ($dir eq '') {
1.1055    raeburn  11805:                 $error = &mt('Directory containing archive file unavailable.');
                   11806:             } elsif (!$error) {
1.1065    raeburn  11807:                 my ($decompressed,$display);
                   11808:                 if ($numskip > 0) {
                   11809:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11810:                     mkdir("$dir/$tempdir",0755);
                   11811:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11812:                     ($decompressed,$display) = 
                   11813:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11814:                     foreach my $item (@to_skip) {
                   11815:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11816:                             if (-f "$dir/$tempdir/$item") { 
                   11817:                                 unlink("$dir/$tempdir/$item");
                   11818:                             } elsif (-d "$dir/$tempdir/$item") {
                   11819:                                 system("rm -rf $dir/$tempdir/$item");
                   11820:                             }
                   11821:                         }
                   11822:                     }
                   11823:                     system("mv $dir/$tempdir/* $dir");
                   11824:                     rmdir("$dir/$tempdir");   
                   11825:                 } else {
                   11826:                     ($decompressed,$display) = 
                   11827:                         &decompress_uploaded_file($file,$dir);
                   11828:                 }
1.1055    raeburn  11829:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11830:                     $output = '<p class="LC_info">'.
                   11831:                               &mt('Files extracted successfully from archive.').
                   11832:                               '</p>'."\n";
1.1055    raeburn  11833:                     my ($warning,$result,@contents);
                   11834:                     my ($newdirlistref,$newlisterror) =
                   11835:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11836:                                                  $docuname,1);
                   11837:                     my (%is_dir,%changes,@newitems);
                   11838:                     my $dirptr = 16384;
1.1065    raeburn  11839:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11840:                         foreach my $dir_line (@{$newdirlistref}) {
                   11841:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11842:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11843:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11844:                                 push(@newitems,$item);
                   11845:                                 if ($dirptr&$testdir) {
                   11846:                                     $is_dir{$item} = 1;
                   11847:                                 }
                   11848:                                 $changes{$item} = 1;
                   11849:                             }
                   11850:                         }
                   11851:                     }
                   11852:                     if (keys(%changes) > 0) {
                   11853:                         foreach my $item (sort(@newitems)) {
                   11854:                             if ($changes{$item}) {
                   11855:                                 push(@contents,$item);
                   11856:                             }
                   11857:                         }
                   11858:                     }
                   11859:                     if (@contents > 0) {
1.1067    raeburn  11860:                         my $wantform;
                   11861:                         unless ($env{'form.autoextract_camtasia'}) {
                   11862:                             $wantform = 1;
                   11863:                         }
1.1056    raeburn  11864:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11865:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11866:                                                                 $currdir,\%is_dir,
                   11867:                                                                 \%children,\%parent,
1.1056    raeburn  11868:                                                                 \@contents,\%dirorder,
                   11869:                                                                 \%titles,$wantform);
1.1055    raeburn  11870:                         if ($datatable ne '') {
                   11871:                             $output .= &archive_options_form('decompressed',$datatable,
                   11872:                                                              $count,$hiddenelem);
1.1065    raeburn  11873:                             my $startcount = 6;
1.1055    raeburn  11874:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11875:                                                            \%titles,\%children);
1.1055    raeburn  11876:                         }
1.1067    raeburn  11877:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  11878:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11879:                             my %displayed;
                   11880:                             my $total = 1;
                   11881:                             $env{'form.archive_directory'} = [];
                   11882:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11883:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11884:                                 $path =~ s{/$}{};
                   11885:                                 my $item;
                   11886:                                 if ($path ne '') {
                   11887:                                     $item = "$path/$titles{$i}";
                   11888:                                 } else {
                   11889:                                     $item = $titles{$i};
                   11890:                                 }
                   11891:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11892:                                 if ($item eq $contents[0]) {
                   11893:                                     push(@{$env{'form.archive_directory'}},$i);
                   11894:                                     $env{'form.archive_'.$i} = 'display';
                   11895:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11896:                                     $displayed{'folder'} = $i;
1.1164    raeburn  11897:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11898:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  11899:                                     $env{'form.archive_'.$i} = 'display';
                   11900:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11901:                                     $displayed{'web'} = $i;
                   11902:                                 } else {
1.1164    raeburn  11903:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11904:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11905:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11906:                                         push(@{$env{'form.archive_directory'}},$i);
                   11907:                                     }
                   11908:                                     $env{'form.archive_'.$i} = 'dependency';
                   11909:                                 }
                   11910:                                 $total ++;
                   11911:                             }
                   11912:                             for (my $i=1; $i<$total; $i++) {
                   11913:                                 next if ($i == $displayed{'web'});
                   11914:                                 next if ($i == $displayed{'folder'});
                   11915:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11916:                             }
                   11917:                             $env{'form.phase'} = 'decompress_cleanup';
                   11918:                             $env{'form.archivedelete'} = 1;
                   11919:                             $env{'form.archive_count'} = $total-1;
                   11920:                             $output .=
                   11921:                                 &process_extracted_files('coursedocs',$docudom,
                   11922:                                                          $docuname,$destination,
                   11923:                                                          $dir_root,$hiddenelem);
                   11924:                         }
1.1055    raeburn  11925:                     } else {
                   11926:                         $warning = &mt('No new items extracted from archive file.');
                   11927:                     }
                   11928:                 } else {
                   11929:                     $output = $display;
                   11930:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11931:                 }
                   11932:             }
                   11933:         }
                   11934:     }
                   11935:     if ($error) {
                   11936:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11937:                    $error.'</p>'."\n";
                   11938:     }
                   11939:     if ($warning) {
                   11940:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11941:     }
                   11942:     return $output;
                   11943: }
                   11944: 
                   11945: sub get_extracted {
1.1056    raeburn  11946:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11947:         $titles,$wantform) = @_;
1.1055    raeburn  11948:     my $count = 0;
                   11949:     my $depth = 0;
                   11950:     my $datatable;
1.1056    raeburn  11951:     my @hierarchy;
1.1055    raeburn  11952:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11953:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11954:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11955:     foreach my $item (@{$contents}) {
                   11956:         $count ++;
1.1056    raeburn  11957:         @{$dirorder->{$count}} = @hierarchy;
                   11958:         $titles->{$count} = $item;
1.1055    raeburn  11959:         &archive_hierarchy($depth,$count,$parent,$children);
                   11960:         if ($wantform) {
                   11961:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11962:                                        $currdir,$depth,$count);
                   11963:         }
                   11964:         if ($is_dir->{$item}) {
                   11965:             $depth ++;
1.1056    raeburn  11966:             push(@hierarchy,$count);
                   11967:             $parent->{$depth} = $count;
1.1055    raeburn  11968:             $datatable .=
                   11969:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11970:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11971:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11972:             $depth --;
1.1056    raeburn  11973:             pop(@hierarchy);
1.1055    raeburn  11974:         }
                   11975:     }
                   11976:     return ($count,$datatable);
                   11977: }
                   11978: 
                   11979: sub recurse_extracted_archive {
1.1056    raeburn  11980:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11981:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11982:     my $result='';
1.1056    raeburn  11983:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11984:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11985:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11986:         return $result;
                   11987:     }
                   11988:     my $dirptr = 16384;
                   11989:     my ($newdirlistref,$newlisterror) =
                   11990:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11991:     if (ref($newdirlistref) eq 'ARRAY') {
                   11992:         foreach my $dir_line (@{$newdirlistref}) {
                   11993:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11994:             unless ($item =~ /^\.+$/) {
                   11995:                 $$count ++;
1.1056    raeburn  11996:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11997:                 $titles->{$$count} = $item;
1.1055    raeburn  11998:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11999: 
1.1055    raeburn  12000:                 my $is_dir;
                   12001:                 if ($dirptr&$testdir) {
                   12002:                     $is_dir = 1;
                   12003:                 }
                   12004:                 if ($wantform) {
                   12005:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12006:                 }
                   12007:                 if ($is_dir) {
                   12008:                     $$depth ++;
1.1056    raeburn  12009:                     push(@{$hierarchy},$$count);
                   12010:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12011:                     $result .=
                   12012:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12013:                                                    $docuname,$depth,$count,
1.1056    raeburn  12014:                                                    $hierarchy,$dirorder,$children,
                   12015:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12016:                     $$depth --;
1.1056    raeburn  12017:                     pop(@{$hierarchy});
1.1055    raeburn  12018:                 }
                   12019:             }
                   12020:         }
                   12021:     }
                   12022:     return $result;
                   12023: }
                   12024: 
                   12025: sub archive_hierarchy {
                   12026:     my ($depth,$count,$parent,$children) =@_;
                   12027:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12028:         if (exists($parent->{$depth})) {
                   12029:              $children->{$parent->{$depth}} .= $count.':';
                   12030:         }
                   12031:     }
                   12032:     return;
                   12033: }
                   12034: 
                   12035: sub archive_row {
                   12036:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12037:     my ($name) = ($item =~ m{([^/]+)$});
                   12038:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12039:                                        'display'    => 'Add as file',
1.1055    raeburn  12040:                                        'dependency' => 'Include as dependency',
                   12041:                                        'discard'    => 'Discard',
                   12042:                                       );
                   12043:     if ($is_dir) {
1.1059    raeburn  12044:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12045:     }
1.1056    raeburn  12046:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12047:     my $offset = 0;
1.1055    raeburn  12048:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12049:         $offset ++;
1.1065    raeburn  12050:         if ($action ne 'display') {
                   12051:             $offset ++;
                   12052:         }  
1.1055    raeburn  12053:         $output .= '<td><span class="LC_nobreak">'.
                   12054:                    '<label><input type="radio" name="archive_'.$count.
                   12055:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12056:         my $text = $choices{$action};
                   12057:         if ($is_dir) {
                   12058:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12059:             if ($action eq 'display') {
1.1059    raeburn  12060:                 $text = &mt('Add as folder');
1.1055    raeburn  12061:             }
1.1056    raeburn  12062:         } else {
                   12063:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12064: 
                   12065:         }
                   12066:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12067:         if ($action eq 'dependency') {
                   12068:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12069:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12070:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12071:                        '<option value=""></option>'."\n".
                   12072:                        '</select>'."\n".
                   12073:                        '</div>';
1.1059    raeburn  12074:         } elsif ($action eq 'display') {
                   12075:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12076:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12077:                        '</div>';
1.1055    raeburn  12078:         }
1.1056    raeburn  12079:         $output .= '</td>';
1.1055    raeburn  12080:     }
                   12081:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12082:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12083:     for (my $i=0; $i<$depth; $i++) {
                   12084:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12085:     }
                   12086:     if ($is_dir) {
                   12087:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12088:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12089:     } else {
                   12090:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12091:     }
                   12092:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12093:                &end_data_table_row();
                   12094:     return $output;
                   12095: }
                   12096: 
                   12097: sub archive_options_form {
1.1065    raeburn  12098:     my ($form,$display,$count,$hiddenelem) = @_;
                   12099:     my %lt = &Apache::lonlocal::texthash(
                   12100:                perm => 'Permanently remove archive file?',
                   12101:                hows => 'How should each extracted item be incorporated in the course?',
                   12102:                cont => 'Content actions for all',
                   12103:                addf => 'Add as folder/file',
                   12104:                incd => 'Include as dependency for a displayed file',
                   12105:                disc => 'Discard',
                   12106:                no   => 'No',
                   12107:                yes  => 'Yes',
                   12108:                save => 'Save',
                   12109:     );
                   12110:     my $output = <<"END";
                   12111: <form name="$form" method="post" action="">
                   12112: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12113: <label>
                   12114:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12115: </label>
                   12116: &nbsp;
                   12117: <label>
                   12118:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12119: </span>
                   12120: </p>
                   12121: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12122: <br />$lt{'hows'}
                   12123: <div class="LC_columnSection">
                   12124:   <fieldset>
                   12125:     <legend>$lt{'cont'}</legend>
                   12126:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12127:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12128:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12129:   </fieldset>
                   12130: </div>
                   12131: END
                   12132:     return $output.
1.1055    raeburn  12133:            &start_data_table()."\n".
1.1065    raeburn  12134:            $display."\n".
1.1055    raeburn  12135:            &end_data_table()."\n".
                   12136:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12137:            $hiddenelem.
1.1065    raeburn  12138:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12139:            '</form>';
                   12140: }
                   12141: 
                   12142: sub archive_javascript {
1.1056    raeburn  12143:     my ($startcount,$numitems,$titles,$children) = @_;
                   12144:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12145:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12146:     my $scripttag = <<START;
                   12147: <script type="text/javascript">
                   12148: // <![CDATA[
                   12149: 
                   12150: function checkAll(form,prefix) {
                   12151:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12152:     for (var i=0; i < form.elements.length; i++) {
                   12153:         var id = form.elements[i].id;
                   12154:         if ((id != '') && (id != undefined)) {
                   12155:             if (idstr.test(id)) {
                   12156:                 if (form.elements[i].type == 'radio') {
                   12157:                     form.elements[i].checked = true;
1.1056    raeburn  12158:                     var nostart = i-$startcount;
1.1059    raeburn  12159:                     var offset = nostart%7;
                   12160:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12161:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12162:                 }
                   12163:             }
                   12164:         }
                   12165:     }
                   12166: }
                   12167: 
                   12168: function propagateCheck(form,count) {
                   12169:     if (count > 0) {
1.1059    raeburn  12170:         var startelement = $startcount + ((count-1) * 7);
                   12171:         for (var j=1; j<6; j++) {
                   12172:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12173:                 var item = startelement + j; 
                   12174:                 if (form.elements[item].type == 'radio') {
                   12175:                     if (form.elements[item].checked) {
                   12176:                         containerCheck(form,count,j);
                   12177:                         break;
                   12178:                     }
1.1055    raeburn  12179:                 }
                   12180:             }
                   12181:         }
                   12182:     }
                   12183: }
                   12184: 
                   12185: numitems = $numitems
1.1056    raeburn  12186: var titles = new Array(numitems);
                   12187: var parents = new Array(numitems);
1.1055    raeburn  12188: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12189:     parents[i] = new Array;
1.1055    raeburn  12190: }
1.1059    raeburn  12191: var maintitle = '$maintitle';
1.1055    raeburn  12192: 
                   12193: START
                   12194: 
1.1056    raeburn  12195:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12196:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12197:         for (my $i=0; $i<@contents; $i ++) {
                   12198:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12199:         }
                   12200:     }
                   12201: 
1.1056    raeburn  12202:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12203:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12204:     }
                   12205: 
1.1055    raeburn  12206:     $scripttag .= <<END;
                   12207: 
                   12208: function containerCheck(form,count,offset) {
                   12209:     if (count > 0) {
1.1056    raeburn  12210:         dependencyCheck(form,count,offset);
1.1059    raeburn  12211:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12212:         form.elements[item].checked = true;
                   12213:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12214:             if (parents[count].length > 0) {
                   12215:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12216:                     containerCheck(form,parents[count][j],offset);
                   12217:                 }
                   12218:             }
                   12219:         }
                   12220:     }
                   12221: }
                   12222: 
                   12223: function dependencyCheck(form,count,offset) {
                   12224:     if (count > 0) {
1.1059    raeburn  12225:         var chosen = (offset+$startcount)+7*(count-1);
                   12226:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12227:         var currtype = form.elements[depitem].type;
                   12228:         if (form.elements[chosen].value == 'dependency') {
                   12229:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12230:             form.elements[depitem].options.length = 0;
                   12231:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12232:             for (var i=1; i<=numitems; i++) {
                   12233:                 if (i == count) {
                   12234:                     continue;
                   12235:                 }
1.1059    raeburn  12236:                 var startelement = $startcount + (i-1) * 7;
                   12237:                 for (var j=1; j<6; j++) {
                   12238:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12239:                         var item = startelement + j;
                   12240:                         if (form.elements[item].type == 'radio') {
                   12241:                             if (form.elements[item].checked) {
                   12242:                                 if (form.elements[item].value == 'display') {
                   12243:                                     var n = form.elements[depitem].options.length;
                   12244:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12245:                                 }
                   12246:                             }
                   12247:                         }
                   12248:                     }
                   12249:                 }
                   12250:             }
                   12251:         } else {
                   12252:             document.getElementById('arc_depon_'+count).style.display='none';
                   12253:             form.elements[depitem].options.length = 0;
                   12254:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12255:         }
1.1059    raeburn  12256:         titleCheck(form,count,offset);
1.1056    raeburn  12257:     }
                   12258: }
                   12259: 
                   12260: function propagateSelect(form,count,offset) {
                   12261:     if (count > 0) {
1.1065    raeburn  12262:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12263:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12264:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12265:             if (parents[count].length > 0) {
                   12266:                 for (var j=0; j<parents[count].length; j++) {
                   12267:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12268:                 }
                   12269:             }
                   12270:         }
                   12271:     }
                   12272: }
1.1056    raeburn  12273: 
                   12274: function containerSelect(form,count,offset,picked) {
                   12275:     if (count > 0) {
1.1065    raeburn  12276:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12277:         if (form.elements[item].type == 'radio') {
                   12278:             if (form.elements[item].value == 'dependency') {
                   12279:                 if (form.elements[item+1].type == 'select-one') {
                   12280:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12281:                         if (form.elements[item+1].options[i].value == picked) {
                   12282:                             form.elements[item+1].selectedIndex = i;
                   12283:                             break;
                   12284:                         }
                   12285:                     }
                   12286:                 }
                   12287:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12288:                     if (parents[count].length > 0) {
                   12289:                         for (var j=0; j<parents[count].length; j++) {
                   12290:                             containerSelect(form,parents[count][j],offset,picked);
                   12291:                         }
                   12292:                     }
                   12293:                 }
                   12294:             }
                   12295:         }
                   12296:     }
                   12297: }
                   12298: 
1.1059    raeburn  12299: function titleCheck(form,count,offset) {
                   12300:     if (count > 0) {
                   12301:         var chosen = (offset+$startcount)+7*(count-1);
                   12302:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12303:         var currtype = form.elements[depitem].type;
                   12304:         if (form.elements[chosen].value == 'display') {
                   12305:             document.getElementById('arc_title_'+count).style.display='block';
                   12306:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12307:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12308:             }
                   12309:         } else {
                   12310:             document.getElementById('arc_title_'+count).style.display='none';
                   12311:             if (currtype == 'text') { 
                   12312:                 document.getElementById('archive_title_'+count).value='';
                   12313:             }
                   12314:         }
                   12315:     }
                   12316:     return;
                   12317: }
                   12318: 
1.1055    raeburn  12319: // ]]>
                   12320: </script>
                   12321: END
                   12322:     return $scripttag;
                   12323: }
                   12324: 
                   12325: sub process_extracted_files {
1.1067    raeburn  12326:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12327:     my $numitems = $env{'form.archive_count'};
                   12328:     return unless ($numitems);
                   12329:     my @ids=&Apache::lonnet::current_machine_ids();
                   12330:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12331:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12332:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12333:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12334:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12335:         $pathtocheck = "$dir_root/$destination";
                   12336:         $dir = $dir_root;
                   12337:         $ishome = 1;
                   12338:     } else {
                   12339:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12340:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12341:         $dir = "$dir_root/$docudom/$docuname";    
                   12342:     }
                   12343:     my $currdir = "$dir_root/$destination";
                   12344:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12345:     if ($env{'form.folderpath'}) {
                   12346:         my @items = split('&',$env{'form.folderpath'});
                   12347:         $folders{'0'} = $items[-2];
1.1099    raeburn  12348:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12349:             $containers{'0'}='page';
                   12350:         } else {  
                   12351:             $containers{'0'}='sequence';
                   12352:         }
1.1055    raeburn  12353:     }
                   12354:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12355:     if ($numitems) {
                   12356:         for (my $i=1; $i<=$numitems; $i++) {
                   12357:             my $path = $env{'form.archive_content_'.$i};
                   12358:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12359:                 my $item = $1;
                   12360:                 $toplevelitems{$item} = $i;
                   12361:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12362:                     $is_dir{$item} = 1;
                   12363:                 }
                   12364:             }
                   12365:         }
                   12366:     }
1.1067    raeburn  12367:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12368:     if (keys(%toplevelitems) > 0) {
                   12369:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12370:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12371:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12372:     }
1.1066    raeburn  12373:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12374:     if ($numitems) {
                   12375:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12376:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12377:             my $path = $env{'form.archive_content_'.$i};
                   12378:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12379:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12380:                     if ($prefix ne '' && $path ne '') {
                   12381:                         if (-e $prefix.$path) {
1.1066    raeburn  12382:                             if ((@archdirs > 0) && 
                   12383:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12384:                                 $todeletedir{$prefix.$path} = 1;
                   12385:                             } else {
                   12386:                                 $todelete{$prefix.$path} = 1;
                   12387:                             }
1.1055    raeburn  12388:                         }
                   12389:                     }
                   12390:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12391:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12392:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12393:                     $docstitle = $env{'form.archive_title_'.$i};
                   12394:                     if ($docstitle eq '') {
                   12395:                         $docstitle = $title;
                   12396:                     }
1.1055    raeburn  12397:                     $outer = 0;
1.1056    raeburn  12398:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12399:                         if (@{$dirorder{$i}} > 0) {
                   12400:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12401:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12402:                                     $outer = $item;
                   12403:                                     last;
                   12404:                                 }
                   12405:                             }
                   12406:                         }
                   12407:                     }
                   12408:                     my ($errtext,$fatal) = 
                   12409:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12410:                                                '/'.$folders{$outer}.'.'.
                   12411:                                                $containers{$outer});
                   12412:                     next if ($fatal);
                   12413:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12414:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12415:                             $mapinner{$i} = time;
1.1055    raeburn  12416:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12417:                             $containers{$i} = 'sequence';
                   12418:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12419:                                       $folders{$i}.'.'.$containers{$i};
                   12420:                             my $newidx = &LONCAPA::map::getresidx();
                   12421:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12422:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12423:                             push(@LONCAPA::map::order,$newidx);
                   12424:                             my ($outtext,$errtext) =
                   12425:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12426:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12427:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12428:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12429:                             unless ($errtext) {
                   12430:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12431:                             }
1.1055    raeburn  12432:                         }
                   12433:                     } else {
                   12434:                         if ($context eq 'coursedocs') {
                   12435:                             my $newidx=&LONCAPA::map::getresidx();
                   12436:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12437:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12438:                                       $title;
                   12439:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12440:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12441:                             }
                   12442:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12443:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12444:                             }
                   12445:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12446:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12447:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12448:                                 unless ($ishome) {
                   12449:                                     my $fetch = "$newdest{$i}/$title";
                   12450:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12451:                                     $prompttofetch{$fetch} = 1;
                   12452:                                 }
1.1055    raeburn  12453:                             }
                   12454:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12455:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12456:                             push(@LONCAPA::map::order, $newidx);
                   12457:                             my ($outtext,$errtext)=
                   12458:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12459:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12460:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12461:                             unless ($errtext) {
                   12462:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12463:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12464:                                 }
                   12465:                             }
1.1055    raeburn  12466:                         }
                   12467:                     }
1.1086    raeburn  12468:                 }
                   12469:             } else {
                   12470:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12471:             }
                   12472:         }
                   12473:         for (my $i=1; $i<=$numitems; $i++) {
                   12474:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12475:             my $path = $env{'form.archive_content_'.$i};
                   12476:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12477:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12478:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12479:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12480:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12481:                         my ($itemidx,$fullpath,$relpath);
                   12482:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12483:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12484:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12485:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12486:                                     $itemidx = $j;
1.1056    raeburn  12487:                                 }
                   12488:                             }
1.1086    raeburn  12489:                         }
                   12490:                         if ($itemidx eq '') {
                   12491:                             $itemidx =  0;
                   12492:                         } 
                   12493:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12494:                             if ($mapinner{$referrer{$i}}) {
                   12495:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12496:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12497:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12498:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12499:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12500:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12501:                                             if (!-e $fullpath) {
                   12502:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12503:                                             }
                   12504:                                         }
1.1086    raeburn  12505:                                     } else {
                   12506:                                         last;
1.1056    raeburn  12507:                                     }
1.1086    raeburn  12508:                                 }
                   12509:                             }
                   12510:                         } elsif ($newdest{$referrer{$i}}) {
                   12511:                             $fullpath = $newdest{$referrer{$i}};
                   12512:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12513:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12514:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12515:                                     last;
                   12516:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12517:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12518:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12519:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12520:                                         if (!-e $fullpath) {
                   12521:                                             mkdir($fullpath,0755);
1.1056    raeburn  12522:                                         }
                   12523:                                     }
1.1086    raeburn  12524:                                 } else {
                   12525:                                     last;
1.1056    raeburn  12526:                                 }
1.1055    raeburn  12527:                             }
                   12528:                         }
1.1086    raeburn  12529:                         if ($fullpath ne '') {
                   12530:                             if (-e "$prefix$path") {
                   12531:                                 system("mv $prefix$path $fullpath/$title");
                   12532:                             }
                   12533:                             if (-e "$fullpath/$title") {
                   12534:                                 my $showpath;
                   12535:                                 if ($relpath ne '') {
                   12536:                                     $showpath = "$relpath/$title";
                   12537:                                 } else {
                   12538:                                     $showpath = "/$title";
                   12539:                                 } 
                   12540:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12541:                             } 
                   12542:                             unless ($ishome) {
                   12543:                                 my $fetch = "$fullpath/$title";
                   12544:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12545:                                 $prompttofetch{$fetch} = 1;
                   12546:                             }
                   12547:                         }
1.1055    raeburn  12548:                     }
1.1086    raeburn  12549:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12550:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12551:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12552:                 }
                   12553:             } else {
                   12554:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12555:             }
                   12556:         }
                   12557:         if (keys(%todelete)) {
                   12558:             foreach my $key (keys(%todelete)) {
                   12559:                 unlink($key);
1.1066    raeburn  12560:             }
                   12561:         }
                   12562:         if (keys(%todeletedir)) {
                   12563:             foreach my $key (keys(%todeletedir)) {
                   12564:                 rmdir($key);
                   12565:             }
                   12566:         }
                   12567:         foreach my $dir (sort(keys(%is_dir))) {
                   12568:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12569:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12570:             }
                   12571:         }
1.1067    raeburn  12572:         if ($result ne '') {
                   12573:             $output .= '<ul>'."\n".
                   12574:                        $result."\n".
                   12575:                        '</ul>';
                   12576:         }
                   12577:         unless ($ishome) {
                   12578:             my $replicationfail;
                   12579:             foreach my $item (keys(%prompttofetch)) {
                   12580:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12581:                 unless ($fetchresult eq 'ok') {
                   12582:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12583:                 }
                   12584:             }
                   12585:             if ($replicationfail) {
                   12586:                 $output .= '<p class="LC_error">'.
                   12587:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12588:                            $replicationfail.
                   12589:                            '</ul></p>';
                   12590:             }
                   12591:         }
1.1055    raeburn  12592:     } else {
                   12593:         $warning = &mt('No items found in archive.');
                   12594:     }
                   12595:     if ($error) {
                   12596:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12597:                    $error.'</p>'."\n";
                   12598:     }
                   12599:     if ($warning) {
                   12600:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12601:     }
                   12602:     return $output;
                   12603: }
                   12604: 
1.1066    raeburn  12605: sub cleanup_empty_dirs {
                   12606:     my ($path) = @_;
                   12607:     if (($path ne '') && (-d $path)) {
                   12608:         if (opendir(my $dirh,$path)) {
                   12609:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12610:             my $numitems = 0;
                   12611:             foreach my $item (@dircontents) {
                   12612:                 if (-d "$path/$item") {
1.1111    raeburn  12613:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12614:                     if (-e "$path/$item") {
                   12615:                         $numitems ++;
                   12616:                     }
                   12617:                 } else {
                   12618:                     $numitems ++;
                   12619:                 }
                   12620:             }
                   12621:             if ($numitems == 0) {
                   12622:                 rmdir($path);
                   12623:             }
                   12624:             closedir($dirh);
                   12625:         }
                   12626:     }
                   12627:     return;
                   12628: }
                   12629: 
1.41      ng       12630: =pod
1.45      matthew  12631: 
1.1162    raeburn  12632: =item * &get_folder_hierarchy()
1.1068    raeburn  12633: 
                   12634: Provides hierarchy of names of folders/sub-folders containing the current
                   12635: item,
                   12636: 
                   12637: Inputs: 3
                   12638:      - $navmap - navmaps object
                   12639: 
                   12640:      - $map - url for map (either the trigger itself, or map containing
                   12641:                            the resource, which is the trigger).
                   12642: 
                   12643:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12644: 
                   12645: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12646: 
                   12647: =cut
                   12648: 
                   12649: sub get_folder_hierarchy {
                   12650:     my ($navmap,$map,$showitem) = @_;
                   12651:     my @pathitems;
                   12652:     if (ref($navmap)) {
                   12653:         my $mapres = $navmap->getResourceByUrl($map);
                   12654:         if (ref($mapres)) {
                   12655:             my $pcslist = $mapres->map_hierarchy();
                   12656:             if ($pcslist ne '') {
                   12657:                 my @pcs = split(/,/,$pcslist);
                   12658:                 foreach my $pc (@pcs) {
                   12659:                     if ($pc == 1) {
1.1129    raeburn  12660:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12661:                     } else {
                   12662:                         my $res = $navmap->getByMapPc($pc);
                   12663:                         if (ref($res)) {
                   12664:                             my $title = $res->compTitle();
                   12665:                             $title =~ s/\W+/_/g;
                   12666:                             if ($title ne '') {
                   12667:                                 push(@pathitems,$title);
                   12668:                             }
                   12669:                         }
                   12670:                     }
                   12671:                 }
                   12672:             }
1.1071    raeburn  12673:             if ($showitem) {
                   12674:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12675:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12676:                 } else {
                   12677:                     my $maptitle = $mapres->compTitle();
                   12678:                     $maptitle =~ s/\W+/_/g;
                   12679:                     if ($maptitle ne '') {
                   12680:                         push(@pathitems,$maptitle);
                   12681:                     }
1.1068    raeburn  12682:                 }
                   12683:             }
                   12684:         }
                   12685:     }
                   12686:     return @pathitems;
                   12687: }
                   12688: 
                   12689: =pod
                   12690: 
1.1015    raeburn  12691: =item * &get_turnedin_filepath()
                   12692: 
                   12693: Determines path in a user's portfolio file for storage of files uploaded
                   12694: to a specific essayresponse or dropbox item.
                   12695: 
                   12696: Inputs: 3 required + 1 optional.
                   12697: $symb is symb for resource, $uname and $udom are for current user (required).
                   12698: $caller is optional (can be "submission", if routine is called when storing
                   12699: an upoaded file when "Submit Answer" button was pressed).
                   12700: 
                   12701: Returns array containing $path and $multiresp. 
                   12702: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12703: than one file upload item.  Callers of routine should append partid as a 
                   12704: subdirectory to $path in cases where $multiresp is 1.
                   12705: 
                   12706: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12707: 
                   12708: =cut
                   12709: 
                   12710: sub get_turnedin_filepath {
                   12711:     my ($symb,$uname,$udom,$caller) = @_;
                   12712:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12713:     my $turnindir;
                   12714:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12715:     $turnindir = $userhash{'turnindir'};
                   12716:     my ($path,$multiresp);
                   12717:     if ($turnindir eq '') {
                   12718:         if ($caller eq 'submission') {
                   12719:             $turnindir = &mt('turned in');
                   12720:             $turnindir =~ s/\W+/_/g;
                   12721:             my %newhash = (
                   12722:                             'turnindir' => $turnindir,
                   12723:                           );
                   12724:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12725:         }
                   12726:     }
                   12727:     if ($turnindir ne '') {
                   12728:         $path = '/'.$turnindir.'/';
                   12729:         my ($multipart,$turnin,@pathitems);
                   12730:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12731:         if (defined($navmap)) {
                   12732:             my $mapres = $navmap->getResourceByUrl($map);
                   12733:             if (ref($mapres)) {
                   12734:                 my $pcslist = $mapres->map_hierarchy();
                   12735:                 if ($pcslist ne '') {
                   12736:                     foreach my $pc (split(/,/,$pcslist)) {
                   12737:                         my $res = $navmap->getByMapPc($pc);
                   12738:                         if (ref($res)) {
                   12739:                             my $title = $res->compTitle();
                   12740:                             $title =~ s/\W+/_/g;
                   12741:                             if ($title ne '') {
1.1149    raeburn  12742:                                 if (($pc > 1) && (length($title) > 12)) {
                   12743:                                     $title = substr($title,0,12);
                   12744:                                 }
1.1015    raeburn  12745:                                 push(@pathitems,$title);
                   12746:                             }
                   12747:                         }
                   12748:                     }
                   12749:                 }
                   12750:                 my $maptitle = $mapres->compTitle();
                   12751:                 $maptitle =~ s/\W+/_/g;
                   12752:                 if ($maptitle ne '') {
1.1149    raeburn  12753:                     if (length($maptitle) > 12) {
                   12754:                         $maptitle = substr($maptitle,0,12);
                   12755:                     }
1.1015    raeburn  12756:                     push(@pathitems,$maptitle);
                   12757:                 }
                   12758:                 unless ($env{'request.state'} eq 'construct') {
                   12759:                     my $res = $navmap->getBySymb($symb);
                   12760:                     if (ref($res)) {
                   12761:                         my $partlist = $res->parts();
                   12762:                         my $totaluploads = 0;
                   12763:                         if (ref($partlist) eq 'ARRAY') {
                   12764:                             foreach my $part (@{$partlist}) {
                   12765:                                 my @types = $res->responseType($part);
                   12766:                                 my @ids = $res->responseIds($part);
                   12767:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12768:                                     if ($types[$i] eq 'essay') {
                   12769:                                         my $partid = $part.'_'.$ids[$i];
                   12770:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12771:                                             $totaluploads ++;
                   12772:                                         }
                   12773:                                     }
                   12774:                                 }
                   12775:                             }
                   12776:                             if ($totaluploads > 1) {
                   12777:                                 $multiresp = 1;
                   12778:                             }
                   12779:                         }
                   12780:                     }
                   12781:                 }
                   12782:             } else {
                   12783:                 return;
                   12784:             }
                   12785:         } else {
                   12786:             return;
                   12787:         }
                   12788:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12789:         $restitle =~ s/\W+/_/g;
                   12790:         if ($restitle eq '') {
                   12791:             $restitle = ($resurl =~ m{/[^/]+$});
                   12792:             if ($restitle eq '') {
                   12793:                 $restitle = time;
                   12794:             }
                   12795:         }
1.1149    raeburn  12796:         if (length($restitle) > 12) {
                   12797:             $restitle = substr($restitle,0,12);
                   12798:         }
1.1015    raeburn  12799:         push(@pathitems,$restitle);
                   12800:         $path .= join('/',@pathitems);
                   12801:     }
                   12802:     return ($path,$multiresp);
                   12803: }
                   12804: 
                   12805: =pod
                   12806: 
1.464     albertel 12807: =back
1.41      ng       12808: 
1.112     bowersj2 12809: =head1 CSV Upload/Handling functions
1.38      albertel 12810: 
1.41      ng       12811: =over 4
                   12812: 
1.648     raeburn  12813: =item * &upfile_store($r)
1.41      ng       12814: 
                   12815: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12816: needs $env{'form.upfile'}
1.41      ng       12817: returns $datatoken to be put into hidden field
                   12818: 
                   12819: =cut
1.31      albertel 12820: 
                   12821: sub upfile_store {
                   12822:     my $r=shift;
1.258     albertel 12823:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12824:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12825:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12826:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12827: 
1.258     albertel 12828:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12829: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12830:     {
1.158     raeburn  12831:         my $datafile = $r->dir_config('lonDaemons').
                   12832:                            '/tmp/'.$datatoken.'.tmp';
                   12833:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12834:             print $fh $env{'form.upfile'};
1.158     raeburn  12835:             close($fh);
                   12836:         }
1.31      albertel 12837:     }
                   12838:     return $datatoken;
                   12839: }
                   12840: 
1.56      matthew  12841: =pod
                   12842: 
1.648     raeburn  12843: =item * &load_tmp_file($r)
1.41      ng       12844: 
                   12845: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12846: needs $env{'form.datatoken'},
                   12847: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12848: 
                   12849: =cut
1.31      albertel 12850: 
                   12851: sub load_tmp_file {
                   12852:     my $r=shift;
                   12853:     my @studentdata=();
                   12854:     {
1.158     raeburn  12855:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12856:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12857:         if ( open(my $fh,"<$studentfile") ) {
                   12858:             @studentdata=<$fh>;
                   12859:             close($fh);
                   12860:         }
1.31      albertel 12861:     }
1.258     albertel 12862:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12863: }
                   12864: 
1.56      matthew  12865: =pod
                   12866: 
1.648     raeburn  12867: =item * &upfile_record_sep()
1.41      ng       12868: 
                   12869: Separate uploaded file into records
                   12870: returns array of records,
1.258     albertel 12871: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12872: 
                   12873: =cut
1.31      albertel 12874: 
                   12875: sub upfile_record_sep {
1.258     albertel 12876:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12877:     } else {
1.248     albertel 12878: 	my @records;
1.258     albertel 12879: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12880: 	    if ($line=~/^\s*$/) { next; }
                   12881: 	    push(@records,$line);
                   12882: 	}
                   12883: 	return @records;
1.31      albertel 12884:     }
                   12885: }
                   12886: 
1.56      matthew  12887: =pod
                   12888: 
1.648     raeburn  12889: =item * &record_sep($record)
1.41      ng       12890: 
1.258     albertel 12891: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12892: 
                   12893: =cut
                   12894: 
1.263     www      12895: sub takeleft {
                   12896:     my $index=shift;
                   12897:     return substr('0000'.$index,-4,4);
                   12898: }
                   12899: 
1.31      albertel 12900: sub record_sep {
                   12901:     my $record=shift;
                   12902:     my %components=();
1.258     albertel 12903:     if ($env{'form.upfiletype'} eq 'xml') {
                   12904:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12905:         my $i=0;
1.356     albertel 12906:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12907:             $field=~s/^(\"|\')//;
                   12908:             $field=~s/(\"|\')$//;
1.263     www      12909:             $components{&takeleft($i)}=$field;
1.31      albertel 12910:             $i++;
                   12911:         }
1.258     albertel 12912:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12913:         my $i=0;
1.356     albertel 12914:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12915:             $field=~s/^(\"|\')//;
                   12916:             $field=~s/(\"|\')$//;
1.263     www      12917:             $components{&takeleft($i)}=$field;
1.31      albertel 12918:             $i++;
                   12919:         }
                   12920:     } else {
1.561     www      12921:         my $separator=',';
1.480     banghart 12922:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12923:             $separator=';';
1.480     banghart 12924:         }
1.31      albertel 12925:         my $i=0;
1.561     www      12926: # the character we are looking for to indicate the end of a quote or a record 
                   12927:         my $looking_for=$separator;
                   12928: # do not add the characters to the fields
                   12929:         my $ignore=0;
                   12930: # we just encountered a separator (or the beginning of the record)
                   12931:         my $just_found_separator=1;
                   12932: # store the field we are working on here
                   12933:         my $field='';
                   12934: # work our way through all characters in record
                   12935:         foreach my $character ($record=~/(.)/g) {
                   12936:             if ($character eq $looking_for) {
                   12937:                if ($character ne $separator) {
                   12938: # Found the end of a quote, again looking for separator
                   12939:                   $looking_for=$separator;
                   12940:                   $ignore=1;
                   12941:                } else {
                   12942: # Found a separator, store away what we got
                   12943:                   $components{&takeleft($i)}=$field;
                   12944: 	          $i++;
                   12945:                   $just_found_separator=1;
                   12946:                   $ignore=0;
                   12947:                   $field='';
                   12948:                }
                   12949:                next;
                   12950:             }
                   12951: # single or double quotation marks after a separator indicate beginning of a quote
                   12952: # we are now looking for the end of the quote and need to ignore separators
                   12953:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12954:                $looking_for=$character;
                   12955:                next;
                   12956:             }
                   12957: # ignore would be true after we reached the end of a quote
                   12958:             if ($ignore) { next; }
                   12959:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12960:             $field.=$character;
                   12961:             $just_found_separator=0; 
1.31      albertel 12962:         }
1.561     www      12963: # catch the very last entry, since we never encountered the separator
                   12964:         $components{&takeleft($i)}=$field;
1.31      albertel 12965:     }
                   12966:     return %components;
                   12967: }
                   12968: 
1.144     matthew  12969: ######################################################
                   12970: ######################################################
                   12971: 
1.56      matthew  12972: =pod
                   12973: 
1.648     raeburn  12974: =item * &upfile_select_html()
1.41      ng       12975: 
1.144     matthew  12976: Return HTML code to select a file from the users machine and specify 
                   12977: the file type.
1.41      ng       12978: 
                   12979: =cut
                   12980: 
1.144     matthew  12981: ######################################################
                   12982: ######################################################
1.31      albertel 12983: sub upfile_select_html {
1.144     matthew  12984:     my %Types = (
                   12985:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12986:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12987:                  space => &mt('Space separated'),
                   12988:                  tab   => &mt('Tabulator separated'),
                   12989: #                 xml   => &mt('HTML/XML'),
                   12990:                  );
                   12991:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12992:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12993:     foreach my $type (sort(keys(%Types))) {
                   12994:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12995:     }
                   12996:     $Str .= "</select>\n";
                   12997:     return $Str;
1.31      albertel 12998: }
                   12999: 
1.301     albertel 13000: sub get_samples {
                   13001:     my ($records,$toget) = @_;
                   13002:     my @samples=({});
                   13003:     my $got=0;
                   13004:     foreach my $rec (@$records) {
                   13005: 	my %temp = &record_sep($rec);
                   13006: 	if (! grep(/\S/, values(%temp))) { next; }
                   13007: 	if (%temp) {
                   13008: 	    $samples[$got]=\%temp;
                   13009: 	    $got++;
                   13010: 	    if ($got == $toget) { last; }
                   13011: 	}
                   13012:     }
                   13013:     return \@samples;
                   13014: }
                   13015: 
1.144     matthew  13016: ######################################################
                   13017: ######################################################
                   13018: 
1.56      matthew  13019: =pod
                   13020: 
1.648     raeburn  13021: =item * &csv_print_samples($r,$records)
1.41      ng       13022: 
                   13023: Prints a table of sample values from each column uploaded $r is an
                   13024: Apache Request ref, $records is an arrayref from
                   13025: &Apache::loncommon::upfile_record_sep
                   13026: 
                   13027: =cut
                   13028: 
1.144     matthew  13029: ######################################################
                   13030: ######################################################
1.31      albertel 13031: sub csv_print_samples {
                   13032:     my ($r,$records) = @_;
1.662     bisitz   13033:     my $samples = &get_samples($records,5);
1.301     albertel 13034: 
1.594     raeburn  13035:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13036:               &start_data_table_header_row());
1.356     albertel 13037:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13038:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13039:     $r->print(&end_data_table_header_row());
1.301     albertel 13040:     foreach my $hash (@$samples) {
1.594     raeburn  13041: 	$r->print(&start_data_table_row());
1.356     albertel 13042: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13043: 	    $r->print('<td>');
1.356     albertel 13044: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13045: 	    $r->print('</td>');
                   13046: 	}
1.594     raeburn  13047: 	$r->print(&end_data_table_row());
1.31      albertel 13048:     }
1.594     raeburn  13049:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13050: }
                   13051: 
1.144     matthew  13052: ######################################################
                   13053: ######################################################
                   13054: 
1.56      matthew  13055: =pod
                   13056: 
1.648     raeburn  13057: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13058: 
                   13059: Prints a table to create associations between values and table columns.
1.144     matthew  13060: 
1.41      ng       13061: $r is an Apache Request ref,
                   13062: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13063: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13064: 
                   13065: =cut
                   13066: 
1.144     matthew  13067: ######################################################
                   13068: ######################################################
1.31      albertel 13069: sub csv_print_select_table {
                   13070:     my ($r,$records,$d) = @_;
1.301     albertel 13071:     my $i=0;
                   13072:     my $samples = &get_samples($records,1);
1.144     matthew  13073:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13074: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13075:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13076:               '<th>'.&mt('Column').'</th>'.
                   13077:               &end_data_table_header_row()."\n");
1.356     albertel 13078:     foreach my $array_ref (@$d) {
                   13079: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13080: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13081: 
1.875     bisitz   13082: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13083: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13084: 	$r->print('<option value="none"></option>');
1.356     albertel 13085: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13086: 	    $r->print('<option value="'.$sample.'"'.
                   13087:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13088:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13089: 	}
1.594     raeburn  13090: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13091: 	$i++;
                   13092:     }
1.594     raeburn  13093:     $r->print(&end_data_table());
1.31      albertel 13094:     $i--;
                   13095:     return $i;
                   13096: }
1.56      matthew  13097: 
1.144     matthew  13098: ######################################################
                   13099: ######################################################
                   13100: 
1.56      matthew  13101: =pod
1.31      albertel 13102: 
1.648     raeburn  13103: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13104: 
                   13105: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13106: 
                   13107: $r is an Apache Request ref,
                   13108: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13109: $d is an array of 2 element arrays (internal name, displayed name)
                   13110: 
                   13111: =cut
                   13112: 
1.144     matthew  13113: ######################################################
                   13114: ######################################################
1.31      albertel 13115: sub csv_samples_select_table {
                   13116:     my ($r,$records,$d) = @_;
                   13117:     my $i=0;
1.144     matthew  13118:     #
1.662     bisitz   13119:     my $max_samples = 5;
                   13120:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13121:     $r->print(&start_data_table().
                   13122:               &start_data_table_header_row().'<th>'.
                   13123:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13124:               &end_data_table_header_row());
1.301     albertel 13125: 
                   13126:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13127: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13128: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13129: 	foreach my $option (@$d) {
                   13130: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13131: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13132:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13133:                       $display.'</option>');
1.31      albertel 13134: 	}
                   13135: 	$r->print('</select></td><td>');
1.662     bisitz   13136: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13137: 	    if (defined($samples->[$line]{$key})) { 
                   13138: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13139: 	    }
                   13140: 	}
1.594     raeburn  13141: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13142: 	$i++;
                   13143:     }
1.594     raeburn  13144:     $r->print(&end_data_table());
1.31      albertel 13145:     $i--;
                   13146:     return($i);
1.115     matthew  13147: }
                   13148: 
1.144     matthew  13149: ######################################################
                   13150: ######################################################
                   13151: 
1.115     matthew  13152: =pod
                   13153: 
1.648     raeburn  13154: =item * &clean_excel_name($name)
1.115     matthew  13155: 
                   13156: Returns a replacement for $name which does not contain any illegal characters.
                   13157: 
                   13158: =cut
                   13159: 
1.144     matthew  13160: ######################################################
                   13161: ######################################################
1.115     matthew  13162: sub clean_excel_name {
                   13163:     my ($name) = @_;
                   13164:     $name =~ s/[:\*\?\/\\]//g;
                   13165:     if (length($name) > 31) {
                   13166:         $name = substr($name,0,31);
                   13167:     }
                   13168:     return $name;
1.25      albertel 13169: }
1.84      albertel 13170: 
1.85      albertel 13171: =pod
                   13172: 
1.648     raeburn  13173: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13174: 
                   13175: Returns either 1 or undef
                   13176: 
                   13177: 1 if the part is to be hidden, undef if it is to be shown
                   13178: 
                   13179: Arguments are:
                   13180: 
                   13181: $id the id of the part to be checked
                   13182: $symb, optional the symb of the resource to check
                   13183: $udom, optional the domain of the user to check for
                   13184: $uname, optional the username of the user to check for
                   13185: 
                   13186: =cut
1.84      albertel 13187: 
                   13188: sub check_if_partid_hidden {
                   13189:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13190:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13191: 					 $symb,$udom,$uname);
1.141     albertel 13192:     my $truth=1;
                   13193:     #if the string starts with !, then the list is the list to show not hide
                   13194:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13195:     my @hiddenlist=split(/,/,$hiddenparts);
                   13196:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13197: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13198:     }
1.141     albertel 13199:     return !$truth;
1.84      albertel 13200: }
1.127     matthew  13201: 
1.138     matthew  13202: 
                   13203: ############################################################
                   13204: ############################################################
                   13205: 
                   13206: =pod
                   13207: 
1.157     matthew  13208: =back 
                   13209: 
1.138     matthew  13210: =head1 cgi-bin script and graphing routines
                   13211: 
1.157     matthew  13212: =over 4
                   13213: 
1.648     raeburn  13214: =item * &get_cgi_id()
1.138     matthew  13215: 
                   13216: Inputs: none
                   13217: 
                   13218: Returns an id which can be used to pass environment variables
                   13219: to various cgi-bin scripts.  These environment variables will
                   13220: be removed from the users environment after a given time by
                   13221: the routine &Apache::lonnet::transfer_profile_to_env.
                   13222: 
                   13223: =cut
                   13224: 
                   13225: ############################################################
                   13226: ############################################################
1.152     albertel 13227: my $uniq=0;
1.136     matthew  13228: sub get_cgi_id {
1.154     albertel 13229:     $uniq=($uniq+1)%100000;
1.280     albertel 13230:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13231: }
                   13232: 
1.127     matthew  13233: ############################################################
                   13234: ############################################################
                   13235: 
                   13236: =pod
                   13237: 
1.648     raeburn  13238: =item * &DrawBarGraph()
1.127     matthew  13239: 
1.138     matthew  13240: Facilitates the plotting of data in a (stacked) bar graph.
                   13241: Puts plot definition data into the users environment in order for 
                   13242: graph.png to plot it.  Returns an <img> tag for the plot.
                   13243: The bars on the plot are labeled '1','2',...,'n'.
                   13244: 
                   13245: Inputs:
                   13246: 
                   13247: =over 4
                   13248: 
                   13249: =item $Title: string, the title of the plot
                   13250: 
                   13251: =item $xlabel: string, text describing the X-axis of the plot
                   13252: 
                   13253: =item $ylabel: string, text describing the Y-axis of the plot
                   13254: 
                   13255: =item $Max: scalar, the maximum Y value to use in the plot
                   13256: If $Max is < any data point, the graph will not be rendered.
                   13257: 
1.140     matthew  13258: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13259: they are plotted.  If undefined, default values will be used.
                   13260: 
1.178     matthew  13261: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13262: 
1.138     matthew  13263: =item @Values: An array of array references.  Each array reference holds data
                   13264: to be plotted in a stacked bar chart.
                   13265: 
1.239     matthew  13266: =item If the final element of @Values is a hash reference the key/value
                   13267: pairs will be added to the graph definition.
                   13268: 
1.138     matthew  13269: =back
                   13270: 
                   13271: Returns:
                   13272: 
                   13273: An <img> tag which references graph.png and the appropriate identifying
                   13274: information for the plot.
                   13275: 
1.127     matthew  13276: =cut
                   13277: 
                   13278: ############################################################
                   13279: ############################################################
1.134     matthew  13280: sub DrawBarGraph {
1.178     matthew  13281:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13282:     #
                   13283:     if (! defined($colors)) {
                   13284:         $colors = ['#33ff00', 
                   13285:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13286:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13287:                   ]; 
                   13288:     }
1.228     matthew  13289:     my $extra_settings = {};
                   13290:     if (ref($Values[-1]) eq 'HASH') {
                   13291:         $extra_settings = pop(@Values);
                   13292:     }
1.127     matthew  13293:     #
1.136     matthew  13294:     my $identifier = &get_cgi_id();
                   13295:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13296:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13297:         return '';
                   13298:     }
1.225     matthew  13299:     #
                   13300:     my @Labels;
                   13301:     if (defined($labels)) {
                   13302:         @Labels = @$labels;
                   13303:     } else {
                   13304:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13305:             push (@Labels,$i+1);
                   13306:         }
                   13307:     }
                   13308:     #
1.129     matthew  13309:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13310:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13311:     my %ValuesHash;
                   13312:     my $NumSets=1;
                   13313:     foreach my $array (@Values) {
                   13314:         next if (! ref($array));
1.136     matthew  13315:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13316:             join(',',@$array);
1.129     matthew  13317:     }
1.127     matthew  13318:     #
1.136     matthew  13319:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13320:     if ($NumBars < 3) {
                   13321:         $width = 120+$NumBars*32;
1.220     matthew  13322:         $xskip = 1;
1.225     matthew  13323:         $bar_width = 30;
                   13324:     } elsif ($NumBars < 5) {
                   13325:         $width = 120+$NumBars*20;
                   13326:         $xskip = 1;
                   13327:         $bar_width = 20;
1.220     matthew  13328:     } elsif ($NumBars < 10) {
1.136     matthew  13329:         $width = 120+$NumBars*15;
                   13330:         $xskip = 1;
                   13331:         $bar_width = 15;
                   13332:     } elsif ($NumBars <= 25) {
                   13333:         $width = 120+$NumBars*11;
                   13334:         $xskip = 5;
                   13335:         $bar_width = 8;
                   13336:     } elsif ($NumBars <= 50) {
                   13337:         $width = 120+$NumBars*8;
                   13338:         $xskip = 5;
                   13339:         $bar_width = 4;
                   13340:     } else {
                   13341:         $width = 120+$NumBars*8;
                   13342:         $xskip = 5;
                   13343:         $bar_width = 4;
                   13344:     }
                   13345:     #
1.137     matthew  13346:     $Max = 1 if ($Max < 1);
                   13347:     if ( int($Max) < $Max ) {
                   13348:         $Max++;
                   13349:         $Max = int($Max);
                   13350:     }
1.127     matthew  13351:     $Title  = '' if (! defined($Title));
                   13352:     $xlabel = '' if (! defined($xlabel));
                   13353:     $ylabel = '' if (! defined($ylabel));
1.369     www      13354:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13355:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13356:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13357:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13358:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13359:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13360:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13361:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13362:     $ValuesHash{$id.'.height'}   = $height;
                   13363:     $ValuesHash{$id.'.width'}    = $width;
                   13364:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13365:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13366:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13367:     #
1.228     matthew  13368:     # Deal with other parameters
                   13369:     while (my ($key,$value) = each(%$extra_settings)) {
                   13370:         $ValuesHash{$id.'.'.$key} = $value;
                   13371:     }
                   13372:     #
1.646     raeburn  13373:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13374:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13375: }
                   13376: 
                   13377: ############################################################
                   13378: ############################################################
                   13379: 
                   13380: =pod
                   13381: 
1.648     raeburn  13382: =item * &DrawXYGraph()
1.137     matthew  13383: 
1.138     matthew  13384: Facilitates the plotting of data in an XY graph.
                   13385: Puts plot definition data into the users environment in order for 
                   13386: graph.png to plot it.  Returns an <img> tag for the plot.
                   13387: 
                   13388: Inputs:
                   13389: 
                   13390: =over 4
                   13391: 
                   13392: =item $Title: string, the title of the plot
                   13393: 
                   13394: =item $xlabel: string, text describing the X-axis of the plot
                   13395: 
                   13396: =item $ylabel: string, text describing the Y-axis of the plot
                   13397: 
                   13398: =item $Max: scalar, the maximum Y value to use in the plot
                   13399: If $Max is < any data point, the graph will not be rendered.
                   13400: 
                   13401: =item $colors: Array ref containing the hex color codes for the data to be 
                   13402: plotted in.  If undefined, default values will be used.
                   13403: 
                   13404: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13405: 
                   13406: =item $Ydata: Array ref containing Array refs.  
1.185     www      13407: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13408: 
                   13409: =item %Values: hash indicating or overriding any default values which are 
                   13410: passed to graph.png.  
                   13411: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13412: 
                   13413: =back
                   13414: 
                   13415: Returns:
                   13416: 
                   13417: An <img> tag which references graph.png and the appropriate identifying
                   13418: information for the plot.
                   13419: 
1.137     matthew  13420: =cut
                   13421: 
                   13422: ############################################################
                   13423: ############################################################
                   13424: sub DrawXYGraph {
                   13425:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13426:     #
                   13427:     # Create the identifier for the graph
                   13428:     my $identifier = &get_cgi_id();
                   13429:     my $id = 'cgi.'.$identifier;
                   13430:     #
                   13431:     $Title  = '' if (! defined($Title));
                   13432:     $xlabel = '' if (! defined($xlabel));
                   13433:     $ylabel = '' if (! defined($ylabel));
                   13434:     my %ValuesHash = 
                   13435:         (
1.369     www      13436:          $id.'.title'  => &escape($Title),
                   13437:          $id.'.xlabel' => &escape($xlabel),
                   13438:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13439:          $id.'.y_max_value'=> $Max,
                   13440:          $id.'.labels'     => join(',',@$Xlabels),
                   13441:          $id.'.PlotType'   => 'XY',
                   13442:          );
                   13443:     #
                   13444:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13445:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13446:     }
                   13447:     #
                   13448:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13449:         return '';
                   13450:     }
                   13451:     my $NumSets=1;
1.138     matthew  13452:     foreach my $array (@{$Ydata}){
1.137     matthew  13453:         next if (! ref($array));
                   13454:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13455:     }
1.138     matthew  13456:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13457:     #
                   13458:     # Deal with other parameters
                   13459:     while (my ($key,$value) = each(%Values)) {
                   13460:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13461:     }
                   13462:     #
1.646     raeburn  13463:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13464:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13465: }
                   13466: 
                   13467: ############################################################
                   13468: ############################################################
                   13469: 
                   13470: =pod
                   13471: 
1.648     raeburn  13472: =item * &DrawXYYGraph()
1.138     matthew  13473: 
                   13474: Facilitates the plotting of data in an XY graph with two Y axes.
                   13475: Puts plot definition data into the users environment in order for 
                   13476: graph.png to plot it.  Returns an <img> tag for the plot.
                   13477: 
                   13478: Inputs:
                   13479: 
                   13480: =over 4
                   13481: 
                   13482: =item $Title: string, the title of the plot
                   13483: 
                   13484: =item $xlabel: string, text describing the X-axis of the plot
                   13485: 
                   13486: =item $ylabel: string, text describing the Y-axis of the plot
                   13487: 
                   13488: =item $colors: Array ref containing the hex color codes for the data to be 
                   13489: plotted in.  If undefined, default values will be used.
                   13490: 
                   13491: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13492: 
                   13493: =item $Ydata1: The first data set
                   13494: 
                   13495: =item $Min1: The minimum value of the left Y-axis
                   13496: 
                   13497: =item $Max1: The maximum value of the left Y-axis
                   13498: 
                   13499: =item $Ydata2: The second data set
                   13500: 
                   13501: =item $Min2: The minimum value of the right Y-axis
                   13502: 
                   13503: =item $Max2: The maximum value of the left Y-axis
                   13504: 
                   13505: =item %Values: hash indicating or overriding any default values which are 
                   13506: passed to graph.png.  
                   13507: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13508: 
                   13509: =back
                   13510: 
                   13511: Returns:
                   13512: 
                   13513: An <img> tag which references graph.png and the appropriate identifying
                   13514: information for the plot.
1.136     matthew  13515: 
                   13516: =cut
                   13517: 
                   13518: ############################################################
                   13519: ############################################################
1.137     matthew  13520: sub DrawXYYGraph {
                   13521:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13522:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13523:     #
                   13524:     # Create the identifier for the graph
                   13525:     my $identifier = &get_cgi_id();
                   13526:     my $id = 'cgi.'.$identifier;
                   13527:     #
                   13528:     $Title  = '' if (! defined($Title));
                   13529:     $xlabel = '' if (! defined($xlabel));
                   13530:     $ylabel = '' if (! defined($ylabel));
                   13531:     my %ValuesHash = 
                   13532:         (
1.369     www      13533:          $id.'.title'  => &escape($Title),
                   13534:          $id.'.xlabel' => &escape($xlabel),
                   13535:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13536:          $id.'.labels' => join(',',@$Xlabels),
                   13537:          $id.'.PlotType' => 'XY',
                   13538:          $id.'.NumSets' => 2,
1.137     matthew  13539:          $id.'.two_axes' => 1,
                   13540:          $id.'.y1_max_value' => $Max1,
                   13541:          $id.'.y1_min_value' => $Min1,
                   13542:          $id.'.y2_max_value' => $Max2,
                   13543:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13544:          );
                   13545:     #
1.137     matthew  13546:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13547:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13548:     }
                   13549:     #
                   13550:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13551:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13552:         return '';
                   13553:     }
                   13554:     my $NumSets=1;
1.137     matthew  13555:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13556:         next if (! ref($array));
                   13557:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13558:     }
                   13559:     #
                   13560:     # Deal with other parameters
                   13561:     while (my ($key,$value) = each(%Values)) {
                   13562:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13563:     }
                   13564:     #
1.646     raeburn  13565:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13566:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13567: }
                   13568: 
                   13569: ############################################################
                   13570: ############################################################
                   13571: 
                   13572: =pod
                   13573: 
1.157     matthew  13574: =back 
                   13575: 
1.139     matthew  13576: =head1 Statistics helper routines?  
                   13577: 
                   13578: Bad place for them but what the hell.
                   13579: 
1.157     matthew  13580: =over 4
                   13581: 
1.648     raeburn  13582: =item * &chartlink()
1.139     matthew  13583: 
                   13584: Returns a link to the chart for a specific student.  
                   13585: 
                   13586: Inputs:
                   13587: 
                   13588: =over 4
                   13589: 
                   13590: =item $linktext: The text of the link
                   13591: 
                   13592: =item $sname: The students username
                   13593: 
                   13594: =item $sdomain: The students domain
                   13595: 
                   13596: =back
                   13597: 
1.157     matthew  13598: =back
                   13599: 
1.139     matthew  13600: =cut
                   13601: 
                   13602: ############################################################
                   13603: ############################################################
                   13604: sub chartlink {
                   13605:     my ($linktext, $sname, $sdomain) = @_;
                   13606:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13607:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13608:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13609:        '">'.$linktext.'</a>';
1.153     matthew  13610: }
                   13611: 
                   13612: #######################################################
                   13613: #######################################################
                   13614: 
                   13615: =pod
                   13616: 
                   13617: =head1 Course Environment Routines
1.157     matthew  13618: 
                   13619: =over 4
1.153     matthew  13620: 
1.648     raeburn  13621: =item * &restore_course_settings()
1.153     matthew  13622: 
1.648     raeburn  13623: =item * &store_course_settings()
1.153     matthew  13624: 
                   13625: Restores/Store indicated form parameters from the course environment.
                   13626: Will not overwrite existing values of the form parameters.
                   13627: 
                   13628: Inputs: 
                   13629: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13630: 
                   13631: a hash ref describing the data to be stored.  For example:
                   13632:    
                   13633: %Save_Parameters = ('Status' => 'scalar',
                   13634:     'chartoutputmode' => 'scalar',
                   13635:     'chartoutputdata' => 'scalar',
                   13636:     'Section' => 'array',
1.373     raeburn  13637:     'Group' => 'array',
1.153     matthew  13638:     'StudentData' => 'array',
                   13639:     'Maps' => 'array');
                   13640: 
                   13641: Returns: both routines return nothing
                   13642: 
1.631     raeburn  13643: =back
                   13644: 
1.153     matthew  13645: =cut
                   13646: 
                   13647: #######################################################
                   13648: #######################################################
                   13649: sub store_course_settings {
1.496     albertel 13650:     return &store_settings($env{'request.course.id'},@_);
                   13651: }
                   13652: 
                   13653: sub store_settings {
1.153     matthew  13654:     # save to the environment
                   13655:     # appenv the same items, just to be safe
1.300     albertel 13656:     my $udom  = $env{'user.domain'};
                   13657:     my $uname = $env{'user.name'};
1.496     albertel 13658:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13659:     my %SaveHash;
                   13660:     my %AppHash;
                   13661:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13662:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13663:         my $envname = 'environment.'.$basename;
1.258     albertel 13664:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13665:             # Save this value away
                   13666:             if ($type eq 'scalar' &&
1.258     albertel 13667:                 (! exists($env{$envname}) || 
                   13668:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13669:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13670:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13671:             } elsif ($type eq 'array') {
                   13672:                 my $stored_form;
1.258     albertel 13673:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13674:                     $stored_form = join(',',
                   13675:                                         map {
1.369     www      13676:                                             &escape($_);
1.258     albertel 13677:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13678:                 } else {
                   13679:                     $stored_form = 
1.369     www      13680:                         &escape($env{'form.'.$setting});
1.153     matthew  13681:                 }
                   13682:                 # Determine if the array contents are the same.
1.258     albertel 13683:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13684:                     $SaveHash{$basename} = $stored_form;
                   13685:                     $AppHash{$envname}   = $stored_form;
                   13686:                 }
                   13687:             }
                   13688:         }
                   13689:     }
                   13690:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13691:                                           $udom,$uname);
1.153     matthew  13692:     if ($put_result !~ /^(ok|delayed)/) {
                   13693:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13694:                                  'got error:'.$put_result);
                   13695:     }
                   13696:     # Make sure these settings stick around in this session, too
1.646     raeburn  13697:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13698:     return;
                   13699: }
                   13700: 
                   13701: sub restore_course_settings {
1.499     albertel 13702:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13703: }
                   13704: 
                   13705: sub restore_settings {
                   13706:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13707:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13708:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13709:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13710:             '.'.$setting;
1.258     albertel 13711:         if (exists($env{$envname})) {
1.153     matthew  13712:             if ($type eq 'scalar') {
1.258     albertel 13713:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13714:             } elsif ($type eq 'array') {
1.258     albertel 13715:                 $env{'form.'.$setting} = [ 
1.153     matthew  13716:                                            map { 
1.369     www      13717:                                                &unescape($_); 
1.258     albertel 13718:                                            } split(',',$env{$envname})
1.153     matthew  13719:                                            ];
                   13720:             }
                   13721:         }
                   13722:     }
1.127     matthew  13723: }
                   13724: 
1.618     raeburn  13725: #######################################################
                   13726: #######################################################
                   13727: 
                   13728: =pod
                   13729: 
                   13730: =head1 Domain E-mail Routines  
                   13731: 
                   13732: =over 4
                   13733: 
1.648     raeburn  13734: =item * &build_recipient_list()
1.618     raeburn  13735: 
1.1144    raeburn  13736: Build recipient lists for following types of e-mail:
1.766     raeburn  13737: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  13738: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13739: module change checking, student/employee ID conflict checks, as
                   13740: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13741: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13742: 
                   13743: Inputs:
1.619     raeburn  13744: defmail (scalar - email address of default recipient), 
1.1144    raeburn  13745: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13746: requestsmail, updatesmail, or idconflictsmail).
                   13747: 
1.619     raeburn  13748: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  13749: 
1.619     raeburn  13750: origmail (scalar - email address of recipient from loncapa.conf, 
                   13751: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  13752: 
1.655     raeburn  13753: Returns: comma separated list of addresses to which to send e-mail.
                   13754: 
                   13755: =back
1.618     raeburn  13756: 
                   13757: =cut
                   13758: 
                   13759: ############################################################
                   13760: ############################################################
                   13761: sub build_recipient_list {
1.619     raeburn  13762:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13763:     my @recipients;
                   13764:     my $otheremails;
                   13765:     my %domconfig =
                   13766:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13767:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13768:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13769:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13770:                 my @contacts = ('adminemail','supportemail');
                   13771:                 foreach my $item (@contacts) {
                   13772:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13773:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13774:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13775:                             push(@recipients,$addr);
                   13776:                         }
1.619     raeburn  13777:                     }
1.766     raeburn  13778:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13779:                 }
                   13780:             }
1.766     raeburn  13781:         } elsif ($origmail ne '') {
                   13782:             push(@recipients,$origmail);
1.618     raeburn  13783:         }
1.619     raeburn  13784:     } elsif ($origmail ne '') {
                   13785:         push(@recipients,$origmail);
1.618     raeburn  13786:     }
1.688     raeburn  13787:     if (defined($defmail)) {
                   13788:         if ($defmail ne '') {
                   13789:             push(@recipients,$defmail);
                   13790:         }
1.618     raeburn  13791:     }
                   13792:     if ($otheremails) {
1.619     raeburn  13793:         my @others;
                   13794:         if ($otheremails =~ /,/) {
                   13795:             @others = split(/,/,$otheremails);
1.618     raeburn  13796:         } else {
1.619     raeburn  13797:             push(@others,$otheremails);
                   13798:         }
                   13799:         foreach my $addr (@others) {
                   13800:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13801:                 push(@recipients,$addr);
                   13802:             }
1.618     raeburn  13803:         }
                   13804:     }
1.619     raeburn  13805:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13806:     return $recipientlist;
                   13807: }
                   13808: 
1.127     matthew  13809: ############################################################
                   13810: ############################################################
1.154     albertel 13811: 
1.655     raeburn  13812: =pod
                   13813: 
                   13814: =head1 Course Catalog Routines
                   13815: 
                   13816: =over 4
                   13817: 
                   13818: =item * &gather_categories()
                   13819: 
                   13820: Converts category definitions - keys of categories hash stored in  
                   13821: coursecategories in configuration.db on the primary library server in a 
                   13822: domain - to an array.  Also generates javascript and idx hash used to 
                   13823: generate Domain Coordinator interface for editing Course Categories.
                   13824: 
                   13825: Inputs:
1.663     raeburn  13826: 
1.655     raeburn  13827: categories (reference to hash of category definitions).
1.663     raeburn  13828: 
1.655     raeburn  13829: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13830:       categories and subcategories).
1.663     raeburn  13831: 
1.655     raeburn  13832: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13833:       editing Course Categories).
1.663     raeburn  13834: 
1.655     raeburn  13835: jsarray (reference to array of categories used to create Javascript arrays for
                   13836:          Domain Coordinator interface for editing Course Categories).
                   13837: 
                   13838: Returns: nothing
                   13839: 
                   13840: Side effects: populates cats, idx and jsarray. 
                   13841: 
                   13842: =cut
                   13843: 
                   13844: sub gather_categories {
                   13845:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13846:     my %counters;
                   13847:     my $num = 0;
                   13848:     foreach my $item (keys(%{$categories})) {
                   13849:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13850:         if ($container eq '' && $depth == 0) {
                   13851:             $cats->[$depth][$categories->{$item}] = $cat;
                   13852:         } else {
                   13853:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13854:         }
                   13855:         my ($escitem,$tail) = split(/:/,$item,2);
                   13856:         if ($counters{$tail} eq '') {
                   13857:             $counters{$tail} = $num;
                   13858:             $num ++;
                   13859:         }
                   13860:         if (ref($idx) eq 'HASH') {
                   13861:             $idx->{$item} = $counters{$tail};
                   13862:         }
                   13863:         if (ref($jsarray) eq 'ARRAY') {
                   13864:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13865:         }
                   13866:     }
                   13867:     return;
                   13868: }
                   13869: 
                   13870: =pod
                   13871: 
                   13872: =item * &extract_categories()
                   13873: 
                   13874: Used to generate breadcrumb trails for course categories.
                   13875: 
                   13876: Inputs:
1.663     raeburn  13877: 
1.655     raeburn  13878: categories (reference to hash of category definitions).
1.663     raeburn  13879: 
1.655     raeburn  13880: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13881:       categories and subcategories).
1.663     raeburn  13882: 
1.655     raeburn  13883: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13884: 
1.655     raeburn  13885: allitems (reference to hash - key is category key 
                   13886:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13887: 
1.655     raeburn  13888: idx (reference to hash of counters used in Domain Coordinator interface for
                   13889:       editing Course Categories).
1.663     raeburn  13890: 
1.655     raeburn  13891: jsarray (reference to array of categories used to create Javascript arrays for
                   13892:          Domain Coordinator interface for editing Course Categories).
                   13893: 
1.665     raeburn  13894: subcats (reference to hash of arrays containing all subcategories within each 
                   13895:          category, -recursive)
                   13896: 
1.655     raeburn  13897: Returns: nothing
                   13898: 
                   13899: Side effects: populates trails and allitems hash references.
                   13900: 
                   13901: =cut
                   13902: 
                   13903: sub extract_categories {
1.665     raeburn  13904:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13905:     if (ref($categories) eq 'HASH') {
                   13906:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13907:         if (ref($cats->[0]) eq 'ARRAY') {
                   13908:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13909:                 my $name = $cats->[0][$i];
                   13910:                 my $item = &escape($name).'::0';
                   13911:                 my $trailstr;
                   13912:                 if ($name eq 'instcode') {
                   13913:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13914:                 } elsif ($name eq 'communities') {
                   13915:                     $trailstr = &mt('Communities');
1.655     raeburn  13916:                 } else {
                   13917:                     $trailstr = $name;
                   13918:                 }
                   13919:                 if ($allitems->{$item} eq '') {
                   13920:                     push(@{$trails},$trailstr);
                   13921:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13922:                 }
                   13923:                 my @parents = ($name);
                   13924:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13925:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13926:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13927:                         if (ref($subcats) eq 'HASH') {
                   13928:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13929:                         }
                   13930:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13931:                     }
                   13932:                 } else {
                   13933:                     if (ref($subcats) eq 'HASH') {
                   13934:                         $subcats->{$item} = [];
1.655     raeburn  13935:                     }
                   13936:                 }
                   13937:             }
                   13938:         }
                   13939:     }
                   13940:     return;
                   13941: }
                   13942: 
                   13943: =pod
                   13944: 
1.1162    raeburn  13945: =item * &recurse_categories()
1.655     raeburn  13946: 
                   13947: Recursively used to generate breadcrumb trails for course categories.
                   13948: 
                   13949: Inputs:
1.663     raeburn  13950: 
1.655     raeburn  13951: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13952:       categories and subcategories).
1.663     raeburn  13953: 
1.655     raeburn  13954: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13955: 
                   13956: category (current course category, for which breadcrumb trail is being generated).
                   13957: 
                   13958: trails (reference to array of breadcrumb trails for each category).
                   13959: 
1.655     raeburn  13960: allitems (reference to hash - key is category key
                   13961:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13962: 
1.655     raeburn  13963: parents (array containing containers directories for current category, 
                   13964:          back to top level). 
                   13965: 
                   13966: Returns: nothing
                   13967: 
                   13968: Side effects: populates trails and allitems hash references
                   13969: 
                   13970: =cut
                   13971: 
                   13972: sub recurse_categories {
1.665     raeburn  13973:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13974:     my $shallower = $depth - 1;
                   13975:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13976:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13977:             my $name = $cats->[$depth]{$category}[$k];
                   13978:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13979:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13980:             if ($allitems->{$item} eq '') {
                   13981:                 push(@{$trails},$trailstr);
                   13982:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13983:             }
                   13984:             my $deeper = $depth+1;
                   13985:             push(@{$parents},$category);
1.665     raeburn  13986:             if (ref($subcats) eq 'HASH') {
                   13987:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13988:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13989:                     my $higher;
                   13990:                     if ($j > 0) {
                   13991:                         $higher = &escape($parents->[$j]).':'.
                   13992:                                   &escape($parents->[$j-1]).':'.$j;
                   13993:                     } else {
                   13994:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13995:                     }
                   13996:                     push(@{$subcats->{$higher}},$subcat);
                   13997:                 }
                   13998:             }
                   13999:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14000:                                 $subcats);
1.655     raeburn  14001:             pop(@{$parents});
                   14002:         }
                   14003:     } else {
                   14004:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14005:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14006:         if ($allitems->{$item} eq '') {
                   14007:             push(@{$trails},$trailstr);
                   14008:             $allitems->{$item} = scalar(@{$trails})-1;
                   14009:         }
                   14010:     }
                   14011:     return;
                   14012: }
                   14013: 
1.663     raeburn  14014: =pod
                   14015: 
1.1162    raeburn  14016: =item * &assign_categories_table()
1.663     raeburn  14017: 
                   14018: Create a datatable for display of hierarchical categories in a domain,
                   14019: with checkboxes to allow a course to be categorized. 
                   14020: 
                   14021: Inputs:
                   14022: 
                   14023: cathash - reference to hash of categories defined for the domain (from
                   14024:           configuration.db)
                   14025: 
                   14026: currcat - scalar with an & separated list of categories assigned to a course. 
                   14027: 
1.919     raeburn  14028: type    - scalar contains course type (Course or Community).
                   14029: 
1.663     raeburn  14030: Returns: $output (markup to be displayed) 
                   14031: 
                   14032: =cut
                   14033: 
                   14034: sub assign_categories_table {
1.919     raeburn  14035:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14036:     my $output;
                   14037:     if (ref($cathash) eq 'HASH') {
                   14038:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14039:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14040:         $maxdepth = scalar(@cats);
                   14041:         if (@cats > 0) {
                   14042:             my $itemcount = 0;
                   14043:             if (ref($cats[0]) eq 'ARRAY') {
                   14044:                 my @currcategories;
                   14045:                 if ($currcat ne '') {
                   14046:                     @currcategories = split('&',$currcat);
                   14047:                 }
1.919     raeburn  14048:                 my $table;
1.663     raeburn  14049:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14050:                     my $parent = $cats[0][$i];
1.919     raeburn  14051:                     next if ($parent eq 'instcode');
                   14052:                     if ($type eq 'Community') {
                   14053:                         next unless ($parent eq 'communities');
                   14054:                     } else {
                   14055:                         next if ($parent eq 'communities');
                   14056:                     }
1.663     raeburn  14057:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14058:                     my $item = &escape($parent).'::0';
                   14059:                     my $checked = '';
                   14060:                     if (@currcategories > 0) {
                   14061:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14062:                             $checked = ' checked="checked"';
1.663     raeburn  14063:                         }
                   14064:                     }
1.919     raeburn  14065:                     my $parent_title = $parent;
                   14066:                     if ($parent eq 'communities') {
                   14067:                         $parent_title = &mt('Communities');
                   14068:                     }
                   14069:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14070:                               '<input type="checkbox" name="usecategory" value="'.
                   14071:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14072:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14073:                     my $depth = 1;
                   14074:                     push(@path,$parent);
1.919     raeburn  14075:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14076:                     pop(@path);
1.919     raeburn  14077:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14078:                     $itemcount ++;
                   14079:                 }
1.919     raeburn  14080:                 if ($itemcount) {
                   14081:                     $output = &Apache::loncommon::start_data_table().
                   14082:                               $table.
                   14083:                               &Apache::loncommon::end_data_table();
                   14084:                 }
1.663     raeburn  14085:             }
                   14086:         }
                   14087:     }
                   14088:     return $output;
                   14089: }
                   14090: 
                   14091: =pod
                   14092: 
1.1162    raeburn  14093: =item * &assign_category_rows()
1.663     raeburn  14094: 
                   14095: Create a datatable row for display of nested categories in a domain,
                   14096: with checkboxes to allow a course to be categorized,called recursively.
                   14097: 
                   14098: Inputs:
                   14099: 
                   14100: itemcount - track row number for alternating colors
                   14101: 
                   14102: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14103:       categories and subcategories.
                   14104: 
                   14105: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14106: 
                   14107: parent - parent of current category item
                   14108: 
                   14109: path - Array containing all categories back up through the hierarchy from the
                   14110:        current category to the top level.
                   14111: 
                   14112: currcategories - reference to array of current categories assigned to the course
                   14113: 
                   14114: Returns: $output (markup to be displayed).
                   14115: 
                   14116: =cut
                   14117: 
                   14118: sub assign_category_rows {
                   14119:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14120:     my ($text,$name,$item,$chgstr);
                   14121:     if (ref($cats) eq 'ARRAY') {
                   14122:         my $maxdepth = scalar(@{$cats});
                   14123:         if (ref($cats->[$depth]) eq 'HASH') {
                   14124:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14125:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14126:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14127:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14128:                 for (my $j=0; $j<$numchildren; $j++) {
                   14129:                     $name = $cats->[$depth]{$parent}[$j];
                   14130:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14131:                     my $deeper = $depth+1;
                   14132:                     my $checked = '';
                   14133:                     if (ref($currcategories) eq 'ARRAY') {
                   14134:                         if (@{$currcategories} > 0) {
                   14135:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14136:                                 $checked = ' checked="checked"';
1.663     raeburn  14137:                             }
                   14138:                         }
                   14139:                     }
1.664     raeburn  14140:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14141:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14142:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14143:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14144:                              '</td><td>';
1.663     raeburn  14145:                     if (ref($path) eq 'ARRAY') {
                   14146:                         push(@{$path},$name);
                   14147:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14148:                         pop(@{$path});
                   14149:                     }
                   14150:                     $text .= '</td></tr>';
                   14151:                 }
                   14152:                 $text .= '</table></td>';
                   14153:             }
                   14154:         }
                   14155:     }
                   14156:     return $text;
                   14157: }
                   14158: 
1.1181    raeburn  14159: =pod
                   14160: 
                   14161: =back
                   14162: 
                   14163: =cut
                   14164: 
1.655     raeburn  14165: ############################################################
                   14166: ############################################################
                   14167: 
                   14168: 
1.443     albertel 14169: sub commit_customrole {
1.664     raeburn  14170:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14171:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14172:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14173:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14174:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14175:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14176:                  '</b><br />';
                   14177:     return $output;
                   14178: }
                   14179: 
                   14180: sub commit_standardrole {
1.1116    raeburn  14181:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14182:     my ($output,$logmsg,$linefeed);
                   14183:     if ($context eq 'auto') {
                   14184:         $linefeed = "\n";
                   14185:     } else {
                   14186:         $linefeed = "<br />\n";
                   14187:     }  
1.443     albertel 14188:     if ($three eq 'st') {
1.541     raeburn  14189:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14190:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14191:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14192:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14193:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14194:         } else {
1.541     raeburn  14195:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14196:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14197:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14198:             if ($context eq 'auto') {
                   14199:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14200:             } else {
                   14201:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14202:                &mt('Add to classlist').': <b>ok</b>';
                   14203:             }
                   14204:             $output .= $linefeed;
1.443     albertel 14205:         }
                   14206:     } else {
                   14207:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14208:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14209:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14210:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14211:         if ($context eq 'auto') {
                   14212:             $output .= $result.$linefeed;
                   14213:         } else {
                   14214:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14215:         }
1.443     albertel 14216:     }
                   14217:     return $output;
                   14218: }
                   14219: 
                   14220: sub commit_studentrole {
1.1116    raeburn  14221:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14222:         $credits) = @_;
1.626     raeburn  14223:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14224:     if ($context eq 'auto') {
                   14225:         $linefeed = "\n";
                   14226:     } else {
                   14227:         $linefeed = '<br />'."\n";
                   14228:     }
1.443     albertel 14229:     if (defined($one) && defined($two)) {
                   14230:         my $cid=$one.'_'.$two;
                   14231:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14232:         my $secchange = 0;
                   14233:         my $expire_role_result;
                   14234:         my $modify_section_result;
1.628     raeburn  14235:         if ($oldsec ne '-1') { 
                   14236:             if ($oldsec ne $sec) {
1.443     albertel 14237:                 $secchange = 1;
1.628     raeburn  14238:                 my $now = time;
1.443     albertel 14239:                 my $uurl='/'.$cid;
                   14240:                 $uurl=~s/\_/\//g;
                   14241:                 if ($oldsec) {
                   14242:                     $uurl.='/'.$oldsec;
                   14243:                 }
1.626     raeburn  14244:                 $oldsecurl = $uurl;
1.628     raeburn  14245:                 $expire_role_result = 
1.652     raeburn  14246:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14247:                 if ($env{'request.course.sec'} ne '') { 
                   14248:                     if ($expire_role_result eq 'refused') {
                   14249:                         my @roles = ('st');
                   14250:                         my @statuses = ('previous');
                   14251:                         my @roledoms = ($one);
                   14252:                         my $withsec = 1;
                   14253:                         my %roleshash = 
                   14254:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14255:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14256:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14257:                             my ($oldstart,$oldend) = 
                   14258:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14259:                             if ($oldend > 0 && $oldend <= $now) {
                   14260:                                 $expire_role_result = 'ok';
                   14261:                             }
                   14262:                         }
                   14263:                     }
                   14264:                 }
1.443     albertel 14265:                 $result = $expire_role_result;
                   14266:             }
                   14267:         }
                   14268:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14269:             $modify_section_result = 
                   14270:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14271:                                                            undef,undef,undef,$sec,
                   14272:                                                            $end,$start,'','',$cid,
                   14273:                                                            '',$context,$credits);
1.443     albertel 14274:             if ($modify_section_result =~ /^ok/) {
                   14275:                 if ($secchange == 1) {
1.628     raeburn  14276:                     if ($sec eq '') {
                   14277:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14278:                     } else {
                   14279:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14280:                     }
1.443     albertel 14281:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14282:                     if ($sec eq '') {
                   14283:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14284:                     } else {
                   14285:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14286:                     }
1.443     albertel 14287:                 } else {
1.628     raeburn  14288:                     if ($sec eq '') {
                   14289:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14290:                     } else {
                   14291:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14292:                     }
1.443     albertel 14293:                 }
                   14294:             } else {
1.1115    raeburn  14295:                 if ($secchange) { 
1.628     raeburn  14296:                     $$logmsg .= &mt('Error when attempting section change for [_1] from old section "[_2]" to new section: "[_3]" in course [_4] -error:',$uname,$oldsec,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14297:                 } else {
                   14298:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14299:                 }
1.443     albertel 14300:             }
                   14301:             $result = $modify_section_result;
                   14302:         } elsif ($secchange == 1) {
1.628     raeburn  14303:             if ($oldsec eq '') {
1.1103    raeburn  14304:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
1.628     raeburn  14305:             } else {
                   14306:                 $$logmsg .= &mt('Error when attempting to expire existing role for [_1] in section [_2] in course [_3] -error: ',$uname,$oldsec,$cid).' '.$expire_role_result.$linefeed;
                   14307:             }
1.626     raeburn  14308:             if ($expire_role_result eq 'refused') {
                   14309:                 my $newsecurl = '/'.$cid;
                   14310:                 $newsecurl =~ s/\_/\//g;
                   14311:                 if ($sec ne '') {
                   14312:                     $newsecurl.='/'.$sec;
                   14313:                 }
                   14314:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14315:                     if ($sec eq '') {
                   14316:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments unaffiliated with any section.',$sec).$linefeed;
                   14317:                     } else {
                   14318:                         $$logmsg .= &mt('Although your current role has privileges to add students to section "[_1]", you do not have privileges to modify existing enrollments in other sections.',$sec).$linefeed;
                   14319:                     }
                   14320:                 }
                   14321:             }
1.443     albertel 14322:         }
                   14323:     } else {
1.626     raeburn  14324:         $$logmsg .= &mt('Incomplete course id defined.').$linefeed.&mt('Addition of user [_1] from domain [_2] to course [_3], section [_4] not completed.',$uname,$udom,$one.'_'.$two,$sec).$linefeed;
1.443     albertel 14325:         $result = "error: incomplete course id\n";
                   14326:     }
                   14327:     return $result;
                   14328: }
                   14329: 
1.1108    raeburn  14330: sub show_role_extent {
                   14331:     my ($scope,$context,$role) = @_;
                   14332:     $scope =~ s{^/}{};
                   14333:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14334:     push(@courseroles,'co');
                   14335:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14336:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14337:         $scope =~ s{/}{_};
                   14338:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14339:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14340:         my ($audom,$auname) = split(/\//,$scope);
                   14341:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14342:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14343:     } else {
                   14344:         $scope =~ s{/$}{};
                   14345:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14346:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14347:     }
                   14348: }
                   14349: 
1.443     albertel 14350: ############################################################
                   14351: ############################################################
                   14352: 
1.566     albertel 14353: sub check_clone {
1.578     raeburn  14354:     my ($args,$linefeed) = @_;
1.566     albertel 14355:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14356:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14357:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14358:     my $clonemsg;
                   14359:     my $can_clone = 0;
1.944     raeburn  14360:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14361:     if ($lctype ne 'community') {
                   14362:         $lctype = 'course';
                   14363:     }
1.566     albertel 14364:     if ($clonehome eq 'no_host') {
1.944     raeburn  14365:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14366:             $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a non-existent community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   14367:         } else {
                   14368:             $clonemsg = &mt('No new course created.').$linefeed.&mt('A new course could not be cloned from the specified original - [_1] - because it is a non-existent course.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   14369:         }     
1.566     albertel 14370:     } else {
                   14371: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14372:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14373:             if ($clonedesc{'type'} ne 'Community') {
                   14374:                  $clonemsg = &mt('No new community created.').$linefeed.&mt('A new community could not be cloned from the specified original - [_1] - because it is a course not a community.',$args->{'clonecourse'}.':'.$args->{'clonedomain'});
                   14375:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14376:             }
                   14377:         }
1.882     raeburn  14378: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14379:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14380: 	    $can_clone = 1;
                   14381: 	} else {
                   14382: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   14383: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   14384: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  14385:             if (grep(/^\*$/,@cloners)) {
                   14386:                 $can_clone = 1;
                   14387:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14388:                 $can_clone = 1;
                   14389:             } else {
1.908     raeburn  14390:                 my $ccrole = 'cc';
1.944     raeburn  14391:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14392:                     $ccrole = 'co';
                   14393:                 }
1.578     raeburn  14394: 	        my %roleshash =
                   14395: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14396: 					 $args->{'ccdomain'},
1.908     raeburn  14397:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  14398: 					 [$args->{'clonedomain'}]);
1.908     raeburn  14399: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  14400:                     $can_clone = 1;
                   14401:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   14402:                     $can_clone = 1;
                   14403:                 } else {
1.944     raeburn  14404:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14405:                         $clonemsg = &mt('No new community created.').$linefeed.&mt('The new community could not be cloned from the existing community because the new community owner ([_1]) does not have cloning rights in the existing community ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   14406:                     } else {
                   14407:                         $clonemsg = &mt('No new course created.').$linefeed.&mt('The new course could not be cloned from the existing course because the new course owner ([_1]) does not have cloning rights in the existing course ([_2]).',$args->{'ccuname'}.':'.$args->{'ccdomain'},$clonedesc{'description'});
                   14408:                     }
1.578     raeburn  14409: 	        }
1.566     albertel 14410: 	    }
1.578     raeburn  14411:         }
1.566     albertel 14412:     }
                   14413:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14414: }
                   14415: 
1.444     albertel 14416: sub construct_course {
1.1166    raeburn  14417:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14418:     my $outcome;
1.541     raeburn  14419:     my $linefeed =  '<br />'."\n";
                   14420:     if ($context eq 'auto') {
                   14421:         $linefeed = "\n";
                   14422:     }
1.566     albertel 14423: 
                   14424: #
                   14425: # Are we cloning?
                   14426: #
                   14427:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14428:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14429: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14430: 	if ($context ne 'auto') {
1.578     raeburn  14431:             if ($clonemsg ne '') {
                   14432: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14433:             }
1.566     albertel 14434: 	}
                   14435: 	$outcome .= $clonemsg.$linefeed;
                   14436: 
                   14437:         if (!$can_clone) {
                   14438: 	    return (0,$outcome);
                   14439: 	}
                   14440:     }
                   14441: 
1.444     albertel 14442: #
                   14443: # Open course
                   14444: #
                   14445:     my $crstype = lc($args->{'crstype'});
                   14446:     my %cenv=();
                   14447:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14448:                                              $args->{'cdescr'},
                   14449:                                              $args->{'curl'},
                   14450:                                              $args->{'course_home'},
                   14451:                                              $args->{'nonstandard'},
                   14452:                                              $args->{'crscode'},
                   14453:                                              $args->{'ccuname'}.':'.
                   14454:                                              $args->{'ccdomain'},
1.882     raeburn  14455:                                              $args->{'crstype'},
1.885     raeburn  14456:                                              $cnum,$context,$category);
1.444     albertel 14457: 
                   14458:     # Note: The testing routines depend on this being output; see 
                   14459:     # Utils::Course. This needs to at least be output as a comment
                   14460:     # if anyone ever decides to not show this, and Utils::Course::new
                   14461:     # will need to be suitably modified.
1.541     raeburn  14462:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14463:     if ($$courseid =~ /^error:/) {
                   14464:         return (0,$outcome);
                   14465:     }
                   14466: 
1.444     albertel 14467: #
                   14468: # Check if created correctly
                   14469: #
1.479     albertel 14470:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14471:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14472:     if ($crsuhome eq 'no_host') {
                   14473:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14474:         return (0,$outcome);
                   14475:     }
1.541     raeburn  14476:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14477: 
1.444     albertel 14478: #
1.566     albertel 14479: # Do the cloning
                   14480: #   
                   14481:     if ($can_clone && $cloneid) {
                   14482: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14483: 	if ($context ne 'auto') {
                   14484: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14485: 	}
                   14486: 	$outcome .= $clonemsg.$linefeed;
                   14487: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14488: # Copy all files
1.637     www      14489: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14490: # Restore URL
1.566     albertel 14491: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14492: # Restore title
1.566     albertel 14493: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14494: # Restore creation date, creator and creation context.
                   14495:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14496:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14497:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14498: # Mark as cloned
1.566     albertel 14499: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14500: # Need to clone grading mode
                   14501:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14502:         $cenv{'grading'}=$newenv{'grading'};
                   14503: # Do not clone these environment entries
                   14504:         &Apache::lonnet::del('environment',
                   14505:                   ['default_enrollment_start_date',
                   14506:                    'default_enrollment_end_date',
                   14507:                    'question.email',
                   14508:                    'policy.email',
                   14509:                    'comment.email',
                   14510:                    'pch.users.denied',
1.725     raeburn  14511:                    'plc.users.denied',
                   14512:                    'hidefromcat',
1.1121    raeburn  14513:                    'checkforpriv',
1.1166    raeburn  14514:                    'categories',
                   14515:                    'internal.uniquecode'],
1.638     www      14516:                    $$crsudom,$$crsunum);
1.1170    raeburn  14517:         if ($args->{'textbook'}) {
                   14518:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14519:         }
1.444     albertel 14520:     }
1.566     albertel 14521: 
1.444     albertel 14522: #
                   14523: # Set environment (will override cloned, if existing)
                   14524: #
                   14525:     my @sections = ();
                   14526:     my @xlists = ();
                   14527:     if ($args->{'crstype'}) {
                   14528:         $cenv{'type'}=$args->{'crstype'};
                   14529:     }
                   14530:     if ($args->{'crsid'}) {
                   14531:         $cenv{'courseid'}=$args->{'crsid'};
                   14532:     }
                   14533:     if ($args->{'crscode'}) {
                   14534:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14535:     }
                   14536:     if ($args->{'crsquota'} ne '') {
                   14537:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14538:     } else {
                   14539:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14540:     }
                   14541:     if ($args->{'ccuname'}) {
                   14542:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14543:                                         ':'.$args->{'ccdomain'};
                   14544:     } else {
                   14545:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14546:     }
1.1116    raeburn  14547:     if ($args->{'defaultcredits'}) {
                   14548:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14549:     }
1.444     albertel 14550:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14551:     if ($args->{'crssections'}) {
                   14552:         $cenv{'internal.sectionnums'} = '';
                   14553:         if ($args->{'crssections'} =~ m/,/) {
                   14554:             @sections = split/,/,$args->{'crssections'};
                   14555:         } else {
                   14556:             $sections[0] = $args->{'crssections'};
                   14557:         }
                   14558:         if (@sections > 0) {
                   14559:             foreach my $item (@sections) {
                   14560:                 my ($sec,$gp) = split/:/,$item;
                   14561:                 my $class = $args->{'crscode'}.$sec;
                   14562:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14563:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14564:                 unless ($addcheck eq 'ok') {
                   14565:                     push @badclasses, $class;
                   14566:                 }
                   14567:             }
                   14568:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14569:         }
                   14570:     }
                   14571: # do not hide course coordinator from staff listing, 
                   14572: # even if privileged
                   14573:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14574: # add course coordinator's domain to domains to check for privileged users
                   14575: # if different to course domain
                   14576:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14577:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14578:     }
1.444     albertel 14579: # add crosslistings
                   14580:     if ($args->{'crsxlist'}) {
                   14581:         $cenv{'internal.crosslistings'}='';
                   14582:         if ($args->{'crsxlist'} =~ m/,/) {
                   14583:             @xlists = split/,/,$args->{'crsxlist'};
                   14584:         } else {
                   14585:             $xlists[0] = $args->{'crsxlist'};
                   14586:         }
                   14587:         if (@xlists > 0) {
                   14588:             foreach my $item (@xlists) {
                   14589:                 my ($xl,$gp) = split/:/,$item;
                   14590:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14591:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14592:                 unless ($addcheck eq 'ok') {
                   14593:                     push @badclasses, $xl;
                   14594:                 }
                   14595:             }
                   14596:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14597:         }
                   14598:     }
                   14599:     if ($args->{'autoadds'}) {
                   14600:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14601:     }
                   14602:     if ($args->{'autodrops'}) {
                   14603:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14604:     }
                   14605: # check for notification of enrollment changes
                   14606:     my @notified = ();
                   14607:     if ($args->{'notify_owner'}) {
                   14608:         if ($args->{'ccuname'} ne '') {
                   14609:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14610:         }
                   14611:     }
                   14612:     if ($args->{'notify_dc'}) {
                   14613:         if ($uname ne '') { 
1.630     raeburn  14614:             push(@notified,$uname.':'.$udom);
1.444     albertel 14615:         }
                   14616:     }
                   14617:     if (@notified > 0) {
                   14618:         my $notifylist;
                   14619:         if (@notified > 1) {
                   14620:             $notifylist = join(',',@notified);
                   14621:         } else {
                   14622:             $notifylist = $notified[0];
                   14623:         }
                   14624:         $cenv{'internal.notifylist'} = $notifylist;
                   14625:     }
                   14626:     if (@badclasses > 0) {
                   14627:         my %lt=&Apache::lonlocal::texthash(
                   14628:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.  However, if automated course roster updates are enabled for this class, these particular sections/crosslistings will not contribute towards enrollment, because the user identified as the course owner for this LON-CAPA course',
                   14629:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14630:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14631:         );
1.541     raeburn  14632:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14633:                            ' ('.$lt{'adby'}.')';
                   14634:         if ($context eq 'auto') {
                   14635:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14636:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14637:             foreach my $item (@badclasses) {
                   14638:                 if ($context eq 'auto') {
                   14639:                     $outcome .= " - $item\n";
                   14640:                 } else {
                   14641:                     $outcome .= "<li>$item</li>\n";
                   14642:                 }
                   14643:             }
                   14644:             if ($context eq 'auto') {
                   14645:                 $outcome .= $linefeed;
                   14646:             } else {
1.566     albertel 14647:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14648:             }
                   14649:         } 
1.444     albertel 14650:     }
                   14651:     if ($args->{'no_end_date'}) {
                   14652:         $args->{'endaccess'} = 0;
                   14653:     }
                   14654:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14655:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14656:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14657:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14658:     if ($args->{'showphotos'}) {
                   14659:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14660:     }
                   14661:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14662:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14663:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14664:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14665:             my $krb_msg = &mt('As you did not include the default Kerberos domain to be used for authentication in this class, the institutional data used by the automated enrollment process must include the Kerberos domain for each new student'); 
                   14666:             if ($context eq 'auto') {
                   14667:                 $outcome .= $krb_msg;
                   14668:             } else {
1.566     albertel 14669:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14670:             }
                   14671:             $outcome .= $linefeed;
1.444     albertel 14672:         }
                   14673:     }
                   14674:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14675:        if ($args->{'setpolicy'}) {
                   14676:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14677:        }
                   14678:        if ($args->{'setcontent'}) {
                   14679:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14680:        }
                   14681:     }
                   14682:     if ($args->{'reshome'}) {
                   14683: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14684: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14685:     }
                   14686: #
                   14687: # course has keyed access
                   14688: #
                   14689:     if ($args->{'setkeys'}) {
                   14690:        $cenv{'keyaccess'}='yes';
                   14691:     }
                   14692: # if specified, key authority is not course, but user
                   14693: # only active if keyaccess is yes
                   14694:     if ($args->{'keyauth'}) {
1.487     albertel 14695: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14696: 	$user = &LONCAPA::clean_username($user);
                   14697: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14698: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14699: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14700: 	}
                   14701:     }
                   14702: 
1.1166    raeburn  14703: #
1.1167    raeburn  14704: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  14705: #
                   14706:     if ($args->{'uniquecode'}) {
                   14707:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14708:         if ($code) {
                   14709:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  14710:             my %crsinfo =
                   14711:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14712:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14713:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14714:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14715:             } 
1.1166    raeburn  14716:             if (ref($coderef)) {
                   14717:                 $$coderef = $code;
                   14718:             }
                   14719:         }
                   14720:     }
                   14721: 
1.444     albertel 14722:     if ($args->{'disresdis'}) {
                   14723:         $cenv{'pch.roles.denied'}='st';
                   14724:     }
                   14725:     if ($args->{'disablechat'}) {
                   14726:         $cenv{'plc.roles.denied'}='st';
                   14727:     }
                   14728: 
                   14729:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14730:     # course
                   14731:     $cenv{'course.helper.not.run'} = 1;
                   14732:     #
                   14733:     # Use new Randomseed
                   14734:     #
                   14735:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14736:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14737:     #
                   14738:     # The encryption code and receipt prefix for this course
                   14739:     #
                   14740:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14741:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14742:     #
                   14743:     # By default, use standard grading
                   14744:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14745: 
1.541     raeburn  14746:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14747:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14748: #
                   14749: # Open all assignments
                   14750: #
                   14751:     if ($args->{'openall'}) {
                   14752:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14753:        my %storecontent = ($storeunder         => time,
                   14754:                            $storeunder.'.type' => 'date_start');
                   14755:        
                   14756:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14757:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14758:    }
                   14759: #
                   14760: # Set first page
                   14761: #
                   14762:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14763: 	    || ($cloneid)) {
1.445     albertel 14764: 	use LONCAPA::map;
1.444     albertel 14765: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14766: 
                   14767: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14768:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14769: 
1.444     albertel 14770:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14771:         my $title; my $url;
                   14772:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14773: 	    $title=&mt('Syllabus');
1.444     albertel 14774:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14775:         } else {
1.963     raeburn  14776:             $title=&mt('Table of Contents');
1.444     albertel 14777:             $url='/adm/navmaps';
                   14778:         }
1.445     albertel 14779: 
                   14780:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14781: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14782: 
                   14783: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14784:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14785:     }
1.566     albertel 14786: 
                   14787:     return (1,$outcome);
1.444     albertel 14788: }
                   14789: 
1.1166    raeburn  14790: sub make_unique_code {
                   14791:     my ($cdom,$cnum) = @_;
                   14792:     # get lock on uniquecodes db
                   14793:     my $lockhash = {
                   14794:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14795:                                                   ':'.$env{'user.domain'},
                   14796:                    };
                   14797:     my $tries = 0;
                   14798:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14799:     my ($code,$error);
                   14800:   
                   14801:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14802:         $tries ++;
                   14803:         sleep 1;
                   14804:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14805:     }
                   14806:     if ($gotlock eq 'ok') {
                   14807:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14808:         my $gotcode;
                   14809:         my $attempts = 0;
                   14810:         while ((!$gotcode) && ($attempts < 100)) {
                   14811:             $code = &generate_code();
                   14812:             if (!exists($currcodes{$code})) {
                   14813:                 $gotcode = 1;
                   14814:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14815:                     $error = 'nostore';
                   14816:                 }
                   14817:             }
                   14818:             $attempts ++;
                   14819:         }
                   14820:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14821:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14822:     } else {
                   14823:         $error = 'nolock';
                   14824:     }
                   14825:     return ($code,$error);
                   14826: }
                   14827: 
                   14828: sub generate_code {
                   14829:     my $code;
                   14830:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14831:     for (my $i=0; $i<6; $i++) {
                   14832:         my $lettnum = int (rand 2);
                   14833:         my $item = '';
                   14834:         if ($lettnum) {
                   14835:             $item = $letts[int( rand(18) )];
                   14836:         } else {
                   14837:             $item = 1+int( rand(8) );
                   14838:         }
                   14839:         $code .= $item;
                   14840:     }
                   14841:     return $code;
                   14842: }
                   14843: 
1.444     albertel 14844: ############################################################
                   14845: ############################################################
                   14846: 
1.953     droeschl 14847: #SD
                   14848: # only Community and Course, or anything else?
1.378     raeburn  14849: sub course_type {
                   14850:     my ($cid) = @_;
                   14851:     if (!defined($cid)) {
                   14852:         $cid = $env{'request.course.id'};
                   14853:     }
1.404     albertel 14854:     if (defined($env{'course.'.$cid.'.type'})) {
                   14855:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14856:     } else {
                   14857:         return 'Course';
1.377     raeburn  14858:     }
                   14859: }
1.156     albertel 14860: 
1.406     raeburn  14861: sub group_term {
                   14862:     my $crstype = &course_type();
                   14863:     my %names = (
                   14864:                   'Course' => 'group',
1.865     raeburn  14865:                   'Community' => 'group',
1.406     raeburn  14866:                 );
                   14867:     return $names{$crstype};
                   14868: }
                   14869: 
1.902     raeburn  14870: sub course_types {
1.1165    raeburn  14871:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14872:     my %typename = (
                   14873:                          official   => 'Official course',
                   14874:                          unofficial => 'Unofficial course',
                   14875:                          community  => 'Community',
1.1165    raeburn  14876:                          textbook   => 'Textbook course',
1.902     raeburn  14877:                    );
                   14878:     return (\@types,\%typename);
                   14879: }
                   14880: 
1.156     albertel 14881: sub icon {
                   14882:     my ($file)=@_;
1.505     albertel 14883:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14884:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14885:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14886:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14887: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14888: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14889: 	            $curfext.".gif") {
                   14890: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14891: 		$curfext.".gif";
                   14892: 	}
                   14893:     }
1.249     albertel 14894:     return &lonhttpdurl($iconname);
1.154     albertel 14895: } 
1.84      albertel 14896: 
1.575     albertel 14897: sub lonhttpdurl {
1.692     www      14898: #
                   14899: # Had been used for "small fry" static images on separate port 8080.
                   14900: # Modify here if lightweight http functionality desired again.
                   14901: # Currently eliminated due to increasing firewall issues.
                   14902: #
1.575     albertel 14903:     my ($url)=@_;
1.692     www      14904:     return $url;
1.215     albertel 14905: }
                   14906: 
1.213     albertel 14907: sub connection_aborted {
                   14908:     my ($r)=@_;
                   14909:     $r->print(" ");$r->rflush();
                   14910:     my $c = $r->connection;
                   14911:     return $c->aborted();
                   14912: }
                   14913: 
1.221     foxr     14914: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14915: #    strings as 'strings'.
                   14916: sub escape_single {
1.221     foxr     14917:     my ($input) = @_;
1.223     albertel 14918:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14919:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14920:     return $input;
                   14921: }
1.223     albertel 14922: 
1.222     foxr     14923: #  Same as escape_single, but escape's "'s  This 
                   14924: #  can be used for  "strings"
                   14925: sub escape_double {
                   14926:     my ($input) = @_;
                   14927:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14928:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14929:     return $input;
                   14930: }
1.223     albertel 14931:  
1.222     foxr     14932: #   Escapes the last element of a full URL.
                   14933: sub escape_url {
                   14934:     my ($url)   = @_;
1.238     raeburn  14935:     my @urlslices = split(/\//, $url,-1);
1.369     www      14936:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  14937:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14938: }
1.462     albertel 14939: 
1.820     raeburn  14940: sub compare_arrays {
                   14941:     my ($arrayref1,$arrayref2) = @_;
                   14942:     my (@difference,%count);
                   14943:     @difference = ();
                   14944:     %count = ();
                   14945:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14946:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14947:         foreach my $element (keys(%count)) {
                   14948:             if ($count{$element} == 1) {
                   14949:                 push(@difference,$element);
                   14950:             }
                   14951:         }
                   14952:     }
                   14953:     return @difference;
                   14954: }
                   14955: 
1.817     bisitz   14956: # -------------------------------------------------------- Initialize user login
1.462     albertel 14957: sub init_user_environment {
1.463     albertel 14958:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14959:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14960: 
                   14961:     my $public=($username eq 'public' && $domain eq 'public');
                   14962: 
                   14963: # See if old ID present, if so, remove
                   14964: 
1.1062    raeburn  14965:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14966:     my $now=time;
                   14967: 
                   14968:     if ($public) {
                   14969: 	my $max_public=100;
                   14970: 	my $oldest;
                   14971: 	my $oldest_time=0;
                   14972: 	for(my $next=1;$next<=$max_public;$next++) {
                   14973: 	    if (-e $lonids."/publicuser_$next.id") {
                   14974: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14975: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14976: 		    $oldest_time=$mtime;
                   14977: 		    $oldest=$next;
                   14978: 		}
                   14979: 	    } else {
                   14980: 		$cookie="publicuser_$next";
                   14981: 		last;
                   14982: 	    }
                   14983: 	}
                   14984: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14985:     } else {
1.463     albertel 14986: 	# if this isn't a robot, kill any existing non-robot sessions
                   14987: 	if (!$args->{'robot'}) {
                   14988: 	    opendir(DIR,$lonids);
                   14989: 	    while ($filename=readdir(DIR)) {
                   14990: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14991: 		    unlink($lonids.'/'.$filename);
                   14992: 		}
1.462     albertel 14993: 	    }
1.463     albertel 14994: 	    closedir(DIR);
1.1204    raeburn  14995: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   14996:             my $namespace = 'nohist_courseeditor';
                   14997:             my $lockingkey = 'paste'."\0".'locked_num';
                   14998:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   14999:                                                 $domain,$username);
                   15000:             if (exists($lockhash{$lockingkey})) {
                   15001:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15002:                 unless ($delresult eq 'ok') {
                   15003:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15004:                 }
                   15005:             }
1.462     albertel 15006: 	}
                   15007: # Give them a new cookie
1.463     albertel 15008: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15009: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15010: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15011:     
                   15012: # Initialize roles
                   15013: 
1.1062    raeburn  15014: 	($userroles,$firstaccenv,$timerintenv) = 
                   15015:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15016:     }
                   15017: # ------------------------------------ Check browser type and MathML capability
                   15018: 
1.1194    raeburn  15019:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15020:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15021: 
                   15022: # ------------------------------------------------------------- Get environment
                   15023: 
                   15024:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15025:     my ($tmp) = keys(%userenv);
                   15026:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15027:     } else {
                   15028: 	undef(%userenv);
                   15029:     }
                   15030:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15031: 	$form->{'interface'}=$userenv{'interface'};
                   15032:     }
                   15033:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15034: 
                   15035: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15036:     foreach my $option ('interface','localpath','localres') {
                   15037:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15038:     }
                   15039: # --------------------------------------------------------- Write first profile
                   15040: 
                   15041:     {
                   15042: 	my %initial_env = 
                   15043: 	    ("user.name"          => $username,
                   15044: 	     "user.domain"        => $domain,
                   15045: 	     "user.home"          => $authhost,
                   15046: 	     "browser.type"       => $clientbrowser,
                   15047: 	     "browser.version"    => $clientversion,
                   15048: 	     "browser.mathml"     => $clientmathml,
                   15049: 	     "browser.unicode"    => $clientunicode,
                   15050: 	     "browser.os"         => $clientos,
1.1137    raeburn  15051:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15052:              "browser.info"       => $clientinfo,
1.1194    raeburn  15053:              "browser.osversion"  => $clientosversion,
1.462     albertel 15054: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15055: 	     "request.course.fn"  => '',
                   15056: 	     "request.course.uri" => '',
                   15057: 	     "request.course.sec" => '',
                   15058: 	     "request.role"       => 'cm',
                   15059: 	     "request.role.adv"   => $env{'user.adv'},
                   15060: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15061: 
                   15062:         if ($form->{'localpath'}) {
                   15063: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15064: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15065:         }
                   15066: 	
                   15067: 	if ($form->{'interface'}) {
                   15068: 	    $form->{'interface'}=~s/\W//gs;
                   15069: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15070: 	    $env{'browser.interface'}=$form->{'interface'};
                   15071: 	}
                   15072: 
1.1157    raeburn  15073:         if ($form->{'iptoken'}) {
                   15074:             my $lonhost = $r->dir_config('lonHostID');
                   15075:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15076:             $env{'user.noloadbalance'} = $lonhost;
                   15077:         }
                   15078: 
1.981     raeburn  15079:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15080:         my %domdef;
                   15081:         unless ($domain eq 'public') {
                   15082:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15083:         }
1.980     raeburn  15084: 
1.1081    raeburn  15085:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15086:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15087:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15088:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15089:         }
                   15090: 
1.1165    raeburn  15091:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15092:             $userenv{'canrequest.'.$crstype} =
                   15093:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15094:                                                   'reload','requestcourses',
                   15095:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15096:         }
                   15097: 
1.1092    raeburn  15098:         $userenv{'canrequest.author'} =
                   15099:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15100:                                         'reload','requestauthor',
                   15101:                                         \%userenv,\%domdef,\%is_adv);
                   15102:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15103:                                              $domain,$username);
                   15104:         my $reqstatus = $reqauthor{'author_status'};
                   15105:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15106:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15107:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15108:                                                   $reqauthor{'author'}{'timestamp'};
                   15109:             }
                   15110:         }
                   15111: 
1.462     albertel 15112: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15113: 
1.462     albertel 15114: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15115: 		 &GDBM_WRCREAT(),0640)) {
                   15116: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15117: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15118: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15119:             if (ref($firstaccenv) eq 'HASH') {
                   15120:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15121:             }
                   15122:             if (ref($timerintenv) eq 'HASH') {
                   15123:                 &_add_to_env(\%disk_env,$timerintenv);
                   15124:             }
1.463     albertel 15125: 	    if (ref($args->{'extra_env'})) {
                   15126: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15127: 	    }
1.462     albertel 15128: 	    untie(%disk_env);
                   15129: 	} else {
1.705     tempelho 15130: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15131: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15132: 	    return 'error: '.$!;
                   15133: 	}
                   15134:     }
                   15135:     $env{'request.role'}='cm';
                   15136:     $env{'request.role.adv'}=$env{'user.adv'};
                   15137:     $env{'browser.type'}=$clientbrowser;
                   15138: 
                   15139:     return $cookie;
                   15140: 
                   15141: }
                   15142: 
                   15143: sub _add_to_env {
                   15144:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15145:     if (ref($env_data) eq 'HASH') {
                   15146:         while (my ($key,$value) = each(%$env_data)) {
                   15147: 	    $idf->{$prefix.$key} = $value;
                   15148: 	    $env{$prefix.$key}   = $value;
                   15149:         }
1.462     albertel 15150:     }
                   15151: }
                   15152: 
1.685     tempelho 15153: # --- Get the symbolic name of a problem and the url
                   15154: sub get_symb {
                   15155:     my ($request,$silent) = @_;
1.726     raeburn  15156:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15157:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15158:     if ($symb eq '') {
                   15159:         if (!$silent) {
1.1071    raeburn  15160:             if (ref($request)) { 
                   15161:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15162:             }
1.685     tempelho 15163:             return ();
                   15164:         }
                   15165:     }
                   15166:     &Apache::lonenc::check_decrypt(\$symb);
                   15167:     return ($symb);
                   15168: }
                   15169: 
                   15170: # --------------------------------------------------------------Get annotation
                   15171: 
                   15172: sub get_annotation {
                   15173:     my ($symb,$enc) = @_;
                   15174: 
                   15175:     my $key = $symb;
                   15176:     if (!$enc) {
                   15177:         $key =
                   15178:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15179:     }
                   15180:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15181:     return $annotation{$key};
                   15182: }
                   15183: 
                   15184: sub clean_symb {
1.731     raeburn  15185:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15186: 
                   15187:     &Apache::lonenc::check_decrypt(\$symb);
                   15188:     my $enc = $env{'request.enc'};
1.731     raeburn  15189:     if ($delete_enc) {
1.730     raeburn  15190:         delete($env{'request.enc'});
                   15191:     }
1.685     tempelho 15192: 
                   15193:     return ($symb,$enc);
                   15194: }
1.462     albertel 15195: 
1.1181    raeburn  15196: ############################################################
                   15197: ############################################################
                   15198: 
                   15199: =pod
                   15200: 
                   15201: =head1 Routines for building display used to search for courses
                   15202: 
                   15203: 
                   15204: =over 4
                   15205: 
                   15206: =item * &build_filters()
                   15207: 
                   15208: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15209: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15210: and quotacheck.pl
                   15211: 
1.1181    raeburn  15212: 
                   15213: Inputs:
                   15214: 
                   15215: filterlist - anonymous array of fields to include as potential filters 
                   15216: 
                   15217: crstype - course type
                   15218: 
                   15219: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15220:               to pop-open a course selector (will contain "extra element"). 
                   15221: 
                   15222: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15223: 
                   15224: filter - anonymous hash of criteria and their values
                   15225: 
                   15226: action - form action
                   15227: 
                   15228: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15229: 
1.1182    raeburn  15230: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15231: 
                   15232: cloneruname - username of owner of new course who wants to clone
                   15233: 
                   15234: clonerudom - domain of owner of new course who wants to clone
                   15235: 
                   15236: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15237: 
                   15238: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15239: 
                   15240: codedom - domain
                   15241: 
                   15242: formname - value of form element named "form". 
                   15243: 
                   15244: fixeddom - domain, if fixed.
                   15245: 
                   15246: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15247: 
                   15248: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15249: 
                   15250: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15251: 
                   15252: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15253: 
                   15254: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15255: 
                   15256: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15257: 
                   15258: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15259: 
1.1182    raeburn  15260: 
1.1181    raeburn  15261: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15262: 
1.1182    raeburn  15263: 
1.1181    raeburn  15264: Side Effects: None
                   15265: 
                   15266: =cut
                   15267: 
                   15268: # ---------------------------------------------- search for courses based on last activity etc.
                   15269: 
                   15270: sub build_filters {
                   15271:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15272:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15273:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15274:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15275:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15276:     my ($list,$jscript);
1.1181    raeburn  15277:     my $onchange = 'javascript:updateFilters(this)';
                   15278:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15279:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15280:         $typeselectform,$instcodetitle);
                   15281:     if ($formname eq '') {
                   15282:         $formname = $caller;
                   15283:     }
                   15284:     foreach my $item (@{$filterlist}) {
                   15285:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15286:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15287:             if ($item eq 'domainfilter') {
                   15288:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15289:             } elsif ($item eq 'coursefilter') {
                   15290:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15291:             } elsif ($item eq 'ownerfilter') {
                   15292:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15293:             } elsif ($item eq 'ownerdomfilter') {
                   15294:                 $filter->{'ownerdomfilter'} =
                   15295:                     &LONCAPA::clean_domain($filter->{$item});
                   15296:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15297:                                                        'ownerdomfilter',1);
                   15298:             } elsif ($item eq 'personfilter') {
                   15299:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15300:             } elsif ($item eq 'persondomfilter') {
                   15301:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15302:                                                         'persondomfilter',1);
                   15303:             } else {
                   15304:                 $filter->{$item} =~ s/\W//g;
                   15305:             }
                   15306:             if (!$filter->{$item}) {
                   15307:                 $filter->{$item} = '';
                   15308:             }
                   15309:         }
                   15310:         if ($item eq 'domainfilter') {
                   15311:             my $allow_blank = 1;
                   15312:             if ($formname eq 'portform') {
                   15313:                 $allow_blank=0;
                   15314:             } elsif ($formname eq 'studentform') {
                   15315:                 $allow_blank=0;
                   15316:             }
                   15317:             if ($fixeddom) {
                   15318:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15319:                                     ' value="'.$codedom.'" />'.
                   15320:                                     &Apache::lonnet::domain($codedom,'description');
                   15321:             } else {
                   15322:                 $domainselectform = &select_dom_form($filter->{$item},
                   15323:                                                      'domainfilter',
                   15324:                                                       $allow_blank,'',$onchange);
                   15325:             }
                   15326:         } else {
                   15327:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15328:         }
                   15329:     }
                   15330: 
                   15331:     # last course activity filter and selection
                   15332:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15333: 
                   15334:     # course created filter and selection
                   15335:     if (exists($filter->{'createdfilter'})) {
                   15336:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15337:     }
                   15338: 
                   15339:     my %lt = &Apache::lonlocal::texthash(
                   15340:                 'cac' => "$crstype Activity",
                   15341:                 'ccr' => "$crstype Created",
                   15342:                 'cde' => "$crstype Title",
                   15343:                 'cdo' => "$crstype Domain",
                   15344:                 'ins' => 'Institutional Code',
                   15345:                 'inc' => 'Institutional Categorization',
                   15346:                 'cow' => "$crstype Owner/Co-owner",
                   15347:                 'cop' => "$crstype Personnel Includes",
                   15348:                 'cog' => 'Type',
                   15349:              );
                   15350: 
                   15351:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15352:         my $typeval = 'Course';
                   15353:         if ($crstype eq 'Community') {
                   15354:             $typeval = 'Community';
                   15355:         }
                   15356:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15357:     } else {
                   15358:         $typeselectform =  '<select name="type" size="1"';
                   15359:         if ($onchange) {
                   15360:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15361:         }
                   15362:         $typeselectform .= '>'."\n";
                   15363:         foreach my $posstype ('Course','Community') {
                   15364:             $typeselectform.='<option value="'.$posstype.'"'.
                   15365:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15366:         }
                   15367:         $typeselectform.="</select>";
                   15368:     }
                   15369: 
                   15370:     my ($cloneableonlyform,$cloneabletitle);
                   15371:     if (exists($filter->{'cloneableonly'})) {
                   15372:         my $cloneableon = '';
                   15373:         my $cloneableoff = ' checked="checked"';
                   15374:         if ($filter->{'cloneableonly'}) {
                   15375:             $cloneableon = $cloneableoff;
                   15376:             $cloneableoff = '';
                   15377:         }
                   15378:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
                   15379:         if ($formname eq 'ccrs') {
1.1187    bisitz   15380:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15381:         } else {
                   15382:             $cloneabletitle = &mt('Cloneable by you');
                   15383:         }
                   15384:     }
                   15385:     my $officialjs;
                   15386:     if ($crstype eq 'Course') {
                   15387:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15388: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15389: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15390:             if ($codedom) { 
1.1181    raeburn  15391:                 $officialjs = 1;
                   15392:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15393:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15394:                                                                   $officialjs,$codetitlesref);
                   15395:                 if ($jscript) {
1.1182    raeburn  15396:                     $jscript = '<script type="text/javascript">'."\n".
                   15397:                                '// <![CDATA['."\n".
                   15398:                                $jscript."\n".
                   15399:                                '// ]]>'."\n".
                   15400:                                '</script>'."\n";
1.1181    raeburn  15401:                 }
                   15402:             }
                   15403:             if ($instcodeform eq '') {
                   15404:                 $instcodeform =
                   15405:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15406:                     $list->{'instcodefilter'}.'" />';
                   15407:                 $instcodetitle = $lt{'ins'};
                   15408:             } else {
                   15409:                 $instcodetitle = $lt{'inc'};
                   15410:             }
                   15411:             if ($fixeddom) {
                   15412:                 $instcodetitle .= '<br />('.$codedom.')';
                   15413:             }
                   15414:         }
                   15415:     }
                   15416:     my $output = qq|
                   15417: <form method="post" name="filterpicker" action="$action">
                   15418: <input type="hidden" name="form" value="$formname" />
                   15419: |;
                   15420:     if ($formname eq 'modifycourse') {
                   15421:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15422:                    '<input type="hidden" name="prevphase" value="'.
                   15423:                    $prevphase.'" />'."\n";
1.1198    musolffc 15424:     } elsif ($formname eq 'quotacheck') {
                   15425:         $output .= qq|
                   15426: <input type="hidden" name="sortby" value="" />
                   15427: <input type="hidden" name="sortorder" value="" />
                   15428: |;
                   15429:     } else {
1.1181    raeburn  15430:         my $name_input;
                   15431:         if ($cnameelement ne '') {
                   15432:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15433:                           $cnameelement.'" />';
                   15434:         }
                   15435:         $output .= qq|
1.1182    raeburn  15436: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15437: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15438: $name_input
                   15439: $roleelement
                   15440: $multelement
                   15441: $typeelement
                   15442: |;
                   15443:         if ($formname eq 'portform') {
                   15444:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15445:         }
                   15446:     }
                   15447:     if ($fixeddom) {
                   15448:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15449:     }
                   15450:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15451:     if ($sincefilterform) {
                   15452:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15453:                   .$sincefilterform
                   15454:                   .&Apache::lonhtmlcommon::row_closure();
                   15455:     }
                   15456:     if ($createdfilterform) {
                   15457:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15458:                   .$createdfilterform
                   15459:                   .&Apache::lonhtmlcommon::row_closure();
                   15460:     }
                   15461:     if ($domainselectform) {
                   15462:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15463:                   .$domainselectform
                   15464:                   .&Apache::lonhtmlcommon::row_closure();
                   15465:     }
                   15466:     if ($typeselectform) {
                   15467:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15468:             $output .= $typeselectform;
                   15469:         } else {
                   15470:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15471:                       .$typeselectform
                   15472:                       .&Apache::lonhtmlcommon::row_closure();
                   15473:         }
                   15474:     }
                   15475:     if ($instcodeform) {
                   15476:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15477:                   .$instcodeform
                   15478:                   .&Apache::lonhtmlcommon::row_closure();
                   15479:     }
                   15480:     if (exists($filter->{'ownerfilter'})) {
                   15481:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15482:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15483:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15484:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15485:                    $ownerdomselectform.'</td></tr></table>'.
                   15486:                    &Apache::lonhtmlcommon::row_closure();
                   15487:     }
                   15488:     if (exists($filter->{'personfilter'})) {
                   15489:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15490:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15491:                    '<input type="text" name="personfilter" size="20" value="'.
                   15492:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15493:                    $persondomselectform.'</td></tr></table>'.
                   15494:                    &Apache::lonhtmlcommon::row_closure();
                   15495:     }
                   15496:     if (exists($filter->{'coursefilter'})) {
                   15497:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15498:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15499:                   .$list->{'coursefilter'}.'" />'
                   15500:                   .&Apache::lonhtmlcommon::row_closure();
                   15501:     }
                   15502:     if ($cloneableonlyform) {
                   15503:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15504:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15505:     }
                   15506:     if (exists($filter->{'descriptfilter'})) {
                   15507:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15508:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15509:                   .$list->{'descriptfilter'}.'" />'
                   15510:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15511:     }
                   15512:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15513:                '<input type="hidden" name="updater" value="" />'."\n".
                   15514:                '<input type="submit" name="gosearch" value="'.
                   15515:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15516:     return $jscript.$clonewarning.$output;
                   15517: }
                   15518: 
                   15519: =pod 
                   15520: 
                   15521: =item * &timebased_select_form()
                   15522: 
1.1182    raeburn  15523: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15524: filter e.g., Course Activity, Course Created, when searching for courses
                   15525: or communities
                   15526: 
                   15527: Inputs:
                   15528: 
                   15529: item - name of form element (sincefilter or createdfilter)
                   15530: 
                   15531: filter - anonymous hash of criteria and their values
                   15532: 
                   15533: Returns: HTML for a select box contained a blank, then six time selections,
                   15534:          with value set in incoming form variables currently selected. 
                   15535: 
                   15536: Side Effects: None
                   15537: 
                   15538: =cut
                   15539: 
                   15540: sub timebased_select_form {
                   15541:     my ($item,$filter) = @_;
                   15542:     if (ref($filter) eq 'HASH') {
                   15543:         $filter->{$item} =~ s/[^\d-]//g;
                   15544:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15545:         return &select_form(
                   15546:                             $filter->{$item},
                   15547:                             $item,
                   15548:                             {      '-1' => '',
                   15549:                                 '86400' => &mt('today'),
                   15550:                                '604800' => &mt('last week'),
                   15551:                               '2592000' => &mt('last month'),
                   15552:                               '7776000' => &mt('last three months'),
                   15553:                              '15552000' => &mt('last six months'),
                   15554:                              '31104000' => &mt('last year'),
                   15555:                     'select_form_order' =>
                   15556:                            ['-1','86400','604800','2592000','7776000',
                   15557:                             '15552000','31104000']});
                   15558:     }
                   15559: }
                   15560: 
                   15561: =pod
                   15562: 
                   15563: =item * &js_changer()
                   15564: 
                   15565: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  15566: when course type or domain is changed, and also to hide 'Searching ...' on
                   15567: page load completion for page showing search result.
1.1181    raeburn  15568: 
                   15569: Inputs: None
                   15570: 
1.1183    raeburn  15571: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  15572: 
                   15573: Side Effects: None
                   15574: 
                   15575: =cut
                   15576: 
                   15577: sub js_changer {
                   15578:     return <<ENDJS;
                   15579: <script type="text/javascript">
                   15580: // <![CDATA[
                   15581: function updateFilters(caller) {
                   15582:     if (typeof(caller) != "undefined") {
                   15583:         document.filterpicker.updater.value = caller.name;
                   15584:     }
                   15585:     document.filterpicker.submit();
                   15586: }
1.1183    raeburn  15587: 
                   15588: function hideSearching() {
                   15589:     if (document.getElementById('searching')) {
                   15590:         document.getElementById('searching').style.display = 'none';
                   15591:     }
                   15592:     return;
                   15593: }
                   15594: 
1.1181    raeburn  15595: // ]]>
                   15596: </script>
                   15597: 
                   15598: ENDJS
                   15599: }
                   15600: 
                   15601: =pod
                   15602: 
1.1182    raeburn  15603: =item * &search_courses()
                   15604: 
                   15605: Process selected filters form course search form and pass to lonnet::courseiddump
                   15606: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15607: 
                   15608: Inputs:
                   15609: 
                   15610: dom - domain being searched 
                   15611: 
                   15612: type - course type ('Course' or 'Community' or '.' if any).
                   15613: 
                   15614: filter - anonymous hash of criteria and their values
                   15615: 
                   15616: numtitles - for institutional codes - number of categories
                   15617: 
                   15618: cloneruname - optional username of new course owner
                   15619: 
                   15620: clonerudom - optional domain of new course owner
                   15621: 
                   15622: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
                   15623:             (used when DC is using course creation form)
                   15624: 
                   15625: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15626: 
                   15627: 
                   15628: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15629: 
                   15630: 
                   15631: Side Effects: None
                   15632: 
                   15633: =cut
                   15634: 
                   15635: 
                   15636: sub search_courses {
                   15637:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
                   15638:     my (%courses,%showcourses,$cloner);
                   15639:     if (($filter->{'ownerfilter'} ne '') ||
                   15640:         ($filter->{'ownerdomfilter'} ne '')) {
                   15641:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15642:                                        $filter->{'ownerdomfilter'};
                   15643:     }
                   15644:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15645:         if (!$filter->{$item}) {
                   15646:             $filter->{$item}='.';
                   15647:         }
                   15648:     }
                   15649:     my $now = time;
                   15650:     my $timefilter =
                   15651:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15652:     my ($createdbefore,$createdafter);
                   15653:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15654:         $createdbefore = $now;
                   15655:         $createdafter = $now-$filter->{'createdfilter'};
                   15656:     }
                   15657:     my ($instcodefilter,$regexpok);
                   15658:     if ($numtitles) {
                   15659:         if ($env{'form.official'} eq 'on') {
                   15660:             $instcodefilter =
                   15661:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15662:             $regexpok = 1;
                   15663:         } elsif ($env{'form.official'} eq 'off') {
                   15664:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15665:             unless ($instcodefilter eq '') {
                   15666:                 $regexpok = -1;
                   15667:             }
                   15668:         }
                   15669:     } else {
                   15670:         $instcodefilter = $filter->{'instcodefilter'};
                   15671:     }
                   15672:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15673:     if ($type eq '') { $type = '.'; }
                   15674: 
                   15675:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15676:         $cloner = $cloneruname.':'.$clonerudom;
                   15677:     }
                   15678:     %courses = &Apache::lonnet::courseiddump($dom,
                   15679:                                              $filter->{'descriptfilter'},
                   15680:                                              $timefilter,
                   15681:                                              $instcodefilter,
                   15682:                                              $filter->{'combownerfilter'},
                   15683:                                              $filter->{'coursefilter'},
                   15684:                                              undef,undef,$type,$regexpok,undef,undef,
                   15685:                                              undef,undef,$cloner,$env{'form.cc_clone'},
                   15686:                                              $filter->{'cloneableonly'},
                   15687:                                              $createdbefore,$createdafter,undef,
                   15688:                                              $domcloner);
                   15689:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15690:         my $ccrole;
                   15691:         if ($type eq 'Community') {
                   15692:             $ccrole = 'co';
                   15693:         } else {
                   15694:             $ccrole = 'cc';
                   15695:         }
                   15696:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15697:                                                      $filter->{'persondomfilter'},
                   15698:                                                      'userroles',undef,
                   15699:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15700:                                                      $dom);
                   15701:         foreach my $role (keys(%rolehash)) {
                   15702:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15703:             my $cid = $cdom.'_'.$cnum;
                   15704:             if (exists($courses{$cid})) {
                   15705:                 if (ref($courses{$cid}) eq 'HASH') {
                   15706:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15707:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15708:                             push (@{$courses{$cid}{roles}},$courserole);
                   15709:                         }
                   15710:                     } else {
                   15711:                         $courses{$cid}{roles} = [$courserole];
                   15712:                     }
                   15713:                     $showcourses{$cid} = $courses{$cid};
                   15714:                 }
                   15715:             }
                   15716:         }
                   15717:         %courses = %showcourses;
                   15718:     }
                   15719:     return %courses;
                   15720: }
                   15721: 
                   15722: =pod
                   15723: 
1.1181    raeburn  15724: =back
                   15725: 
1.1207    raeburn  15726: =head1 Routines for version requirements for current course.
                   15727: 
                   15728: =over 4
                   15729: 
                   15730: =item * &check_release_required()
                   15731: 
                   15732: Compares required LON-CAPA version with version on server, and
                   15733: if required version is newer looks for a server with the required version.
                   15734: 
                   15735: Looks first at servers in user's owen domain; if none suitable, looks at
                   15736: servers in course's domain are permitted to host sessions for user's domain.
                   15737: 
                   15738: Inputs:
                   15739: 
                   15740: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15741: 
                   15742: $courseid - Course ID of current course
                   15743: 
                   15744: $rolecode - User's current role in course (for switchserver query string).
                   15745: 
                   15746: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15747: 
                   15748: 
                   15749: Returns:
                   15750: 
                   15751: $switchserver - query string tp append to /adm/switchserver call (if 
                   15752:                 current server's LON-CAPA version is too old. 
                   15753: 
                   15754: $warning - Message is displayed if no suitable server could be found.
                   15755: 
                   15756: =cut
                   15757: 
                   15758: sub check_release_required {
                   15759:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15760:     my ($switchserver,$warning);
                   15761:     if ($required ne '') {
                   15762:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15763:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15764:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15765:             my $otherserver;
                   15766:             if (($major eq '' && $minor eq '') ||
                   15767:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15768:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15769:                 my $switchlcrev =
                   15770:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15771:                                                            $userdomserver);
                   15772:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15773:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15774:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15775:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15776:                     if ($cdom ne $env{'user.domain'}) {
                   15777:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15778:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15779:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15780:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15781:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15782:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15783:                         my $canhost =
                   15784:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15785:                                                               $coursedomserver,
                   15786:                                                               $remoterev,
                   15787:                                                               $udomdefaults{'remotesessions'},
                   15788:                                                               $defdomdefaults{'hostedsessions'});
                   15789: 
                   15790:                         if ($canhost) {
                   15791:                             $otherserver = $coursedomserver;
                   15792:                         } else {
                   15793:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
                   15794:                         }
                   15795:                     } else {
                   15796:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
                   15797:                     }
                   15798:                 } else {
                   15799:                     $otherserver = $userdomserver;
                   15800:                 }
                   15801:             }
                   15802:             if ($otherserver ne '') {
                   15803:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   15804:             }
                   15805:         }
                   15806:     }
                   15807:     return ($switchserver,$warning);
                   15808: }
                   15809: 
                   15810: =pod
                   15811: 
                   15812: =item * &check_release_result()
                   15813: 
                   15814: Inputs:
                   15815: 
                   15816: $switchwarning - Warning message if no suitable server found to host session.
                   15817: 
                   15818: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15819:                 and current role.
                   15820: 
                   15821: Returns: HTML to display with information about requirement to switch server.
                   15822:          Either displaying warning with link to Roles/Courses screen or
                   15823:          display link to switchserver.
                   15824: 
1.1181    raeburn  15825: =cut
                   15826: 
1.1207    raeburn  15827: sub check_release_result {
                   15828:     my ($switchwarning,$switchserver) = @_;
                   15829:     my $output = &start_page('Selected course unavailable on this server').
                   15830:                  '<p class="LC_warning">';
                   15831:     if ($switchwarning) {
                   15832:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   15833:         if (&show_course()) {
                   15834:             $output .= &mt('Display courses');
                   15835:         } else {
                   15836:             $output .= &mt('Display roles');
                   15837:         }
                   15838:         $output .= '</a>';
                   15839:     } elsif ($switchserver) {
                   15840:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   15841:                    '<br />'.
                   15842:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   15843:                    &mt('Switch Server').
                   15844:                    '</a>';
                   15845:     }
                   15846:     $output .= '</p>'.&end_page();
                   15847:     return $output;
                   15848: }
                   15849: 
                   15850: =pod
                   15851: 
                   15852: =item * &needs_coursereinit()
                   15853: 
                   15854: Determine if course contents stored for user's session needs to be
                   15855: refreshed, because content has changed since "Big Hash" last tied.
                   15856: 
                   15857: Check for change is made if time last checked is more than 10 minutes ago
                   15858: (by default).
                   15859: 
                   15860: Inputs:
                   15861: 
                   15862: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15863: 
                   15864: $interval (optional) - Time which may elapse (in s) between last check for content
                   15865:                        change in current course. (default: 600 s).  
                   15866: 
                   15867: Returns: an array; first element is:
                   15868: 
                   15869: =over 4
                   15870: 
                   15871: 'switch' - if content updates mean user's session
                   15872:            needs to be switched to a server running a newer LON-CAPA version
                   15873:  
                   15874: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   15875:            on current server hosting user's session                
                   15876: 
                   15877: ''       - if no action required.
                   15878: 
                   15879: =back
                   15880: 
                   15881: If first item element is 'switch':
                   15882: 
                   15883: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   15884: 
                   15885: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15886:                               and current role. 
                   15887: 
                   15888: otherwise: no other elements returned.
                   15889: 
                   15890: =back
                   15891: 
                   15892: =cut
                   15893: 
                   15894: sub needs_coursereinit {
                   15895:     my ($loncaparev,$interval) = @_;
                   15896:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   15897:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   15898:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   15899:     my $now = time;
                   15900:     if ($interval eq '') {
                   15901:         $interval = 600;
                   15902:     }
                   15903:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   15904:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15905:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   15906:         if ($lastchange > $env{'request.course.tied'}) {
                   15907:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15908:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   15909:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   15910:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   15911:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   15912:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   15913:                     my ($switchserver,$switchwarning) =
                   15914:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   15915:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   15916:                     if ($switchwarning ne '' || $switchserver ne '') {
                   15917:                         return ('switch',$switchwarning,$switchserver);
                   15918:                     }
                   15919:                 }
                   15920:             }
                   15921:             return ('update');
                   15922:         }
                   15923:     }
                   15924:     return ();
                   15925: }
1.1181    raeburn  15926: 
1.1083    raeburn  15927: sub update_content_constraints {
                   15928:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15929:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15930:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15931:     my %checkresponsetypes;
                   15932:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15933:         my ($item,$name,$value) = split(/:/,$key);
                   15934:         if ($item eq 'resourcetag') {
                   15935:             if ($name eq 'responsetype') {
                   15936:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15937:             }
                   15938:         }
                   15939:     }
                   15940:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15941:     if (defined($navmap)) {
                   15942:         my %allresponses;
                   15943:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15944:             my %responses = $res->responseTypes();
                   15945:             foreach my $key (keys(%responses)) {
                   15946:                 next unless(exists($checkresponsetypes{$key}));
                   15947:                 $allresponses{$key} += $responses{$key};
                   15948:             }
                   15949:         }
                   15950:         foreach my $key (keys(%allresponses)) {
                   15951:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15952:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15953:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15954:             }
                   15955:         }
                   15956:         undef($navmap);
                   15957:     }
                   15958:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15959:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15960:     }
                   15961:     return;
                   15962: }
                   15963: 
1.1110    raeburn  15964: sub allmaps_incourse {
                   15965:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15966:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15967:         $cid = $env{'request.course.id'};
                   15968:         $cdom = $env{'course.'.$cid.'.domain'};
                   15969:         $cnum = $env{'course.'.$cid.'.num'};
                   15970:         $chome = $env{'course.'.$cid.'.home'};
                   15971:     }
                   15972:     my %allmaps = ();
                   15973:     my $lastchange =
                   15974:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15975:     if ($lastchange > $env{'request.course.tied'}) {
                   15976:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15977:         unless ($ferr) {
                   15978:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15979:         }
                   15980:     }
                   15981:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15982:     if (defined($navmap)) {
                   15983:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15984:             $allmaps{$res->src()} = 1;
                   15985:         }
                   15986:     }
                   15987:     return \%allmaps;
                   15988: }
                   15989: 
1.1083    raeburn  15990: sub parse_supplemental_title {
                   15991:     my ($title) = @_;
                   15992: 
                   15993:     my ($foldertitle,$renametitle);
                   15994:     if ($title =~ /&amp;&amp;&amp;/) {
                   15995:         $title = &HTML::Entites::decode($title);
                   15996:     }
                   15997:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   15998:         $renametitle=$4;
                   15999:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16000:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16001:         my $name =  &plainname($uname,$udom);
                   16002:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16003:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16004:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16005:             $name.': <br />'.$foldertitle;
                   16006:     }
                   16007:     if (wantarray) {
                   16008:         return ($title,$foldertitle,$renametitle);
                   16009:     }
                   16010:     return $title;
                   16011: }
                   16012: 
1.1143    raeburn  16013: sub recurse_supplemental {
                   16014:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16015:     if ($suppmap) {
                   16016:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16017:         if ($fatal) {
                   16018:             $errors ++;
                   16019:         } else {
                   16020:             if ($#LONCAPA::map::resources > 0) {
                   16021:                 foreach my $res (@LONCAPA::map::resources) {
                   16022:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16023:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16024:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16025:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16026:                         } else {
                   16027:                             $numfiles ++;
                   16028:                         }
                   16029:                     }
                   16030:                 }
                   16031:             }
                   16032:         }
                   16033:     }
                   16034:     return ($numfiles,$errors);
                   16035: }
                   16036: 
1.1101    raeburn  16037: sub symb_to_docspath {
                   16038:     my ($symb) = @_;
                   16039:     return unless ($symb);
                   16040:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16041:     if ($resurl=~/\.(sequence|page)$/) {
                   16042:         $mapurl=$resurl;
                   16043:     } elsif ($resurl eq 'adm/navmaps') {
                   16044:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16045:     }
                   16046:     my $mapresobj;
                   16047:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16048:     if (ref($navmap)) {
                   16049:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16050:     }
                   16051:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16052:     my $type=$2;
                   16053:     my $path;
                   16054:     if (ref($mapresobj)) {
                   16055:         my $pcslist = $mapresobj->map_hierarchy();
                   16056:         if ($pcslist ne '') {
                   16057:             foreach my $pc (split(/,/,$pcslist)) {
                   16058:                 next if ($pc <= 1);
                   16059:                 my $res = $navmap->getByMapPc($pc);
                   16060:                 if (ref($res)) {
                   16061:                     my $thisurl = $res->src();
                   16062:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16063:                     my $thistitle = $res->title();
                   16064:                     $path .= '&'.
                   16065:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16066:                              &escape($thistitle).
1.1101    raeburn  16067:                              ':'.$res->randompick().
                   16068:                              ':'.$res->randomout().
                   16069:                              ':'.$res->encrypted().
                   16070:                              ':'.$res->randomorder().
                   16071:                              ':'.$res->is_page();
                   16072:                 }
                   16073:             }
                   16074:         }
                   16075:         $path =~ s/^\&//;
                   16076:         my $maptitle = $mapresobj->title();
                   16077:         if ($mapurl eq 'default') {
1.1129    raeburn  16078:             $maptitle = 'Main Content';
1.1101    raeburn  16079:         }
                   16080:         $path .= (($path ne '')? '&' : '').
                   16081:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16082:                  &escape($maptitle).
1.1101    raeburn  16083:                  ':'.$mapresobj->randompick().
                   16084:                  ':'.$mapresobj->randomout().
                   16085:                  ':'.$mapresobj->encrypted().
                   16086:                  ':'.$mapresobj->randomorder().
                   16087:                  ':'.$mapresobj->is_page();
                   16088:     } else {
                   16089:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16090:         my $ispage = (($type eq 'page')? 1 : '');
                   16091:         if ($mapurl eq 'default') {
1.1129    raeburn  16092:             $maptitle = 'Main Content';
1.1101    raeburn  16093:         }
                   16094:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16095:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16096:     }
                   16097:     unless ($mapurl eq 'default') {
                   16098:         $path = 'default&'.
1.1146    raeburn  16099:                 &escape('Main Content').
1.1101    raeburn  16100:                 ':::::&'.$path;
                   16101:     }
                   16102:     return $path;
                   16103: }
                   16104: 
1.1094    raeburn  16105: sub captcha_display {
                   16106:     my ($context,$lonhost) = @_;
                   16107:     my ($output,$error);
                   16108:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16109:     if ($captcha eq 'original') {
1.1094    raeburn  16110:         $output = &create_captcha();
                   16111:         unless ($output) {
1.1172    raeburn  16112:             $error = 'captcha';
1.1094    raeburn  16113:         }
                   16114:     } elsif ($captcha eq 'recaptcha') {
                   16115:         $output = &create_recaptcha($pubkey);
                   16116:         unless ($output) {
1.1172    raeburn  16117:             $error = 'recaptcha';
1.1094    raeburn  16118:         }
                   16119:     }
1.1176    raeburn  16120:     return ($output,$error,$captcha);
1.1094    raeburn  16121: }
                   16122: 
                   16123: sub captcha_response {
                   16124:     my ($context,$lonhost) = @_;
                   16125:     my ($captcha_chk,$captcha_error);
                   16126:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16127:     if ($captcha eq 'original') {
1.1094    raeburn  16128:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16129:     } elsif ($captcha eq 'recaptcha') {
                   16130:         $captcha_chk = &check_recaptcha($privkey);
                   16131:     } else {
                   16132:         $captcha_chk = 1;
                   16133:     }
                   16134:     return ($captcha_chk,$captcha_error);
                   16135: }
                   16136: 
                   16137: sub get_captcha_config {
                   16138:     my ($context,$lonhost) = @_;
1.1095    raeburn  16139:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  16140:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16141:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16142:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  16143:     if ($context eq 'usercreation') {
                   16144:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16145:         if (ref($domconfig{$context}) eq 'HASH') {
                   16146:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16147:             if (ref($hashtocheck) eq 'HASH') {
                   16148:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16149:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16150:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16151:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16152:                     }
                   16153:                     if ($privkey && $pubkey) {
                   16154:                         $captcha = 'recaptcha';
                   16155:                     } else {
                   16156:                         $captcha = 'original';
                   16157:                     }
                   16158:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16159:                     $captcha = 'original';
                   16160:                 }
1.1094    raeburn  16161:             }
1.1095    raeburn  16162:         } else {
                   16163:             $captcha = 'captcha';
                   16164:         }
                   16165:     } elsif ($context eq 'login') {
                   16166:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16167:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16168:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16169:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  16170:             if ($privkey && $pubkey) {
                   16171:                 $captcha = 'recaptcha';
1.1095    raeburn  16172:             } else {
                   16173:                 $captcha = 'original';
1.1094    raeburn  16174:             }
1.1095    raeburn  16175:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16176:             $captcha = 'original';
1.1094    raeburn  16177:         }
                   16178:     }
                   16179:     return ($captcha,$pubkey,$privkey);
                   16180: }
                   16181: 
                   16182: sub create_captcha {
                   16183:     my %captcha_params = &captcha_settings();
                   16184:     my ($output,$maxtries,$tries) = ('',10,0);
                   16185:     while ($tries < $maxtries) {
                   16186:         $tries ++;
                   16187:         my $captcha = Authen::Captcha->new (
                   16188:                                            output_folder => $captcha_params{'output_dir'},
                   16189:                                            data_folder   => $captcha_params{'db_dir'},
                   16190:                                           );
                   16191:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16192: 
                   16193:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16194:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16195:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  16196:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16197:                       '<br />'.
                   16198:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  16199:             last;
                   16200:         }
                   16201:     }
                   16202:     return $output;
                   16203: }
                   16204: 
                   16205: sub captcha_settings {
                   16206:     my %captcha_params = (
                   16207:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16208:                            www_output_dir => "/captchaspool",
                   16209:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16210:                            numchars       => '5',
                   16211:                          );
                   16212:     return %captcha_params;
                   16213: }
                   16214: 
                   16215: sub check_captcha {
                   16216:     my ($captcha_chk,$captcha_error);
                   16217:     my $code = $env{'form.code'};
                   16218:     my $md5sum = $env{'form.crypt'};
                   16219:     my %captcha_params = &captcha_settings();
                   16220:     my $captcha = Authen::Captcha->new(
                   16221:                       output_folder => $captcha_params{'output_dir'},
                   16222:                       data_folder   => $captcha_params{'db_dir'},
                   16223:                   );
1.1109    raeburn  16224:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  16225:     my %captcha_hash = (
                   16226:                         0       => 'Code not checked (file error)',
                   16227:                        -1      => 'Failed: code expired',
                   16228:                        -2      => 'Failed: invalid code (not in database)',
                   16229:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16230:     );
                   16231:     if ($captcha_chk != 1) {
                   16232:         $captcha_error = $captcha_hash{$captcha_chk}
                   16233:     }
                   16234:     return ($captcha_chk,$captcha_error);
                   16235: }
                   16236: 
                   16237: sub create_recaptcha {
                   16238:     my ($pubkey) = @_;
1.1153    raeburn  16239:     my $use_ssl;
                   16240:     if ($ENV{'SERVER_PORT'} == 443) {
                   16241:         $use_ssl = 1;
                   16242:     }
1.1094    raeburn  16243:     my $captcha = Captcha::reCAPTCHA->new;
                   16244:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  16245:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1213  ! raeburn  16246:            &mt('If the text is hard to read, [_1] will replace them.',
1.1133    raeburn  16247:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  16248:            '<br /><br />';
                   16249: }
                   16250: 
                   16251: sub check_recaptcha {
                   16252:     my ($privkey) = @_;
                   16253:     my $captcha_chk;
                   16254:     my $captcha = Captcha::reCAPTCHA->new;
                   16255:     my $captcha_result =
                   16256:         $captcha->check_answer(
                   16257:                                 $privkey,
                   16258:                                 $ENV{'REMOTE_ADDR'},
                   16259:                                 $env{'form.recaptcha_challenge_field'},
                   16260:                                 $env{'form.recaptcha_response_field'},
                   16261:                               );
                   16262:     if ($captcha_result->{is_valid}) {
                   16263:         $captcha_chk = 1;
                   16264:     }
                   16265:     return $captcha_chk;
                   16266: }
                   16267: 
1.1174    raeburn  16268: sub emailusername_info {
1.1177    raeburn  16269:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  16270:     my %titles = &Apache::lonlocal::texthash (
                   16271:                      lastname      => 'Last Name',
                   16272:                      firstname     => 'First Name',
                   16273:                      institution   => 'School/college/university',
                   16274:                      location      => "School's city, state/province, country",
                   16275:                      web           => "School's web address",
                   16276:                      officialemail => 'E-mail address at institution (if different)',
                   16277:                  );
                   16278:     return (\@fields,\%titles);
                   16279: }
                   16280: 
1.1161    raeburn  16281: sub cleanup_html {
                   16282:     my ($incoming) = @_;
                   16283:     my $outgoing;
                   16284:     if ($incoming ne '') {
                   16285:         $outgoing = $incoming;
                   16286:         $outgoing =~ s/;/&#059;/g;
                   16287:         $outgoing =~ s/\#/&#035;/g;
                   16288:         $outgoing =~ s/\&/&#038;/g;
                   16289:         $outgoing =~ s/</&#060;/g;
                   16290:         $outgoing =~ s/>/&#062;/g;
                   16291:         $outgoing =~ s/\(/&#040/g;
                   16292:         $outgoing =~ s/\)/&#041;/g;
                   16293:         $outgoing =~ s/"/&#034;/g;
                   16294:         $outgoing =~ s/'/&#039;/g;
                   16295:         $outgoing =~ s/\$/&#036;/g;
                   16296:         $outgoing =~ s{/}{&#047;}g;
                   16297:         $outgoing =~ s/=/&#061;/g;
                   16298:         $outgoing =~ s/\\/&#092;/g
                   16299:     }
                   16300:     return $outgoing;
                   16301: }
                   16302: 
1.1190    musolffc 16303: # Checks for critical messages and returns a redirect url if one exists.
                   16304: # $interval indicates how often to check for messages.
                   16305: sub critical_redirect {
                   16306:     my ($interval) = @_;
                   16307:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16308:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16309:                                         $env{'user.name'});
                   16310:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16311:         my $redirecturl;
1.1190    musolffc 16312:         if ($what[0]) {
                   16313: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16314: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16315: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16316:                 return (1, $url);
1.1190    musolffc 16317:             }
1.1191    raeburn  16318:         }
                   16319:     } 
                   16320:     return ();
1.1190    musolffc 16321: }
                   16322: 
1.1174    raeburn  16323: # Use:
                   16324: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16325: #
                   16326: ##################################################
                   16327: #          password associated functions         #
                   16328: ##################################################
                   16329: sub des_keys {
                   16330:     # Make a new key for DES encryption.
                   16331:     # Each key has two parts which are returned separately.
                   16332:     # Please note:  Each key must be passed through the &hex function
                   16333:     # before it is output to the web browser.  The hex versions cannot
                   16334:     # be used to decrypt.
                   16335:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16336:                 '8','9','a','b','c','d','e','f');
                   16337:     my $lkey='';
                   16338:     for (0..7) {
                   16339:         $lkey.=$hexstr[rand(15)];
                   16340:     }
                   16341:     my $ukey='';
                   16342:     for (0..7) {
                   16343:         $ukey.=$hexstr[rand(15)];
                   16344:     }
                   16345:     return ($lkey,$ukey);
                   16346: }
                   16347: 
                   16348: sub des_decrypt {
                   16349:     my ($key,$cyphertext) = @_;
                   16350:     my $keybin=pack("H16",$key);
                   16351:     my $cypher;
                   16352:     if ($Crypt::DES::VERSION>=2.03) {
                   16353:         $cypher=new Crypt::DES $keybin;
                   16354:     } else {
                   16355:         $cypher=new DES $keybin;
                   16356:     }
                   16357:     my $plaintext=
                   16358:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16359:     $plaintext.=
                   16360:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16361:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16362:     return $plaintext;
                   16363: }
                   16364: 
1.112     bowersj2 16365: 1;
                   16366: __END__;
1.41      ng       16367: 

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