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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.38! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.37 2013/05/12 11:25:47 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.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.479     albertel   72: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    73: use DateTime::TimeZone;
1.687     raeburn    74: use DateTime::Locale::Catalog;
1.1075.2.14  raeburn    75: use Authen::Captcha;
                     76: use Captcha::reCAPTCHA;
1.117     www        77: 
1.517     raeburn    78: # ---------------------------------------------- Designs
                     79: use vars qw(%defaultdesign);
                     80: 
1.22      www        81: my $readit;
                     82: 
1.517     raeburn    83: 
1.157     matthew    84: ##
                     85: ## Global Variables
                     86: ##
1.46      matthew    87: 
1.643     foxr       88: 
                     89: # ----------------------------------------------- SSI with retries:
                     90: #
                     91: 
                     92: =pod
                     93: 
1.648     raeburn    94: =head1 Server Side include with retries:
1.643     foxr       95: 
                     96: =over 4
                     97: 
1.648     raeburn    98: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       99: 
                    100: Performs an ssi with some number of retries.  Retries continue either
                    101: until the result is ok or until the retry count supplied by the
                    102: caller is exhausted.  
                    103: 
                    104: Inputs:
1.648     raeburn   105: 
                    106: =over 4
                    107: 
1.643     foxr      108: resource   - Identifies the resource to insert.
1.648     raeburn   109: 
1.643     foxr      110: retries    - Count of the number of retries allowed.
1.648     raeburn   111: 
1.643     foxr      112: form       - Hash that identifies the rendering options.
                    113: 
1.648     raeburn   114: =back
                    115: 
                    116: Returns:
                    117: 
                    118: =over 4
                    119: 
1.643     foxr      120: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   121: 
1.643     foxr      122: response   - The response from the last attempt (which may or may not have been successful.
                    123: 
1.648     raeburn   124: =back
                    125: 
                    126: =back
                    127: 
1.643     foxr      128: =cut
                    129: 
                    130: sub ssi_with_retries {
                    131:     my ($resource, $retries, %form) = @_;
                    132: 
                    133: 
                    134:     my $ok = 0;			# True if we got a good response.
                    135:     my $content;
                    136:     my $response;
                    137: 
                    138:     # Try to get the ssi done. within the retries count:
                    139: 
                    140:     do {
                    141: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    142: 	$ok      = $response->is_success;
1.650     www       143:         if (!$ok) {
                    144:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    145:         }
1.643     foxr      146: 	$retries--;
                    147:     } while (!$ok && ($retries > 0));
                    148: 
                    149:     if (!$ok) {
                    150: 	$content = '';		# On error return an empty content.
                    151:     }
                    152:     return ($content, $response);
                    153: 
                    154: }
                    155: 
                    156: 
                    157: 
1.20      www       158: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  159: my %language;
1.124     www       160: my %supported_language;
1.1048    foxr      161: my %latex_language;		# For choosing hyphenation in <transl..>
                    162: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  163: my %cprtag;
1.192     taceyjo1  164: my %scprtag;
1.351     www       165: my %fe; my %fd; my %fm;
1.41      ng        166: my %category_extensions;
1.12      harris41  167: 
1.46      matthew   168: # ---------------------------------------------- Thesaurus variables
1.144     matthew   169: #
                    170: # %Keywords:
                    171: #      A hash used by &keyword to determine if a word is considered a keyword.
                    172: # $thesaurus_db_file 
                    173: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   174: 
                    175: my %Keywords;
                    176: my $thesaurus_db_file;
                    177: 
1.144     matthew   178: #
                    179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    180: # thesaurus.tab, and filecategories.tab.
                    181: #
1.18      www       182: BEGIN {
1.46      matthew   183:     # Variable initialization
                    184:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    185:     #
1.22      www       186:     unless ($readit) {
1.12      harris41  187: # ------------------------------------------------------------------- languages
                    188:     {
1.158     raeburn   189:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    190:                                    '/language.tab';
                    191:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  192:             while (my $line = <$fh>) {
                    193:                 next if ($line=~/^\#/);
                    194:                 chomp($line);
1.1048    foxr      195:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   196:                 $language{$key}=$val.' - '.$enc;
                    197:                 if ($sup) {
                    198:                     $supported_language{$key}=$sup;
                    199:                 }
1.1048    foxr      200: 		if ($latex) {
                    201: 		    $latex_language_bykey{$key} = $latex;
                    202: 		    $latex_language{$two} = $latex;
                    203: 		}
1.158     raeburn   204:             }
                    205:             close($fh);
                    206:         }
1.12      harris41  207:     }
                    208: # ------------------------------------------------------------------ copyrights
                    209:     {
1.158     raeburn   210:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    211:                                   '/copyright.tab';
                    212:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  213:             while (my $line = <$fh>) {
                    214:                 next if ($line=~/^\#/);
                    215:                 chomp($line);
                    216:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   217:                 $cprtag{$key}=$val;
                    218:             }
                    219:             close($fh);
                    220:         }
1.12      harris41  221:     }
1.351     www       222: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  223:     {
                    224:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    225:                                   '/source_copyright.tab';
                    226:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  227:             while (my $line = <$fh>) {
                    228:                 next if ($line =~ /^\#/);
                    229:                 chomp($line);
                    230:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  231:                 $scprtag{$key}=$val;
                    232:             }
                    233:             close($fh);
                    234:         }
                    235:     }
1.63      www       236: 
1.517     raeburn   237: # -------------------------------------------------------------- default domain designs
1.63      www       238:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   239:     my $designfile = $designdir.'/default.tab';
                    240:     if ( open (my $fh,"<$designfile") ) {
                    241:         while (my $line = <$fh>) {
                    242:             next if ($line =~ /^\#/);
                    243:             chomp($line);
                    244:             my ($key,$val)=(split(/\=/,$line));
                    245:             if ($val) { $defaultdesign{$key}=$val; }
                    246:         }
                    247:         close($fh);
1.63      www       248:     }
                    249: 
1.15      harris41  250: # ------------------------------------------------------------- file categories
                    251:     {
1.158     raeburn   252:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    253:                                   '/filecategories.tab';
                    254:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  255: 	    while (my $line = <$fh>) {
                    256: 		next if ($line =~ /^\#/);
                    257: 		chomp($line);
                    258:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   259:                 push @{$category_extensions{lc($category)}},$extension;
                    260:             }
                    261:             close($fh);
                    262:         }
                    263: 
1.15      harris41  264:     }
1.12      harris41  265: # ------------------------------------------------------------------ file types
                    266:     {
1.158     raeburn   267:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    268:                '/filetypes.tab';
                    269:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  270:             while (my $line = <$fh>) {
                    271: 		next if ($line =~ /^\#/);
                    272: 		chomp($line);
                    273:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   274:                 if ($descr ne '') {
                    275:                     $fe{$ending}=lc($emb);
                    276:                     $fd{$ending}=$descr;
1.351     www       277:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   278:                 }
                    279:             }
                    280:             close($fh);
                    281:         }
1.12      harris41  282:     }
1.22      www       283:     &Apache::lonnet::logthis(
1.705     tempelho  284:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       285:     $readit=1;
1.46      matthew   286:     }  # end of unless($readit) 
1.32      matthew   287:     
                    288: }
1.112     bowersj2  289: 
1.42      matthew   290: ###############################################################
                    291: ##           HTML and Javascript Helper Functions            ##
                    292: ###############################################################
                    293: 
                    294: =pod 
                    295: 
1.112     bowersj2  296: =head1 HTML and Javascript Functions
1.42      matthew   297: 
1.112     bowersj2  298: =over 4
                    299: 
1.648     raeburn   300: =item * &browser_and_searcher_javascript()
1.112     bowersj2  301: 
                    302: X<browsing, javascript>X<searching, javascript>Returns a string
                    303: containing javascript with two functions, C<openbrowser> and
                    304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    305: tags.
1.42      matthew   306: 
1.648     raeburn   307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   308: 
                    309: inputs: formname, elementname, only, omit
                    310: 
                    311: formname and elementname indicate the name of the html form and name of
                    312: the element that the results of the browsing selection are to be placed in. 
                    313: 
                    314: Specifying 'only' will restrict the browser to displaying only files
1.185     www       315: with the given extension.  Can be a comma separated list.
1.42      matthew   316: 
                    317: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       318: with the given extension.  Can be a comma separated list.
1.42      matthew   319: 
1.648     raeburn   320: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   321: 
                    322: Inputs: formname, elementname
                    323: 
                    324: formname and elementname specify the name of the html form and the name
                    325: of the element the selection from the search results will be placed in.
1.542     raeburn   326: 
1.42      matthew   327: =cut
                    328: 
                    329: sub browser_and_searcher_javascript {
1.199     albertel  330:     my ($mode)=@_;
                    331:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  332:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   333:     return <<END;
1.219     albertel  334: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   335:     var editbrowser = null;
1.135     albertel  336:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       337:         var url = '$resurl/?';
1.42      matthew   338:         if (editbrowser == null) {
                    339:             url += 'launch=1&';
                    340:         }
                    341:         url += 'catalogmode=interactive&';
1.199     albertel  342:         url += 'mode=$mode&';
1.611     albertel  343:         url += 'inhibitmenu=yes&';
1.42      matthew   344:         url += 'form=' + formname + '&';
                    345:         if (only != null) {
                    346:             url += 'only=' + only + '&';
1.217     albertel  347:         } else {
                    348:             url += 'only=&';
                    349: 	}
1.42      matthew   350:         if (omit != null) {
                    351:             url += 'omit=' + omit + '&';
1.217     albertel  352:         } else {
                    353:             url += 'omit=&';
                    354: 	}
1.135     albertel  355:         if (titleelement != null) {
                    356:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  357:         } else {
                    358: 	    url += 'titleelement=&';
                    359: 	}
1.42      matthew   360:         url += 'element=' + elementname + '';
                    361:         var title = 'Browser';
1.435     albertel  362:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   363:         options += ',width=700,height=600';
                    364:         editbrowser = open(url,title,options,'1');
                    365:         editbrowser.focus();
                    366:     }
                    367:     var editsearcher;
1.135     albertel  368:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   369:         var url = '/adm/searchcat?';
                    370:         if (editsearcher == null) {
                    371:             url += 'launch=1&';
                    372:         }
                    373:         url += 'catalogmode=interactive&';
1.199     albertel  374:         url += 'mode=$mode&';
1.42      matthew   375:         url += 'form=' + formname + '&';
1.135     albertel  376:         if (titleelement != null) {
                    377:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  378:         } else {
                    379: 	    url += 'titleelement=&';
                    380: 	}
1.42      matthew   381:         url += 'element=' + elementname + '';
                    382:         var title = 'Search';
1.435     albertel  383:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   384:         options += ',width=700,height=600';
                    385:         editsearcher = open(url,title,options,'1');
                    386:         editsearcher.focus();
                    387:     }
1.219     albertel  388: // END LON-CAPA Internal -->
1.42      matthew   389: END
1.170     www       390: }
                    391: 
                    392: sub lastresurl {
1.258     albertel  393:     if ($env{'environment.lastresurl'}) {
                    394: 	return $env{'environment.lastresurl'}
1.170     www       395:     } else {
                    396: 	return '/res';
                    397:     }
                    398: }
                    399: 
                    400: sub storeresurl {
                    401:     my $resurl=&Apache::lonnet::clutter(shift);
                    402:     unless ($resurl=~/^\/res/) { return 0; }
                    403:     $resurl=~s/\/$//;
                    404:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   405:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       406:     return 1;
1.42      matthew   407: }
                    408: 
1.74      www       409: sub studentbrowser_javascript {
1.111     www       410:    unless (
1.258     albertel  411:             (($env{'request.course.id'}) && 
1.302     albertel  412:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    413: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    414: 					  '/'.$env{'request.course.sec'})
                    415: 	      ))
1.258     albertel  416:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       417:           ) { return ''; }  
1.74      www       418:    return (<<'ENDSTDBRW');
1.776     bisitz    419: <script type="text/javascript" language="Javascript">
1.824     bisitz    420: // <![CDATA[
1.74      www       421:     var stdeditbrowser;
1.999     www       422:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       423:         var url = '/adm/pickstudent?';
                    424:         var filter;
1.558     albertel  425: 	if (!ignorefilter) {
                    426: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    427: 	}
1.74      www       428:         if (filter != null) {
                    429:            if (filter != '') {
                    430:                url += 'filter='+filter+'&';
                    431: 	   }
                    432:         }
                    433:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       434:                                     '&udomelement='+udom+
                    435:                                     '&clicker='+clicker;
1.111     www       436: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   437:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       438:         var title = 'Student_Browser';
1.74      www       439:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    440:         options += ',width=700,height=600';
                    441:         stdeditbrowser = open(url,title,options,'1');
                    442:         stdeditbrowser.focus();
                    443:     }
1.824     bisitz    444: // ]]>
1.74      www       445: </script>
                    446: ENDSTDBRW
                    447: }
1.42      matthew   448: 
1.1003    www       449: sub resourcebrowser_javascript {
                    450:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       451:    return (<<'ENDRESBRW');
1.1003    www       452: <script type="text/javascript" language="Javascript">
                    453: // <![CDATA[
                    454:     var reseditbrowser;
1.1004    www       455:     function openresbrowser(formname,reslink) {
1.1005    www       456:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       457:         var title = 'Resource_Browser';
                    458:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       459:         options += ',width=700,height=500';
1.1004    www       460:         reseditbrowser = open(url,title,options,'1');
                    461:         reseditbrowser.focus();
1.1003    www       462:     }
                    463: // ]]>
                    464: </script>
1.1004    www       465: ENDRESBRW
1.1003    www       466: }
                    467: 
1.74      www       468: sub selectstudent_link {
1.999     www       469:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    470:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    471:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    472:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  473:    if ($env{'request.course.id'}) {  
1.302     albertel  474:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    475: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    476: 					'/'.$env{'request.course.sec'})) {
1.111     www       477: 	   return '';
                    478:        }
1.999     www       479:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   480:        if ($courseadvonly)  {
                    481:            $callargs .= ",'',1,1";
                    482:        }
                    483:        return '<span class="LC_nobreak">'.
                    484:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    485:               &mt('Select User').'</a></span>';
1.74      www       486:    }
1.258     albertel  487:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       488:        $callargs .= ",'',1"; 
1.793     raeburn   489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.111     www       492:    }
                    493:    return '';
1.91      www       494: }
                    495: 
1.1004    www       496: sub selectresource_link {
                    497:    my ($form,$reslink,$arg)=@_;
                    498:    
                    499:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    500:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    501:    unless ($env{'request.course.id'}) { return $arg; }
                    502:    return '<span class="LC_nobreak">'.
                    503:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    504:               $arg.'</a></span>';
                    505: }
                    506: 
                    507: 
                    508: 
1.653     raeburn   509: sub authorbrowser_javascript {
                    510:     return <<"ENDAUTHORBRW";
1.776     bisitz    511: <script type="text/javascript" language="JavaScript">
1.824     bisitz    512: // <![CDATA[
1.653     raeburn   513: var stdeditbrowser;
                    514: 
                    515: function openauthorbrowser(formname,udom) {
                    516:     var url = '/adm/pickauthor?';
                    517:     url += 'form='+formname+'&roledom='+udom;
                    518:     var title = 'Author_Browser';
                    519:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    520:     options += ',width=700,height=600';
                    521:     stdeditbrowser = open(url,title,options,'1');
                    522:     stdeditbrowser.focus();
                    523: }
                    524: 
1.824     bisitz    525: // ]]>
1.653     raeburn   526: </script>
                    527: ENDAUTHORBRW
                    528: }
                    529: 
1.91      www       530: sub coursebrowser_javascript {
1.1075.2.31  raeburn   531:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    532:         $credits_element) = @_;
1.932     raeburn   533:     my $wintitle = 'Course_Browser';
1.931     raeburn   534:     if ($crstype eq 'Community') {
1.932     raeburn   535:         $wintitle = 'Community_Browser';
1.909     raeburn   536:     }
1.876     raeburn   537:     my $id_functions = &javascript_index_functions();
                    538:     my $output = '
1.776     bisitz    539: <script type="text/javascript" language="JavaScript">
1.824     bisitz    540: // <![CDATA[
1.468     raeburn   541:     var stdeditbrowser;'."\n";
1.876     raeburn   542: 
                    543:     $output .= <<"ENDSTDBRW";
1.909     raeburn   544:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       545:         var url = '/adm/pickcourse?';
1.895     raeburn   546:         var formid = getFormIdByName(formname);
1.876     raeburn   547:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  548:         if (domainfilter != null) {
                    549:            if (domainfilter != '') {
                    550:                url += 'domainfilter='+domainfilter+'&';
                    551: 	   }
                    552:         }
1.91      www       553:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  554: 	                            '&cdomelement='+udom+
                    555:                                     '&cnameelement='+desc;
1.468     raeburn   556:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   557:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   558:                 url += '&roleelement='+extra_element;
                    559:                 if (domainfilter == null || domainfilter == '') {
                    560:                     url += '&domainfilter='+extra_element;
                    561:                 }
1.234     raeburn   562:             }
1.468     raeburn   563:             else {
                    564:                 if (formname == 'portform') {
                    565:                     url += '&setroles='+extra_element;
1.800     raeburn   566:                 } else {
                    567:                     if (formname == 'rules') {
                    568:                         url += '&fixeddom='+extra_element; 
                    569:                     }
1.468     raeburn   570:                 }
                    571:             }     
1.230     raeburn   572:         }
1.909     raeburn   573:         if (type != null && type != '') {
                    574:             url += '&type='+type;
                    575:         }
                    576:         if (type_elem != null && type_elem != '') {
                    577:             url += '&typeelement='+type_elem;
                    578:         }
1.872     raeburn   579:         if (formname == 'ccrs') {
                    580:             var ownername = document.forms[formid].ccuname.value;
                    581:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    582:             url += '&cloner='+ownername+':'+ownerdom;
                    583:         }
1.293     raeburn   584:         if (multflag !=null && multflag != '') {
                    585:             url += '&multiple='+multflag;
                    586:         }
1.909     raeburn   587:         var title = '$wintitle';
1.91      www       588:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    589:         options += ',width=700,height=600';
                    590:         stdeditbrowser = open(url,title,options,'1');
                    591:         stdeditbrowser.focus();
                    592:     }
1.876     raeburn   593: $id_functions
                    594: ENDSTDBRW
1.1075.2.31  raeburn   595:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    596:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    597:                                       $credits_element);
1.876     raeburn   598:     }
                    599:     $output .= '
                    600: // ]]>
                    601: </script>';
                    602:     return $output;
                    603: }
                    604: 
                    605: sub javascript_index_functions {
                    606:     return <<"ENDJS";
                    607: 
                    608: function getFormIdByName(formname) {
                    609:     for (var i=0;i<document.forms.length;i++) {
                    610:         if (document.forms[i].name == formname) {
                    611:             return i;
                    612:         }
                    613:     }
                    614:     return -1;
                    615: }
                    616: 
                    617: function getIndexByName(formid,item) {
                    618:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    619:         if (document.forms[formid].elements[i].name == item) {
                    620:             return i;
                    621:         }
                    622:     }
                    623:     return -1;
                    624: }
1.468     raeburn   625: 
1.876     raeburn   626: function getDomainFromSelectbox(formname,udom) {
                    627:     var userdom;
                    628:     var formid = getFormIdByName(formname);
                    629:     if (formid > -1) {
                    630:         var domid = getIndexByName(formid,udom);
                    631:         if (domid > -1) {
                    632:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    633:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    634:             }
                    635:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    636:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   637:             }
                    638:         }
                    639:     }
1.876     raeburn   640:     return userdom;
                    641: }
                    642: 
                    643: ENDJS
1.468     raeburn   644: 
1.876     raeburn   645: }
                    646: 
1.1017    raeburn   647: sub javascript_array_indexof {
1.1018    raeburn   648:     return <<ENDJS;
1.1017    raeburn   649: <script type="text/javascript" language="JavaScript">
                    650: // <![CDATA[
                    651: 
                    652: if (!Array.prototype.indexOf) {
                    653:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    654:         "use strict";
                    655:         if (this === void 0 || this === null) {
                    656:             throw new TypeError();
                    657:         }
                    658:         var t = Object(this);
                    659:         var len = t.length >>> 0;
                    660:         if (len === 0) {
                    661:             return -1;
                    662:         }
                    663:         var n = 0;
                    664:         if (arguments.length > 0) {
                    665:             n = Number(arguments[1]);
                    666:             if (n !== n) { // shortcut for verifying if it's NaN
                    667:                 n = 0;
                    668:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    669:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    670:             }
                    671:         }
                    672:         if (n >= len) {
                    673:             return -1;
                    674:         }
                    675:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    676:         for (; k < len; k++) {
                    677:             if (k in t && t[k] === searchElement) {
                    678:                 return k;
                    679:             }
                    680:         }
                    681:         return -1;
                    682:     }
                    683: }
                    684: 
                    685: // ]]>
                    686: </script>
                    687: 
                    688: ENDJS
                    689: 
                    690: }
                    691: 
1.876     raeburn   692: sub userbrowser_javascript {
                    693:     my $id_functions = &javascript_index_functions();
                    694:     return <<"ENDUSERBRW";
                    695: 
1.888     raeburn   696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   697:     var url = '/adm/pickuser?';
                    698:     var userdom = getDomainFromSelectbox(formname,udom);
                    699:     if (userdom != null) {
                    700:        if (userdom != '') {
                    701:            url += 'srchdom='+userdom+'&';
                    702:        }
                    703:     }
                    704:     url += 'form=' + formname + '&unameelement='+uname+
                    705:                                 '&udomelement='+udom+
                    706:                                 '&ulastelement='+ulast+
                    707:                                 '&ufirstelement='+ufirst+
                    708:                                 '&uemailelement='+uemail+
1.881     raeburn   709:                                 '&hideudomelement='+hideudom+
                    710:                                 '&coursedom='+crsdom;
1.888     raeburn   711:     if ((caller != null) && (caller != undefined)) {
                    712:         url += '&caller='+caller;
                    713:     }
1.876     raeburn   714:     var title = 'User_Browser';
                    715:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    716:     options += ',width=700,height=600';
                    717:     var stdeditbrowser = open(url,title,options,'1');
                    718:     stdeditbrowser.focus();
                    719: }
                    720: 
1.888     raeburn   721: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   722:     var formid = getFormIdByName(formname);
                    723:     if (formid > -1) {
1.888     raeburn   724:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   725:         var domid = getIndexByName(formid,udom);
                    726:         var hidedomid = getIndexByName(formid,origdom);
                    727:         if (hidedomid > -1) {
                    728:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   729:             var unameval = document.forms[formid].elements[unameid].value;
                    730:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    731:                 if (domid > -1) {
                    732:                     var slct = document.forms[formid].elements[domid];
                    733:                     if (slct.type == 'select-one') {
                    734:                         var i;
                    735:                         for (i=0;i<slct.length;i++) {
                    736:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    737:                         }
                    738:                     }
                    739:                     if (slct.type == 'hidden') {
                    740:                         slct.value = fixeddom;
1.876     raeburn   741:                     }
                    742:                 }
1.468     raeburn   743:             }
                    744:         }
                    745:     }
1.876     raeburn   746:     return;
                    747: }
                    748: 
                    749: $id_functions
                    750: ENDUSERBRW
1.468     raeburn   751: }
                    752: 
                    753: sub setsec_javascript {
1.1075.2.31  raeburn   754:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   755:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    756:         $communityrolestr);
                    757:     if ($role_element ne '') {
                    758:         my @allroles = ('st','ta','ep','in','ad');
                    759:         foreach my $crstype ('Course','Community') {
                    760:             if ($crstype eq 'Community') {
                    761:                 foreach my $role (@allroles) {
                    762:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    763:                 }
                    764:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    765:             } else {
                    766:                 foreach my $role (@allroles) {
                    767:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    768:                 }
                    769:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    770:             }
                    771:         }
                    772:         $rolestr = '"'.join('","',@allroles).'"';
                    773:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    774:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    775:     }
1.468     raeburn   776:     my $setsections = qq|
                    777: function setSect(sectionlist) {
1.629     raeburn   778:     var sectionsArray = new Array();
                    779:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    780:         sectionsArray = sectionlist.split(",");
                    781:     }
1.468     raeburn   782:     var numSections = sectionsArray.length;
                    783:     document.$formname.$sec_element.length = 0;
                    784:     if (numSections == 0) {
                    785:         document.$formname.$sec_element.multiple=false;
                    786:         document.$formname.$sec_element.size=1;
                    787:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    788:     } else {
                    789:         if (numSections == 1) {
                    790:             document.$formname.$sec_element.multiple=false;
                    791:             document.$formname.$sec_element.size=1;
                    792:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    793:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    794:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    795:         } else {
                    796:             for (var i=0; i<numSections; i++) {
                    797:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    798:             }
                    799:             document.$formname.$sec_element.multiple=true
                    800:             if (numSections < 3) {
                    801:                 document.$formname.$sec_element.size=numSections;
                    802:             } else {
                    803:                 document.$formname.$sec_element.size=3;
                    804:             }
                    805:             document.$formname.$sec_element.options[0].selected = false
                    806:         }
                    807:     }
1.91      www       808: }
1.905     raeburn   809: 
                    810: function setRole(crstype) {
1.468     raeburn   811: |;
1.905     raeburn   812:     if ($role_element eq '') {
                    813:         $setsections .= '    return;
                    814: }
                    815: ';
                    816:     } else {
                    817:         $setsections .= qq|
                    818:     var elementLength = document.$formname.$role_element.length;
                    819:     var allroles = Array($rolestr);
                    820:     var courserolenames = Array($courserolestr);
                    821:     var communityrolenames = Array($communityrolestr);
                    822:     if (elementLength != undefined) {
                    823:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    824:             if (crstype == 'Course') {
                    825:                 return;
                    826:             } else {
                    827:                 allroles[5] = 'co';
                    828:                 for (var i=0; i<6; i++) {
                    829:                     document.$formname.$role_element.options[i].value = allroles[i];
                    830:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    831:                 }
                    832:             }
                    833:         } else {
                    834:             if (crstype == 'Community') {
                    835:                 return;
                    836:             } else {
                    837:                 allroles[5] = 'cc';
                    838:                 for (var i=0; i<6; i++) {
                    839:                     document.$formname.$role_element.options[i].value = allroles[i];
                    840:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    841:                 }
                    842:             }
                    843:         }
                    844:     }
                    845:     return;
                    846: }
                    847: |;
                    848:     }
1.1075.2.31  raeburn   849:     if ($credits_element) {
                    850:         $setsections .= qq|
                    851: function setCredits(defaultcredits) {
                    852:     document.$formname.$credits_element.value = defaultcredits;
                    853:     return;
                    854: }
                    855: |;
                    856:     }
1.468     raeburn   857:     return $setsections;
                    858: }
                    859: 
1.91      www       860: sub selectcourse_link {
1.909     raeburn   861:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    862:        $typeelement) = @_;
                    863:    my $type = $selecttype;
1.871     raeburn   864:    my $linktext = &mt('Select Course');
                    865:    if ($selecttype eq 'Community') {
1.909     raeburn   866:        $linktext = &mt('Select Community');
1.906     raeburn   867:    } elsif ($selecttype eq 'Course/Community') {
                    868:        $linktext = &mt('Select Course/Community');
1.909     raeburn   869:        $type = '';
1.1019    raeburn   870:    } elsif ($selecttype eq 'Select') {
                    871:        $linktext = &mt('Select');
                    872:        $type = '';
1.871     raeburn   873:    }
1.787     bisitz    874:    return '<span class="LC_nobreak">'
                    875:          ."<a href='"
                    876:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    877:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   878:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   879:          ."'>".$linktext.'</a>'
1.787     bisitz    880:          .'</span>';
1.74      www       881: }
1.42      matthew   882: 
1.653     raeburn   883: sub selectauthor_link {
                    884:    my ($form,$udom)=@_;
                    885:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    886:           &mt('Select Author').'</a>';
                    887: }
                    888: 
1.876     raeburn   889: sub selectuser_link {
1.881     raeburn   890:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   891:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   892:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   893:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   894:            ');">'.$linktext.'</a>';
1.876     raeburn   895: }
                    896: 
1.273     raeburn   897: sub check_uncheck_jscript {
                    898:     my $jscript = <<"ENDSCRT";
                    899: function checkAll(field) {
                    900:     if (field.length > 0) {
                    901:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   902:             if (!field[i].disabled) {
                    903:                 field[i].checked = true;
                    904:             }
1.273     raeburn   905:         }
                    906:     } else {
1.1075.2.14  raeburn   907:         if (!field.disabled) {
                    908:             field.checked = true;
                    909:         }
1.273     raeburn   910:     }
                    911: }
                    912:  
                    913: function uncheckAll(field) {
                    914:     if (field.length > 0) {
                    915:         for (i = 0; i < field.length; i++) {
                    916:             field[i].checked = false ;
1.543     albertel  917:         }
                    918:     } else {
1.273     raeburn   919:         field.checked = false ;
                    920:     }
                    921: }
                    922: ENDSCRT
                    923:     return $jscript;
                    924: }
                    925: 
1.656     www       926: sub select_timezone {
1.659     raeburn   927:    my ($name,$selected,$onchange,$includeempty)=@_;
                    928:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    929:    if ($includeempty) {
                    930:        $output .= '<option value=""';
                    931:        if (($selected eq '') || ($selected eq 'local')) {
                    932:            $output .= ' selected="selected" ';
                    933:        }
                    934:        $output .= '> </option>';
                    935:    }
1.657     raeburn   936:    my @timezones = DateTime::TimeZone->all_names;
                    937:    foreach my $tzone (@timezones) {
                    938:        $output.= '<option value="'.$tzone.'"';
                    939:        if ($tzone eq $selected) {
                    940:            $output.=' selected="selected"';
                    941:        }
                    942:        $output.=">$tzone</option>\n";
1.656     www       943:    }
                    944:    $output.="</select>";
                    945:    return $output;
                    946: }
1.273     raeburn   947: 
1.687     raeburn   948: sub select_datelocale {
                    949:     my ($name,$selected,$onchange,$includeempty)=@_;
                    950:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    951:     if ($includeempty) {
                    952:         $output .= '<option value=""';
                    953:         if ($selected eq '') {
                    954:             $output .= ' selected="selected" ';
                    955:         }
                    956:         $output .= '> </option>';
                    957:     }
                    958:     my (@possibles,%locale_names);
                    959:     my @locales = DateTime::Locale::Catalog::Locales;
                    960:     foreach my $locale (@locales) {
                    961:         if (ref($locale) eq 'HASH') {
                    962:             my $id = $locale->{'id'};
                    963:             if ($id ne '') {
                    964:                 my $en_terr = $locale->{'en_territory'};
                    965:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   966:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   967:                 if (grep(/^en$/,@languages) || !@languages) {
                    968:                     if ($en_terr ne '') {
                    969:                         $locale_names{$id} = '('.$en_terr.')';
                    970:                     } elsif ($native_terr ne '') {
                    971:                         $locale_names{$id} = $native_terr;
                    972:                     }
                    973:                 } else {
                    974:                     if ($native_terr ne '') {
                    975:                         $locale_names{$id} = $native_terr.' ';
                    976:                     } elsif ($en_terr ne '') {
                    977:                         $locale_names{$id} = '('.$en_terr.')';
                    978:                     }
                    979:                 }
                    980:                 push (@possibles,$id);
                    981:             }
                    982:         }
                    983:     }
                    984:     foreach my $item (sort(@possibles)) {
                    985:         $output.= '<option value="'.$item.'"';
                    986:         if ($item eq $selected) {
                    987:             $output.=' selected="selected"';
                    988:         }
                    989:         $output.=">$item";
                    990:         if ($locale_names{$item} ne '') {
                    991:             $output.="  $locale_names{$item}</option>\n";
                    992:         }
                    993:         $output.="</option>\n";
                    994:     }
                    995:     $output.="</select>";
                    996:     return $output;
                    997: }
                    998: 
1.792     raeburn   999: sub select_language {
                   1000:     my ($name,$selected,$includeempty) = @_;
                   1001:     my %langchoices;
                   1002:     if ($includeempty) {
1.1075.2.32  raeburn  1003:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1004:     }
                   1005:     foreach my $id (&languageids()) {
                   1006:         my $code = &supportedlanguagecode($id);
                   1007:         if ($code) {
                   1008:             $langchoices{$code} = &plainlanguagedescription($id);
                   1009:         }
                   1010:     }
1.1075.2.32  raeburn  1011:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1012:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1013: }
                   1014: 
1.42      matthew  1015: =pod
1.36      matthew  1016: 
1.648     raeburn  1017: =item * &linked_select_forms(...)
1.36      matthew  1018: 
                   1019: linked_select_forms returns a string containing a <script></script> block
                   1020: and html for two <select> menus.  The select menus will be linked in that
                   1021: changing the value of the first menu will result in new values being placed
                   1022: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1023: order unless a defined order is provided.
1.36      matthew  1024: 
                   1025: linked_select_forms takes the following ordered inputs:
                   1026: 
                   1027: =over 4
                   1028: 
1.112     bowersj2 1029: =item * $formname, the name of the <form> tag
1.36      matthew  1030: 
1.112     bowersj2 1031: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1032: 
1.112     bowersj2 1033: =item * $firstdefault, the default value for the first menu
1.36      matthew  1034: 
1.112     bowersj2 1035: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1036: 
1.112     bowersj2 1037: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1038: 
1.112     bowersj2 1039: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1040: 
1.609     raeburn  1041: =item * $menuorder, the order of values in the first menu
                   1042: 
1.1075.2.31  raeburn  1043: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1044:         event for the first <select> tag
                   1045: 
                   1046: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1047:         event for the second <select> tag
                   1048: 
1.41      ng       1049: =back 
                   1050: 
1.36      matthew  1051: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1052: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1053: values for the first select menu.  The text that coincides with the 
1.41      ng       1054: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1055: and text for the second menu are given in the hash pointed to by 
                   1056: $menu{$choice1}->{'select2'}.  
                   1057: 
1.112     bowersj2 1058:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1059:                        default => "B3",
                   1060:                        select2 => { 
                   1061:                            B1 => "Choice B1",
                   1062:                            B2 => "Choice B2",
                   1063:                            B3 => "Choice B3",
                   1064:                            B4 => "Choice B4"
1.609     raeburn  1065:                            },
                   1066:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1067:                    },
                   1068:                A2 => { text =>"Choice A2" ,
                   1069:                        default => "C2",
                   1070:                        select2 => { 
                   1071:                            C1 => "Choice C1",
                   1072:                            C2 => "Choice C2",
                   1073:                            C3 => "Choice C3"
1.609     raeburn  1074:                            },
                   1075:                        order => ['C2','C1','C3'],
1.112     bowersj2 1076:                    },
                   1077:                A3 => { text =>"Choice A3" ,
                   1078:                        default => "D6",
                   1079:                        select2 => { 
                   1080:                            D1 => "Choice D1",
                   1081:                            D2 => "Choice D2",
                   1082:                            D3 => "Choice D3",
                   1083:                            D4 => "Choice D4",
                   1084:                            D5 => "Choice D5",
                   1085:                            D6 => "Choice D6",
                   1086:                            D7 => "Choice D7"
1.609     raeburn  1087:                            },
                   1088:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1089:                    }
                   1090:                );
1.36      matthew  1091: 
                   1092: =cut
                   1093: 
                   1094: sub linked_select_forms {
                   1095:     my ($formname,
                   1096:         $middletext,
                   1097:         $firstdefault,
                   1098:         $firstselectname,
                   1099:         $secondselectname, 
1.609     raeburn  1100:         $hashref,
                   1101:         $menuorder,
1.1075.2.31  raeburn  1102:         $onchangefirst,
                   1103:         $onchangesecond
1.36      matthew  1104:         ) = @_;
                   1105:     my $second = "document.$formname.$secondselectname";
                   1106:     my $first = "document.$formname.$firstselectname";
                   1107:     # output the javascript to do the changing
                   1108:     my $result = '';
1.776     bisitz   1109:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1110:     $result.="// <![CDATA[\n";
1.36      matthew  1111:     $result.="var select2data = new Object();\n";
                   1112:     $" = '","';
                   1113:     my $debug = '';
                   1114:     foreach my $s1 (sort(keys(%$hashref))) {
                   1115:         $result.="select2data.d_$s1 = new Object();\n";        
                   1116:         $result.="select2data.d_$s1.def = new String('".
                   1117:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1118:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1119:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1120:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1121:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1122:         }
1.36      matthew  1123:         $result.="\"@s2values\");\n";
                   1124:         $result.="select2data.d_$s1.texts = new Array(";        
                   1125:         my @s2texts;
                   1126:         foreach my $value (@s2values) {
                   1127:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1128:         }
                   1129:         $result.="\"@s2texts\");\n";
                   1130:     }
                   1131:     $"=' ';
                   1132:     $result.= <<"END";
                   1133: 
                   1134: function select1_changed() {
                   1135:     // Determine new choice
                   1136:     var newvalue = "d_" + $first.value;
                   1137:     // update select2
                   1138:     var values     = select2data[newvalue].values;
                   1139:     var texts      = select2data[newvalue].texts;
                   1140:     var select2def = select2data[newvalue].def;
                   1141:     var i;
                   1142:     // out with the old
                   1143:     for (i = 0; i < $second.options.length; i++) {
                   1144:         $second.options[i] = null;
                   1145:     }
                   1146:     // in with the nuclear
                   1147:     for (i=0;i<values.length; i++) {
                   1148:         $second.options[i] = new Option(values[i]);
1.143     matthew  1149:         $second.options[i].value = values[i];
1.36      matthew  1150:         $second.options[i].text = texts[i];
                   1151:         if (values[i] == select2def) {
                   1152:             $second.options[i].selected = true;
                   1153:         }
                   1154:     }
                   1155: }
1.824     bisitz   1156: // ]]>
1.36      matthew  1157: </script>
                   1158: END
                   1159:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1160:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1161:     my @order = sort(keys(%{$hashref}));
                   1162:     if (ref($menuorder) eq 'ARRAY') {
                   1163:         @order = @{$menuorder};
                   1164:     }
                   1165:     foreach my $value (@order) {
1.36      matthew  1166:         $result.="    <option value=\"$value\" ";
1.253     albertel 1167:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1168:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1169:     }
                   1170:     $result .= "</select>\n";
                   1171:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1172:     $result .= $middletext;
1.1075.2.31  raeburn  1173:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1174:     if ($onchangesecond) {
                   1175:         $result .= ' onchange="'.$onchangesecond.'"';
                   1176:     }
                   1177:     $result .= ">\n";
1.36      matthew  1178:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1179:     
                   1180:     my @secondorder = sort(keys(%select2));
                   1181:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1182:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1183:     }
                   1184:     foreach my $value (@secondorder) {
1.36      matthew  1185:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1186:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1187:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1188:     }
                   1189:     $result .= "</select>\n";
                   1190:     #    return $debug;
                   1191:     return $result;
                   1192: }   #  end of sub linked_select_forms {
                   1193: 
1.45      matthew  1194: =pod
1.44      bowersj2 1195: 
1.973     raeburn  1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1197: 
1.112     bowersj2 1198: Returns a string corresponding to an HTML link to the given help
                   1199: $topic, where $topic corresponds to the name of a .tex file in
                   1200: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1201: spaces. 
                   1202: 
                   1203: $text will optionally be linked to the same topic, allowing you to
                   1204: link text in addition to the graphic. If you do not want to link
                   1205: text, but wish to specify one of the later parameters, pass an
                   1206: empty string. 
                   1207: 
                   1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1209: the link will not open a new window. If false, the link will open
                   1210: a new window using Javascript. (Default is false.) 
                   1211: 
                   1212: $width and $height are optional numerical parameters that will
                   1213: override the width and height of the popped up window, which may
1.973     raeburn  1214: be useful for certain help topics with big pictures included.
                   1215: 
                   1216: $imgid is the id of the img tag used for the help icon. This may be
                   1217: used in a javascript call to switch the image src.  See 
                   1218: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1219: 
                   1220: =cut
                   1221: 
                   1222: sub help_open_topic {
1.973     raeburn  1223:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1224:     $text = "" if (not defined $text);
1.44      bowersj2 1225:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1226:     $width = 500 if (not defined $width);
1.44      bowersj2 1227:     $height = 400 if (not defined $height);
                   1228:     my $filename = $topic;
                   1229:     $filename =~ s/ /_/g;
                   1230: 
1.48      bowersj2 1231:     my $template = "";
                   1232:     my $link;
1.572     banghart 1233:     
1.159     www      1234:     $topic=~s/\W/\_/g;
1.44      bowersj2 1235: 
1.572     banghart 1236:     if (!$stayOnPage) {
1.1033    www      1237: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1238:     } elsif ($stayOnPage eq 'popup') {
                   1239:         $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 1240:     } else {
1.48      bowersj2 1241: 	$link = "/adm/help/${filename}.hlp";
                   1242:     }
                   1243: 
                   1244:     # Add the text
1.755     neumanie 1245:     if ($text ne "") {	
1.763     bisitz   1246: 	$template.='<span class="LC_help_open_topic">'
                   1247:                   .'<a target="_top" href="'.$link.'">'
                   1248:                   .$text.'</a>';
1.48      bowersj2 1249:     }
                   1250: 
1.763     bisitz   1251:     # (Always) Add the graphic
1.179     matthew  1252:     my $title = &mt('Online Help');
1.667     raeburn  1253:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1254:     if ($imgid ne '') {
                   1255:         $imgid = ' id="'.$imgid.'"';
                   1256:     }
1.763     bisitz   1257:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1258:               .'<img src="'.$helpicon.'" border="0"'
                   1259:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1260:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1261:               .' /></a>';
                   1262:     if ($text ne "") {	
                   1263:         $template.='</span>';
                   1264:     }
1.44      bowersj2 1265:     return $template;
                   1266: 
1.106     bowersj2 1267: }
                   1268: 
                   1269: # This is a quicky function for Latex cheatsheet editing, since it 
                   1270: # appears in at least four places
                   1271: sub helpLatexCheatsheet {
1.1037    www      1272:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1273:     my $out;
1.106     bowersj2 1274:     my $addOther = '';
1.732     raeburn  1275:     if ($topic) {
1.1037    www      1276: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1277:     }
                   1278:     $out = '<span>' # Start cheatsheet
                   1279: 	  .$addOther
                   1280:           .'<span>'
1.1037    www      1281: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1282: 	  .'</span> <span>'
1.1037    www      1283: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1284: 	  .'</span>';
1.732     raeburn  1285:     unless ($not_author) {
1.763     bisitz   1286:         $out .= ' <span>'
1.1037    www      1287: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1288: 	       .'</span>';
1.732     raeburn  1289:     }
1.763     bisitz   1290:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1291:     return $out;
1.172     www      1292: }
                   1293: 
1.430     albertel 1294: sub general_help {
                   1295:     my $helptopic='Student_Intro';
                   1296:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1297: 	$helptopic='Authoring_Intro';
1.907     raeburn  1298:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1299: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1300:     } elsif ($env{'request.role'}=~/^dc/) {
                   1301:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1302:     }
                   1303:     return $helptopic;
                   1304: }
                   1305: 
                   1306: sub update_help_link {
                   1307:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1308:     my $origurl = $ENV{'REQUEST_URI'};
                   1309:     $origurl=~s|^/~|/priv/|;
                   1310:     my $timestamp = time;
                   1311:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1312:         $$datum = &escape($$datum);
                   1313:     }
                   1314: 
                   1315:     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";
                   1316:     my $output .= <<"ENDOUTPUT";
                   1317: <script type="text/javascript">
1.824     bisitz   1318: // <![CDATA[
1.430     albertel 1319: banner_link = '$banner_link';
1.824     bisitz   1320: // ]]>
1.430     albertel 1321: </script>
                   1322: ENDOUTPUT
                   1323:     return $output;
                   1324: }
                   1325: 
                   1326: # now just updates the help link and generates a blue icon
1.193     raeburn  1327: sub help_open_menu {
1.430     albertel 1328:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1329: 	= @_;    
1.949     droeschl 1330:     $stayOnPage = 1;
1.430     albertel 1331:     my $output;
                   1332:     if ($component_help) {
                   1333: 	if (!$text) {
                   1334: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1335: 				       $width,$height);
                   1336: 	} else {
                   1337: 	    my $help_text;
                   1338: 	    $help_text=&unescape($topic);
                   1339: 	    $output='<table><tr><td>'.
                   1340: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1341: 				 $width,$height).'</td></tr></table>';
                   1342: 	}
                   1343:     }
                   1344:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1345:     return $output.$banner_link;
                   1346: }
                   1347: 
                   1348: sub top_nav_help {
                   1349:     my ($text) = @_;
1.436     albertel 1350:     $text = &mt($text);
1.949     droeschl 1351:     my $stay_on_page = 1;
                   1352: 
1.572     banghart 1353:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1354: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1355:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1356: 
1.201     raeburn  1357:     my $title = &mt('Get help');
1.436     albertel 1358: 
                   1359:     return <<"END";
                   1360: $banner_link
                   1361:  <a href="$link" title="$title">$text</a>
                   1362: END
                   1363: }
                   1364: 
                   1365: sub help_menu_js {
                   1366:     my ($text) = @_;
1.949     droeschl 1367:     my $stayOnPage = 1;
1.436     albertel 1368:     my $width = 620;
                   1369:     my $height = 600;
1.430     albertel 1370:     my $helptopic=&general_help();
                   1371:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1372:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1373:     my $start_page =
                   1374:         &Apache::loncommon::start_page('Help Menu', undef,
                   1375: 				       {'frameset'    => 1,
                   1376: 					'js_ready'    => 1,
                   1377: 					'add_entries' => {
                   1378: 					    'border' => '0',
1.579     raeburn  1379: 					    'rows'   => "110,*",},});
1.331     albertel 1380:     my $end_page =
                   1381:         &Apache::loncommon::end_page({'frameset' => 1,
                   1382: 				      'js_ready' => 1,});
                   1383: 
1.436     albertel 1384:     my $template .= <<"ENDTEMPLATE";
                   1385: <script type="text/javascript">
1.877     bisitz   1386: // <![CDATA[
1.253     albertel 1387: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1388: var banner_link = '';
1.243     raeburn  1389: function helpMenu(target) {
                   1390:     var caller = this;
                   1391:     if (target == 'open') {
                   1392:         var newWindow = null;
                   1393:         try {
1.262     albertel 1394:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1395:         }
                   1396:         catch(error) {
                   1397:             writeHelp(caller);
                   1398:             return;
                   1399:         }
                   1400:         if (newWindow) {
                   1401:             caller = newWindow;
                   1402:         }
1.193     raeburn  1403:     }
1.243     raeburn  1404:     writeHelp(caller);
                   1405:     return;
                   1406: }
                   1407: function writeHelp(caller) {
1.1072    raeburn  1408:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1.243     raeburn  1409:     caller.document.close()
                   1410:     caller.focus()
1.193     raeburn  1411: }
1.877     bisitz   1412: // END LON-CAPA Internal -->
1.253     albertel 1413: // ]]>
1.436     albertel 1414: </script>
1.193     raeburn  1415: ENDTEMPLATE
                   1416:     return $template;
                   1417: }
                   1418: 
1.172     www      1419: sub help_open_bug {
                   1420:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1421:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1422:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1423:     $text = "" if (not defined $text);
                   1424: 	$stayOnPage=1;
1.184     albertel 1425:     $width = 600 if (not defined $width);
                   1426:     $height = 600 if (not defined $height);
1.172     www      1427: 
                   1428:     $topic=~s/\W+/\+/g;
                   1429:     my $link='';
                   1430:     my $template='';
1.379     albertel 1431:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1432: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1433:     if (!$stayOnPage)
                   1434:     {
                   1435: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1436:     }
                   1437:     else
                   1438:     {
                   1439: 	$link = $url;
                   1440:     }
                   1441:     # Add the text
                   1442:     if ($text ne "")
                   1443:     {
                   1444: 	$template .= 
                   1445:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1446:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1447:     }
                   1448: 
                   1449:     # Add the graphic
1.179     matthew  1450:     my $title = &mt('Report a Bug');
1.215     albertel 1451:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1452:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1453:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1454: ENDTEMPLATE
                   1455:     if ($text ne '') { $template.='</td></tr></table>' };
                   1456:     return $template;
                   1457: 
                   1458: }
                   1459: 
                   1460: sub help_open_faq {
                   1461:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1462:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1463:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1464:     $text = "" if (not defined $text);
                   1465: 	$stayOnPage=1;
                   1466:     $width = 350 if (not defined $width);
                   1467:     $height = 400 if (not defined $height);
                   1468: 
                   1469:     $topic=~s/\W+/\+/g;
                   1470:     my $link='';
                   1471:     my $template='';
                   1472:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1473:     if (!$stayOnPage)
                   1474:     {
                   1475: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1476:     }
                   1477:     else
                   1478:     {
                   1479: 	$link = $url;
                   1480:     }
                   1481: 
                   1482:     # Add the text
                   1483:     if ($text ne "")
                   1484:     {
                   1485: 	$template .= 
1.173     www      1486:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1487:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1488:     }
                   1489: 
                   1490:     # Add the graphic
1.179     matthew  1491:     my $title = &mt('View the FAQ');
1.215     albertel 1492:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1493:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1494:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1495: ENDTEMPLATE
                   1496:     if ($text ne '') { $template.='</td></tr></table>' };
                   1497:     return $template;
                   1498: 
1.44      bowersj2 1499: }
1.37      matthew  1500: 
1.180     matthew  1501: ###############################################################
                   1502: ###############################################################
                   1503: 
1.45      matthew  1504: =pod
                   1505: 
1.648     raeburn  1506: =item * &change_content_javascript():
1.256     matthew  1507: 
                   1508: This and the next function allow you to create small sections of an
                   1509: otherwise static HTML page that you can update on the fly with
                   1510: Javascript, even in Netscape 4.
                   1511: 
                   1512: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1513: must be written to the HTML page once. It will prove the Javascript
                   1514: function "change(name, content)". Calling the change function with the
                   1515: name of the section 
                   1516: you want to update, matching the name passed to C<changable_area>, and
                   1517: the new content you want to put in there, will put the content into
                   1518: that area.
                   1519: 
                   1520: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1521: to contain room for the original contents. You need to "make space"
                   1522: for whatever changes you wish to make, and be B<sure> to check your
                   1523: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1524: it's adequate for updating a one-line status display, but little more.
                   1525: This script will set the space to 100% width, so you only need to
                   1526: worry about height in Netscape 4.
                   1527: 
                   1528: Modern browsers are much less limiting, and if you can commit to the
                   1529: user not using Netscape 4, this feature may be used freely with
                   1530: pretty much any HTML.
                   1531: 
                   1532: =cut
                   1533: 
                   1534: sub change_content_javascript {
                   1535:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1536:     if ($env{'browser.type'} eq 'netscape' &&
                   1537: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1538: 	return (<<NETSCAPE4);
                   1539: 	function change(name, content) {
                   1540: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1541: 	    doc.open();
                   1542: 	    doc.write(content);
                   1543: 	    doc.close();
                   1544: 	}
                   1545: NETSCAPE4
                   1546:     } else {
                   1547: 	# Otherwise, we need to use semi-standards-compliant code
                   1548: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1549: 	# is really scary, and every useful browser supports it
                   1550: 	return (<<DOMBASED);
                   1551: 	function change(name, content) {
                   1552: 	    element = document.getElementById(name);
                   1553: 	    element.innerHTML = content;
                   1554: 	}
                   1555: DOMBASED
                   1556:     }
                   1557: }
                   1558: 
                   1559: =pod
                   1560: 
1.648     raeburn  1561: =item * &changable_area($name,$origContent):
1.256     matthew  1562: 
                   1563: This provides a "changable area" that can be modified on the fly via
                   1564: the Javascript code provided in C<change_content_javascript>. $name is
                   1565: the name you will use to reference the area later; do not repeat the
                   1566: same name on a given HTML page more then once. $origContent is what
                   1567: the area will originally contain, which can be left blank.
                   1568: 
                   1569: =cut
                   1570: 
                   1571: sub changable_area {
                   1572:     my ($name, $origContent) = @_;
                   1573: 
1.258     albertel 1574:     if ($env{'browser.type'} eq 'netscape' &&
                   1575: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1576: 	# If this is netscape 4, we need to use the Layer tag
                   1577: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1578:     } else {
                   1579: 	return "<span id='$name'>$origContent</span>";
                   1580:     }
                   1581: }
                   1582: 
                   1583: =pod
                   1584: 
1.648     raeburn  1585: =item * &viewport_geometry_js 
1.590     raeburn  1586: 
                   1587: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1588: 
                   1589: =cut
                   1590: 
                   1591: 
                   1592: sub viewport_geometry_js { 
                   1593:     return <<"GEOMETRY";
                   1594: var Geometry = {};
                   1595: function init_geometry() {
                   1596:     if (Geometry.init) { return };
                   1597:     Geometry.init=1;
                   1598:     if (window.innerHeight) {
                   1599:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1600:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1601:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1602:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1603:     }
                   1604:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1605:         Geometry.getViewportHeight =
                   1606:             function() { return document.documentElement.clientHeight; };
                   1607:         Geometry.getViewportWidth =
                   1608:             function() { return document.documentElement.clientWidth; };
                   1609: 
                   1610:         Geometry.getHorizontalScroll =
                   1611:             function() { return document.documentElement.scrollLeft; };
                   1612:         Geometry.getVerticalScroll =
                   1613:             function() { return document.documentElement.scrollTop; };
                   1614:     }
                   1615:     else if (document.body.clientHeight) {
                   1616:         Geometry.getViewportHeight =
                   1617:             function() { return document.body.clientHeight; };
                   1618:         Geometry.getViewportWidth =
                   1619:             function() { return document.body.clientWidth; };
                   1620:         Geometry.getHorizontalScroll =
                   1621:             function() { return document.body.scrollLeft; };
                   1622:         Geometry.getVerticalScroll =
                   1623:             function() { return document.body.scrollTop; };
                   1624:     }
                   1625: }
                   1626: 
                   1627: GEOMETRY
                   1628: }
                   1629: 
                   1630: =pod
                   1631: 
1.648     raeburn  1632: =item * &viewport_size_js()
1.590     raeburn  1633: 
                   1634: 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. 
                   1635: 
                   1636: =cut
                   1637: 
                   1638: sub viewport_size_js {
                   1639:     my $geometry = &viewport_geometry_js();
                   1640:     return <<"DIMS";
                   1641: 
                   1642: $geometry
                   1643: 
                   1644: function getViewportDims(width,height) {
                   1645:     init_geometry();
                   1646:     width.value = Geometry.getViewportWidth();
                   1647:     height.value = Geometry.getViewportHeight();
                   1648:     return;
                   1649: }
                   1650: 
                   1651: DIMS
                   1652: }
                   1653: 
                   1654: =pod
                   1655: 
1.648     raeburn  1656: =item * &resize_textarea_js()
1.565     albertel 1657: 
                   1658: emits the needed javascript to resize a textarea to be as big as possible
                   1659: 
                   1660: creates a function resize_textrea that takes two IDs first should be
                   1661: the id of the element to resize, second should be the id of a div that
                   1662: surrounds everything that comes after the textarea, this routine needs
                   1663: to be attached to the <body> for the onload and onresize events.
                   1664: 
1.648     raeburn  1665: =back
1.565     albertel 1666: 
                   1667: =cut
                   1668: 
                   1669: sub resize_textarea_js {
1.590     raeburn  1670:     my $geometry = &viewport_geometry_js();
1.565     albertel 1671:     return <<"RESIZE";
                   1672:     <script type="text/javascript">
1.824     bisitz   1673: // <![CDATA[
1.590     raeburn  1674: $geometry
1.565     albertel 1675: 
1.588     albertel 1676: function getX(element) {
                   1677:     var x = 0;
                   1678:     while (element) {
                   1679: 	x += element.offsetLeft;
                   1680: 	element = element.offsetParent;
                   1681:     }
                   1682:     return x;
                   1683: }
                   1684: function getY(element) {
                   1685:     var y = 0;
                   1686:     while (element) {
                   1687: 	y += element.offsetTop;
                   1688: 	element = element.offsetParent;
                   1689:     }
                   1690:     return y;
                   1691: }
                   1692: 
                   1693: 
1.565     albertel 1694: function resize_textarea(textarea_id,bottom_id) {
                   1695:     init_geometry();
                   1696:     var textarea        = document.getElementById(textarea_id);
                   1697:     //alert(textarea);
                   1698: 
1.588     albertel 1699:     var textarea_top    = getY(textarea);
1.565     albertel 1700:     var textarea_height = textarea.offsetHeight;
                   1701:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1702:     var bottom_top      = getY(bottom);
1.565     albertel 1703:     var bottom_height   = bottom.offsetHeight;
                   1704:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1705:     var fudge           = 23;
1.565     albertel 1706:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1707:     if (new_height < 300) {
                   1708: 	new_height = 300;
                   1709:     }
                   1710:     textarea.style.height=new_height+'px';
                   1711: }
1.824     bisitz   1712: // ]]>
1.565     albertel 1713: </script>
                   1714: RESIZE
                   1715: 
                   1716: }
                   1717: 
                   1718: =pod
                   1719: 
1.256     matthew  1720: =head1 Excel and CSV file utility routines
                   1721: 
                   1722: =over 4
                   1723: 
                   1724: =cut
                   1725: 
                   1726: ###############################################################
                   1727: ###############################################################
                   1728: 
                   1729: =pod
                   1730: 
1.648     raeburn  1731: =item * &csv_translate($text) 
1.37      matthew  1732: 
1.185     www      1733: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1734: format.
                   1735: 
                   1736: =cut
                   1737: 
1.180     matthew  1738: ###############################################################
                   1739: ###############################################################
1.37      matthew  1740: sub csv_translate {
                   1741:     my $text = shift;
                   1742:     $text =~ s/\"/\"\"/g;
1.209     albertel 1743:     $text =~ s/\n/ /g;
1.37      matthew  1744:     return $text;
                   1745: }
1.180     matthew  1746: 
                   1747: ###############################################################
                   1748: ###############################################################
                   1749: 
                   1750: =pod
                   1751: 
1.648     raeburn  1752: =item * &define_excel_formats()
1.180     matthew  1753: 
                   1754: Define some commonly used Excel cell formats.
                   1755: 
                   1756: Currently supported formats:
                   1757: 
                   1758: =over 4
                   1759: 
                   1760: =item header
                   1761: 
                   1762: =item bold
                   1763: 
                   1764: =item h1
                   1765: 
                   1766: =item h2
                   1767: 
                   1768: =item h3
                   1769: 
1.256     matthew  1770: =item h4
                   1771: 
                   1772: =item i
                   1773: 
1.180     matthew  1774: =item date
                   1775: 
                   1776: =back
                   1777: 
                   1778: Inputs: $workbook
                   1779: 
                   1780: Returns: $format, a hash reference.
                   1781: 
1.1057    foxr     1782: 
1.180     matthew  1783: =cut
                   1784: 
                   1785: ###############################################################
                   1786: ###############################################################
                   1787: sub define_excel_formats {
                   1788:     my ($workbook) = @_;
                   1789:     my $format;
                   1790:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1791:                                                 bottom    => 1,
                   1792:                                                 align     => 'center');
                   1793:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1794:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1795:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1796:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1797:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1798:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1799:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1800:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1801:     return $format;
                   1802: }
                   1803: 
                   1804: ###############################################################
                   1805: ###############################################################
1.113     bowersj2 1806: 
                   1807: =pod
                   1808: 
1.648     raeburn  1809: =item * &create_workbook()
1.255     matthew  1810: 
                   1811: Create an Excel worksheet.  If it fails, output message on the
                   1812: request object and return undefs.
                   1813: 
                   1814: Inputs: Apache request object
                   1815: 
                   1816: Returns (undef) on failure, 
                   1817:     Excel worksheet object, scalar with filename, and formats 
                   1818:     from &Apache::loncommon::define_excel_formats on success
                   1819: 
                   1820: =cut
                   1821: 
                   1822: ###############################################################
                   1823: ###############################################################
                   1824: sub create_workbook {
                   1825:     my ($r) = @_;
                   1826:         #
                   1827:     # Create the excel spreadsheet
                   1828:     my $filename = '/prtspool/'.
1.258     albertel 1829:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1830:         time.'_'.rand(1000000000).'.xls';
                   1831:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1832:     if (! defined($workbook)) {
                   1833:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1834:         $r->print(
                   1835:             '<p class="LC_error">'
                   1836:            .&mt('Problems occurred in creating the new Excel file.')
                   1837:            .' '.&mt('This error has been logged.')
                   1838:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1839:            .'</p>'
                   1840:         );
1.255     matthew  1841:         return (undef);
                   1842:     }
                   1843:     #
1.1014    foxr     1844:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1845:     #
                   1846:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1847:     return ($workbook,$filename,$format);
                   1848: }
                   1849: 
                   1850: ###############################################################
                   1851: ###############################################################
                   1852: 
                   1853: =pod
                   1854: 
1.648     raeburn  1855: =item * &create_text_file()
1.113     bowersj2 1856: 
1.542     raeburn  1857: Create a file to write to and eventually make available to the user.
1.256     matthew  1858: If file creation fails, outputs an error message on the request object and 
                   1859: return undefs.
1.113     bowersj2 1860: 
1.256     matthew  1861: Inputs: Apache request object, and file suffix
1.113     bowersj2 1862: 
1.256     matthew  1863: Returns (undef) on failure, 
                   1864:     Filehandle and filename on success.
1.113     bowersj2 1865: 
                   1866: =cut
                   1867: 
1.256     matthew  1868: ###############################################################
                   1869: ###############################################################
                   1870: sub create_text_file {
                   1871:     my ($r,$suffix) = @_;
                   1872:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1873:     my $fh;
                   1874:     my $filename = '/prtspool/'.
1.258     albertel 1875:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1876:         time.'_'.rand(1000000000).'.'.$suffix;
                   1877:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1878:     if (! defined($fh)) {
                   1879:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1880:         $r->print(
                   1881:             '<p class="LC_error">'
                   1882:            .&mt('Problems occurred in creating the output file.')
                   1883:            .' '.&mt('This error has been logged.')
                   1884:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1885:            .'</p>'
                   1886:         );
1.113     bowersj2 1887:     }
1.256     matthew  1888:     return ($fh,$filename)
1.113     bowersj2 1889: }
                   1890: 
                   1891: 
1.256     matthew  1892: =pod 
1.113     bowersj2 1893: 
                   1894: =back
                   1895: 
                   1896: =cut
1.37      matthew  1897: 
                   1898: ###############################################################
1.33      matthew  1899: ##        Home server <option> list generating code          ##
                   1900: ###############################################################
1.35      matthew  1901: 
1.169     www      1902: # ------------------------------------------
                   1903: 
                   1904: sub domain_select {
                   1905:     my ($name,$value,$multiple)=@_;
                   1906:     my %domains=map { 
1.514     albertel 1907: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1908:     } &Apache::lonnet::all_domains();
1.169     www      1909:     if ($multiple) {
                   1910: 	$domains{''}=&mt('Any domain');
1.550     albertel 1911: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1912: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1913:     } else {
1.550     albertel 1914: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1915: 	return &select_form($name,$value,\%domains);
1.169     www      1916:     }
                   1917: }
                   1918: 
1.282     albertel 1919: #-------------------------------------------
                   1920: 
                   1921: =pod
                   1922: 
1.519     raeburn  1923: =head1 Routines for form select boxes
                   1924: 
                   1925: =over 4
                   1926: 
1.648     raeburn  1927: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1928: 
                   1929: Returns a string containing a <select> element int multiple mode
                   1930: 
                   1931: 
                   1932: Args:
                   1933:   $name - name of the <select> element
1.506     raeburn  1934:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1935:   $size - number of rows long the select element is
1.283     albertel 1936:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1937:           (shown text should already have been &mt())
1.506     raeburn  1938:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1939: 
1.282     albertel 1940: =cut
                   1941: 
                   1942: #-------------------------------------------
1.169     www      1943: sub multiple_select_form {
1.284     albertel 1944:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1945:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1946:     my $output='';
1.191     matthew  1947:     if (! defined($size)) {
                   1948:         $size = 4;
1.283     albertel 1949:         if (scalar(keys(%$hash))<4) {
                   1950:             $size = scalar(keys(%$hash));
1.191     matthew  1951:         }
                   1952:     }
1.734     bisitz   1953:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1954:     my @order;
1.506     raeburn  1955:     if (ref($order) eq 'ARRAY')  {
                   1956:         @order = @{$order};
                   1957:     } else {
                   1958:         @order = sort(keys(%$hash));
1.501     banghart 1959:     }
                   1960:     if (exists($$hash{'select_form_order'})) {
                   1961:         @order = @{$$hash{'select_form_order'}};
                   1962:     }
                   1963:         
1.284     albertel 1964:     foreach my $key (@order) {
1.356     albertel 1965:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1966:         $output.='selected="selected" ' if ($selected{$key});
                   1967:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1968:     }
                   1969:     $output.="</select>\n";
                   1970:     return $output;
                   1971: }
                   1972: 
1.88      www      1973: #-------------------------------------------
                   1974: 
                   1975: =pod
                   1976: 
1.970     raeburn  1977: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1978: 
                   1979: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1980: allow a user to select options from a ref to a hash containing:
                   1981: option_name => displayed text. An optional $onchange can include
                   1982: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   1983: 
1.88      www      1984: See lonrights.pm for an example invocation and use.
                   1985: 
                   1986: =cut
                   1987: 
                   1988: #-------------------------------------------
                   1989: sub select_form {
1.970     raeburn  1990:     my ($def,$name,$hashref,$onchange) = @_;
                   1991:     return unless (ref($hashref) eq 'HASH');
                   1992:     if ($onchange) {
                   1993:         $onchange = ' onchange="'.$onchange.'"';
                   1994:     }
                   1995:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 1996:     my @keys;
1.970     raeburn  1997:     if (exists($hashref->{'select_form_order'})) {
                   1998: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 1999:     } else {
1.970     raeburn  2000: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2001:     }
1.356     albertel 2002:     foreach my $key (@keys) {
                   2003:         $selectform.=
                   2004: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2005:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2006:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2007:     }
                   2008:     $selectform.="</select>";
                   2009:     return $selectform;
                   2010: }
                   2011: 
1.475     www      2012: # For display filters
                   2013: 
                   2014: sub display_filter {
1.1074    raeburn  2015:     my ($context) = @_;
1.475     www      2016:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2017:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2018:     my $phraseinput = 'hidden';
                   2019:     my $includeinput = 'hidden';
                   2020:     my ($checked,$includetypestext);
                   2021:     if ($env{'form.displayfilter'} eq 'containing') {
                   2022:         $phraseinput = 'text'; 
                   2023:         if ($context eq 'parmslog') {
                   2024:             $includeinput = 'checkbox';
                   2025:             if ($env{'form.includetypes'}) {
                   2026:                 $checked = ' checked="checked"';
                   2027:             }
                   2028:             $includetypestext = &mt('Include parameter types');
                   2029:         }
                   2030:     } else {
                   2031:         $includetypestext = '&nbsp;';
                   2032:     }
                   2033:     my ($additional,$secondid,$thirdid);
                   2034:     if ($context eq 'parmslog') {
                   2035:         $additional = 
                   2036:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2037:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2038:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2039:             '</label>';
                   2040:         $secondid = 'includetypes';
                   2041:         $thirdid = 'includetypestext';
                   2042:     }
                   2043:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2044:                                                     '$secondid','$thirdid')";
                   2045:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2046: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2047: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2048: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2049:            &mt('Filter: [_1]',
1.477     www      2050: 	   &select_form($env{'form.displayfilter'},
                   2051: 			'displayfilter',
1.970     raeburn  2052: 			{'currentfolder' => 'Current folder/page',
1.477     www      2053: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2054: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2055: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2056:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2057:                          '" />'.$additional;
                   2058: }
                   2059: 
                   2060: sub display_filter_js {
                   2061:     my $includetext = &mt('Include parameter types');
                   2062:     return <<"ENDJS";
                   2063:   
                   2064: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2065:     var firstType = 'hidden';
                   2066:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2067:         firstType = 'text';
                   2068:     }
                   2069:     firstObject = document.getElementById(firstid);
                   2070:     if (typeof(firstObject) == 'object') {
                   2071:         if (firstObject.type != firstType) {
                   2072:             changeInputType(firstObject,firstType);
                   2073:         }
                   2074:     }
                   2075:     if (context == 'parmslog') {
                   2076:         var secondType = 'hidden';
                   2077:         if (firstType == 'text') {
                   2078:             secondType = 'checkbox';
                   2079:         }
                   2080:         secondObject = document.getElementById(secondid);  
                   2081:         if (typeof(secondObject) == 'object') {
                   2082:             if (secondObject.type != secondType) {
                   2083:                 changeInputType(secondObject,secondType);
                   2084:             }
                   2085:         }
                   2086:         var textItem = document.getElementById(thirdid);
                   2087:         var currtext = textItem.innerHTML;
                   2088:         var newtext;
                   2089:         if (firstType == 'text') {
                   2090:             newtext = '$includetext';
                   2091:         } else {
                   2092:             newtext = '&nbsp;';
                   2093:         }
                   2094:         if (currtext != newtext) {
                   2095:             textItem.innerHTML = newtext;
                   2096:         }
                   2097:     }
                   2098:     return;
                   2099: }
                   2100: 
                   2101: function changeInputType(oldObject,newType) {
                   2102:     var newObject = document.createElement('input');
                   2103:     newObject.type = newType;
                   2104:     if (oldObject.size) {
                   2105:         newObject.size = oldObject.size;
                   2106:     }
                   2107:     if (oldObject.value) {
                   2108:         newObject.value = oldObject.value;
                   2109:     }
                   2110:     if (oldObject.name) {
                   2111:         newObject.name = oldObject.name;
                   2112:     }
                   2113:     if (oldObject.id) {
                   2114:         newObject.id = oldObject.id;
                   2115:     }
                   2116:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2117:     return;
                   2118: }
                   2119: 
                   2120: ENDJS
1.475     www      2121: }
                   2122: 
1.167     www      2123: sub gradeleveldescription {
                   2124:     my $gradelevel=shift;
                   2125:     my %gradelevels=(0 => 'Not specified',
                   2126: 		     1 => 'Grade 1',
                   2127: 		     2 => 'Grade 2',
                   2128: 		     3 => 'Grade 3',
                   2129: 		     4 => 'Grade 4',
                   2130: 		     5 => 'Grade 5',
                   2131: 		     6 => 'Grade 6',
                   2132: 		     7 => 'Grade 7',
                   2133: 		     8 => 'Grade 8',
                   2134: 		     9 => 'Grade 9',
                   2135: 		     10 => 'Grade 10',
                   2136: 		     11 => 'Grade 11',
                   2137: 		     12 => 'Grade 12',
                   2138: 		     13 => 'Grade 13',
                   2139: 		     14 => '100 Level',
                   2140: 		     15 => '200 Level',
                   2141: 		     16 => '300 Level',
                   2142: 		     17 => '400 Level',
                   2143: 		     18 => 'Graduate Level');
                   2144:     return &mt($gradelevels{$gradelevel});
                   2145: }
                   2146: 
1.163     www      2147: sub select_level_form {
                   2148:     my ($deflevel,$name)=@_;
                   2149:     unless ($deflevel) { $deflevel=0; }
1.167     www      2150:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2151:     for (my $i=0; $i<=18; $i++) {
                   2152:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2153:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2154:                 ">".&gradeleveldescription($i)."</option>\n";
                   2155:     }
                   2156:     $selectform.="</select>";
                   2157:     return $selectform;
1.163     www      2158: }
1.167     www      2159: 
1.35      matthew  2160: #-------------------------------------------
                   2161: 
1.45      matthew  2162: =pod
                   2163: 
1.1075.2.36  raeburn  2164: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoma,$excdoms)
1.35      matthew  2165: 
                   2166: Returns a string containing a <select name='$name' size='1'> form to 
                   2167: allow a user to select the domain to preform an operation in.  
                   2168: See loncreateuser.pm for an example invocation and use.
                   2169: 
1.90      www      2170: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2171: selected");
                   2172: 
1.743     raeburn  2173: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2174: 
1.910     raeburn  2175: 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.
                   2176: 
1.1075.2.36  raeburn  2177: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2178: 
                   2179: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
1.563     raeburn  2180: 
1.35      matthew  2181: =cut
                   2182: 
                   2183: #-------------------------------------------
1.34      matthew  2184: sub select_dom_form {
1.1075.2.36  raeburn  2185:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2186:     if ($onchange) {
1.874     raeburn  2187:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2188:     }
1.1075.2.36  raeburn  2189:     my (@domains,%exclude);
1.910     raeburn  2190:     if (ref($incdoms) eq 'ARRAY') {
                   2191:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2192:     } else {
                   2193:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2194:     }
1.90      www      2195:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2196:     if (ref($excdoms) eq 'ARRAY') {
                   2197:         map { $exclude{$_} = 1; } @{$excdoms};
                   2198:     }
1.743     raeburn  2199:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2200:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2201:         next if ($exclude{$dom});
1.356     albertel 2202:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2203:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2204:         if ($showdomdesc) {
                   2205:             if ($dom ne '') {
                   2206:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2207:                 if ($domdesc ne '') {
                   2208:                     $selectdomain .= ' ('.$domdesc.')';
                   2209:                 }
                   2210:             } 
                   2211:         }
                   2212:         $selectdomain .= "</option>\n";
1.34      matthew  2213:     }
                   2214:     $selectdomain.="</select>";
                   2215:     return $selectdomain;
                   2216: }
                   2217: 
1.35      matthew  2218: #-------------------------------------------
                   2219: 
1.45      matthew  2220: =pod
                   2221: 
1.648     raeburn  2222: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2223: 
1.586     raeburn  2224: input: 4 arguments (two required, two optional) - 
                   2225:     $domain - domain of new user
                   2226:     $name - name of form element
                   2227:     $default - Value of 'default' causes a default item to be first 
                   2228:                             option, and selected by default. 
                   2229:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2230:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2231: output: returns 2 items: 
1.586     raeburn  2232: (a) form element which contains either:
                   2233:    (i) <select name="$name">
                   2234:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2235:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2236:        </select>
                   2237:        form item if there are multiple library servers in $domain, or
                   2238:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2239:        if there is only one library server in $domain.
                   2240: 
                   2241: (b) number of library servers found.
                   2242: 
                   2243: See loncreateuser.pm for example of use.
1.35      matthew  2244: 
                   2245: =cut
                   2246: 
                   2247: #-------------------------------------------
1.586     raeburn  2248: sub home_server_form_item {
                   2249:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2250:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2251:     my $result;
                   2252:     my $numlib = keys(%servers);
                   2253:     if ($numlib > 1) {
                   2254:         $result .= '<select name="'.$name.'" />'."\n";
                   2255:         if ($default) {
1.804     bisitz   2256:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2257:                        '</option>'."\n";
                   2258:         }
                   2259:         foreach my $hostid (sort(keys(%servers))) {
                   2260:             $result.= '<option value="'.$hostid.'">'.
                   2261: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2262:         }
                   2263:         $result .= '</select>'."\n";
                   2264:     } elsif ($numlib == 1) {
                   2265:         my $hostid;
                   2266:         foreach my $item (keys(%servers)) {
                   2267:             $hostid = $item;
                   2268:         }
                   2269:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2270:                    $hostid.'" />';
                   2271:                    if (!$hide) {
                   2272:                        $result .= $hostid.' '.$servers{$hostid};
                   2273:                    }
                   2274:                    $result .= "\n";
                   2275:     } elsif ($default) {
                   2276:         $result .= '<input type="hidden" name="'.$name.
                   2277:                    '" value="default" />';
                   2278:                    if (!$hide) {
                   2279:                        $result .= &mt('default');
                   2280:                    }
                   2281:                    $result .= "\n";
1.33      matthew  2282:     }
1.586     raeburn  2283:     return ($result,$numlib);
1.33      matthew  2284: }
1.112     bowersj2 2285: 
                   2286: =pod
                   2287: 
1.534     albertel 2288: =back 
                   2289: 
1.112     bowersj2 2290: =cut
1.87      matthew  2291: 
                   2292: ###############################################################
1.112     bowersj2 2293: ##                  Decoding User Agent                      ##
1.87      matthew  2294: ###############################################################
                   2295: 
                   2296: =pod
                   2297: 
1.112     bowersj2 2298: =head1 Decoding the User Agent
                   2299: 
                   2300: =over 4
                   2301: 
                   2302: =item * &decode_user_agent()
1.87      matthew  2303: 
                   2304: Inputs: $r
                   2305: 
                   2306: Outputs:
                   2307: 
                   2308: =over 4
                   2309: 
1.112     bowersj2 2310: =item * $httpbrowser
1.87      matthew  2311: 
1.112     bowersj2 2312: =item * $clientbrowser
1.87      matthew  2313: 
1.112     bowersj2 2314: =item * $clientversion
1.87      matthew  2315: 
1.112     bowersj2 2316: =item * $clientmathml
1.87      matthew  2317: 
1.112     bowersj2 2318: =item * $clientunicode
1.87      matthew  2319: 
1.112     bowersj2 2320: =item * $clientos
1.87      matthew  2321: 
                   2322: =back
                   2323: 
1.157     matthew  2324: =back 
                   2325: 
1.87      matthew  2326: =cut
                   2327: 
                   2328: ###############################################################
                   2329: ###############################################################
                   2330: sub decode_user_agent {
1.247     albertel 2331:     my ($r)=@_;
1.87      matthew  2332:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2333:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2334:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2335:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2336:     my $clientbrowser='unknown';
                   2337:     my $clientversion='0';
                   2338:     my $clientmathml='';
                   2339:     my $clientunicode='0';
                   2340:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2341:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2342: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2343: 	    $clientbrowser=$bname;
                   2344:             $httpbrowser=~/$vreg/i;
                   2345: 	    $clientversion=$1;
                   2346:             $clientmathml=($clientversion>=$minv);
                   2347:             $clientunicode=($clientversion>=$univ);
                   2348: 	}
                   2349:     }
                   2350:     my $clientos='unknown';
                   2351:     if (($httpbrowser=~/linux/i) ||
                   2352:         ($httpbrowser=~/unix/i) ||
                   2353:         ($httpbrowser=~/ux/i) ||
                   2354:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2355:     if (($httpbrowser=~/vax/i) ||
                   2356:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2357:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2358:     if (($httpbrowser=~/mac/i) ||
                   2359:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2360:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2361:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   2362:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   2363:             $clientunicode,$clientos,);
                   2364: }
                   2365: 
1.32      matthew  2366: ###############################################################
                   2367: ##    Authentication changing form generation subroutines    ##
                   2368: ###############################################################
                   2369: ##
                   2370: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2371: ## hash, and have reasonable default values.
                   2372: ##
                   2373: ##    formname = the name given in the <form> tag.
1.35      matthew  2374: #-------------------------------------------
                   2375: 
1.45      matthew  2376: =pod
                   2377: 
1.112     bowersj2 2378: =head1 Authentication Routines
                   2379: 
                   2380: =over 4
                   2381: 
1.648     raeburn  2382: =item * &authform_xxxxxx()
1.35      matthew  2383: 
                   2384: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2385: handle some of the conveniences required for authentication forms.  
                   2386: This is not an optimal method, but it works.  
                   2387: 
                   2388: =over 4
                   2389: 
1.112     bowersj2 2390: =item * authform_header
1.35      matthew  2391: 
1.112     bowersj2 2392: =item * authform_authorwarning
1.35      matthew  2393: 
1.112     bowersj2 2394: =item * authform_nochange
1.35      matthew  2395: 
1.112     bowersj2 2396: =item * authform_kerberos
1.35      matthew  2397: 
1.112     bowersj2 2398: =item * authform_internal
1.35      matthew  2399: 
1.112     bowersj2 2400: =item * authform_filesystem
1.35      matthew  2401: 
                   2402: =back
                   2403: 
1.648     raeburn  2404: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2405: 
1.35      matthew  2406: =cut
                   2407: 
                   2408: #-------------------------------------------
1.32      matthew  2409: sub authform_header{  
                   2410:     my %in = (
                   2411:         formname => 'cu',
1.80      albertel 2412:         kerb_def_dom => '',
1.32      matthew  2413:         @_,
                   2414:     );
                   2415:     $in{'formname'} = 'document.' . $in{'formname'};
                   2416:     my $result='';
1.80      albertel 2417: 
                   2418: #---------------------------------------------- Code for upper case translation
                   2419:     my $Javascript_toUpperCase;
                   2420:     unless ($in{kerb_def_dom}) {
                   2421:         $Javascript_toUpperCase =<<"END";
                   2422:         switch (choice) {
                   2423:            case 'krb': currentform.elements[choicearg].value =
                   2424:                currentform.elements[choicearg].value.toUpperCase();
                   2425:                break;
                   2426:            default:
                   2427:         }
                   2428: END
                   2429:     } else {
                   2430:         $Javascript_toUpperCase = "";
                   2431:     }
                   2432: 
1.165     raeburn  2433:     my $radioval = "'nochange'";
1.591     raeburn  2434:     if (defined($in{'curr_authtype'})) {
                   2435:         if ($in{'curr_authtype'} ne '') {
                   2436:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2437:         }
1.174     matthew  2438:     }
1.165     raeburn  2439:     my $argfield = 'null';
1.591     raeburn  2440:     if (defined($in{'mode'})) {
1.165     raeburn  2441:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2442:             if (defined($in{'curr_autharg'})) {
                   2443:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2444:                     $argfield = "'$in{'curr_autharg'}'";
                   2445:                 }
                   2446:             }
                   2447:         }
                   2448:     }
                   2449: 
1.32      matthew  2450:     $result.=<<"END";
                   2451: var current = new Object();
1.165     raeburn  2452: current.radiovalue = $radioval;
                   2453: current.argfield = $argfield;
1.32      matthew  2454: 
                   2455: function changed_radio(choice,currentform) {
                   2456:     var choicearg = choice + 'arg';
                   2457:     // If a radio button in changed, we need to change the argfield
                   2458:     if (current.radiovalue != choice) {
                   2459:         current.radiovalue = choice;
                   2460:         if (current.argfield != null) {
                   2461:             currentform.elements[current.argfield].value = '';
                   2462:         }
                   2463:         if (choice == 'nochange') {
                   2464:             current.argfield = null;
                   2465:         } else {
                   2466:             current.argfield = choicearg;
                   2467:             switch(choice) {
                   2468:                 case 'krb': 
                   2469:                     currentform.elements[current.argfield].value = 
                   2470:                         "$in{'kerb_def_dom'}";
                   2471:                 break;
                   2472:               default:
                   2473:                 break;
                   2474:             }
                   2475:         }
                   2476:     }
                   2477:     return;
                   2478: }
1.22      www      2479: 
1.32      matthew  2480: function changed_text(choice,currentform) {
                   2481:     var choicearg = choice + 'arg';
                   2482:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2483:         $Javascript_toUpperCase
1.32      matthew  2484:         // clear old field
                   2485:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2486:             currentform.elements[current.argfield].value = '';
                   2487:         }
                   2488:         current.argfield = choicearg;
                   2489:     }
                   2490:     set_auth_radio_buttons(choice,currentform);
                   2491:     return;
1.20      www      2492: }
1.32      matthew  2493: 
                   2494: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2495:     var numauthchoices = currentform.login.length;
                   2496:     if (typeof numauthchoices  == "undefined") {
                   2497:         return;
                   2498:     } 
1.32      matthew  2499:     var i=0;
1.986     raeburn  2500:     while (i < numauthchoices) {
1.32      matthew  2501:         if (currentform.login[i].value == newvalue) { break; }
                   2502:         i++;
                   2503:     }
1.986     raeburn  2504:     if (i == numauthchoices) {
1.32      matthew  2505:         return;
                   2506:     }
                   2507:     current.radiovalue = newvalue;
                   2508:     currentform.login[i].checked = true;
                   2509:     return;
                   2510: }
                   2511: END
                   2512:     return $result;
                   2513: }
                   2514: 
1.1075.2.20  raeburn  2515: sub authform_authorwarning {
1.32      matthew  2516:     my $result='';
1.144     matthew  2517:     $result='<i>'.
                   2518:         &mt('As a general rule, only authors or co-authors should be '.
                   2519:             'filesystem authenticated '.
                   2520:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2521:     return $result;
                   2522: }
                   2523: 
1.1075.2.20  raeburn  2524: sub authform_nochange {
1.32      matthew  2525:     my %in = (
                   2526:               formname => 'document.cu',
                   2527:               kerb_def_dom => 'MSU.EDU',
                   2528:               @_,
                   2529:           );
1.1075.2.20  raeburn  2530:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2531:     my $result;
1.1075.2.20  raeburn  2532:     if (!$authnum) {
                   2533:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2534:     } else {
                   2535:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2536:                   '<input type="radio" name="login" value="nochange" '.
                   2537:                   'checked="checked" onclick="'.
1.281     albertel 2538:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2539: 	    '</label>';
1.586     raeburn  2540:     }
1.32      matthew  2541:     return $result;
                   2542: }
                   2543: 
1.591     raeburn  2544: sub authform_kerberos {
1.32      matthew  2545:     my %in = (
                   2546:               formname => 'document.cu',
                   2547:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2548:               kerb_def_auth => 'krb4',
1.32      matthew  2549:               @_,
                   2550:               );
1.586     raeburn  2551:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2552:         $autharg,$jscall);
1.1075.2.20  raeburn  2553:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2554:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2555:        $check5 = ' checked="checked"';
1.80      albertel 2556:     } else {
1.772     bisitz   2557:        $check4 = ' checked="checked"';
1.80      albertel 2558:     }
1.165     raeburn  2559:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2560:     if (defined($in{'curr_authtype'})) {
                   2561:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2562:             $krbcheck = ' checked="checked"';
1.623     raeburn  2563:             if (defined($in{'mode'})) {
                   2564:                 if ($in{'mode'} eq 'modifyuser') {
                   2565:                     $krbcheck = '';
                   2566:                 }
                   2567:             }
1.591     raeburn  2568:             if (defined($in{'curr_kerb_ver'})) {
                   2569:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2570:                     $check5 = ' checked="checked"';
1.591     raeburn  2571:                     $check4 = '';
                   2572:                 } else {
1.772     bisitz   2573:                     $check4 = ' checked="checked"';
1.591     raeburn  2574:                     $check5 = '';
                   2575:                 }
1.586     raeburn  2576:             }
1.591     raeburn  2577:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2578:                 $krbarg = $in{'curr_autharg'};
                   2579:             }
1.586     raeburn  2580:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2581:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2582:                     $result = 
                   2583:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2584:         $in{'curr_autharg'},$krbver);
                   2585:                 } else {
                   2586:                     $result =
                   2587:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2588:                 }
                   2589:                 return $result; 
                   2590:             }
                   2591:         }
                   2592:     } else {
                   2593:         if ($authnum == 1) {
1.784     bisitz   2594:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2595:         }
                   2596:     }
1.586     raeburn  2597:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2598:         return;
1.587     raeburn  2599:     } elsif ($authtype eq '') {
1.591     raeburn  2600:         if (defined($in{'mode'})) {
1.587     raeburn  2601:             if ($in{'mode'} eq 'modifycourse') {
                   2602:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2603:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2604:                 }
                   2605:             }
                   2606:         }
1.586     raeburn  2607:     }
                   2608:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2609:     if ($authtype eq '') {
                   2610:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2611:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2612:                     $krbcheck.' />';
                   2613:     }
                   2614:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2615:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2616:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2617:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2618:          $in{'curr_authtype'} eq 'krb4')) {
                   2619:         $result .= &mt
1.144     matthew  2620:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2621:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2622:          '<label>'.$authtype,
1.281     albertel 2623:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2624:              'value="'.$krbarg.'" '.
1.144     matthew  2625:              'onchange="'.$jscall.'" />',
1.281     albertel 2626:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2627:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2628: 	 '</label>');
1.586     raeburn  2629:     } elsif ($can_assign{'krb4'}) {
                   2630:         $result .= &mt
                   2631:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2632:          '[_3] Version 4 [_4]',
                   2633:          '<label>'.$authtype,
                   2634:          '</label><input type="text" size="10" name="krbarg" '.
                   2635:              'value="'.$krbarg.'" '.
                   2636:              'onchange="'.$jscall.'" />',
                   2637:          '<label><input type="hidden" name="krbver" value="4" />',
                   2638:          '</label>');
                   2639:     } elsif ($can_assign{'krb5'}) {
                   2640:         $result .= &mt
                   2641:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2642:          '[_3] Version 5 [_4]',
                   2643:          '<label>'.$authtype,
                   2644:          '</label><input type="text" size="10" name="krbarg" '.
                   2645:              'value="'.$krbarg.'" '.
                   2646:              'onchange="'.$jscall.'" />',
                   2647:          '<label><input type="hidden" name="krbver" value="5" />',
                   2648:          '</label>');
                   2649:     }
1.32      matthew  2650:     return $result;
                   2651: }
                   2652: 
1.1075.2.20  raeburn  2653: sub authform_internal {
1.586     raeburn  2654:     my %in = (
1.32      matthew  2655:                 formname => 'document.cu',
                   2656:                 kerb_def_dom => 'MSU.EDU',
                   2657:                 @_,
                   2658:                 );
1.586     raeburn  2659:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2660:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2661:     if (defined($in{'curr_authtype'})) {
                   2662:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2663:             if ($can_assign{'int'}) {
1.772     bisitz   2664:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2665:                 if (defined($in{'mode'})) {
                   2666:                     if ($in{'mode'} eq 'modifyuser') {
                   2667:                         $intcheck = '';
                   2668:                     }
                   2669:                 }
1.591     raeburn  2670:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2671:                     $intarg = $in{'curr_autharg'};
                   2672:                 }
                   2673:             } else {
                   2674:                 $result = &mt('Currently internally authenticated.');
                   2675:                 return $result;
1.165     raeburn  2676:             }
                   2677:         }
1.586     raeburn  2678:     } else {
                   2679:         if ($authnum == 1) {
1.784     bisitz   2680:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2681:         }
                   2682:     }
                   2683:     if (!$can_assign{'int'}) {
                   2684:         return;
1.587     raeburn  2685:     } elsif ($authtype eq '') {
1.591     raeburn  2686:         if (defined($in{'mode'})) {
1.587     raeburn  2687:             if ($in{'mode'} eq 'modifycourse') {
                   2688:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2689:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2690:                 }
                   2691:             }
                   2692:         }
1.165     raeburn  2693:     }
1.586     raeburn  2694:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2695:     if ($authtype eq '') {
                   2696:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2697:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2698:     }
1.605     bisitz   2699:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2700:                $intarg.'" onchange="'.$jscall.'" />';
                   2701:     $result = &mt
1.144     matthew  2702:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2703:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2704:     $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  2705:     return $result;
                   2706: }
                   2707: 
1.1075.2.20  raeburn  2708: sub authform_local {
1.32      matthew  2709:     my %in = (
                   2710:               formname => 'document.cu',
                   2711:               kerb_def_dom => 'MSU.EDU',
                   2712:               @_,
                   2713:               );
1.586     raeburn  2714:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2715:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2716:     if (defined($in{'curr_authtype'})) {
                   2717:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2718:             if ($can_assign{'loc'}) {
1.772     bisitz   2719:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2720:                 if (defined($in{'mode'})) {
                   2721:                     if ($in{'mode'} eq 'modifyuser') {
                   2722:                         $loccheck = '';
                   2723:                     }
                   2724:                 }
1.591     raeburn  2725:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2726:                     $locarg = $in{'curr_autharg'};
                   2727:                 }
                   2728:             } else {
                   2729:                 $result = &mt('Currently using local (institutional) authentication.');
                   2730:                 return $result;
1.165     raeburn  2731:             }
                   2732:         }
1.586     raeburn  2733:     } else {
                   2734:         if ($authnum == 1) {
1.784     bisitz   2735:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2736:         }
                   2737:     }
                   2738:     if (!$can_assign{'loc'}) {
                   2739:         return;
1.587     raeburn  2740:     } elsif ($authtype eq '') {
1.591     raeburn  2741:         if (defined($in{'mode'})) {
1.587     raeburn  2742:             if ($in{'mode'} eq 'modifycourse') {
                   2743:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2744:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2745:                 }
                   2746:             }
                   2747:         }
1.165     raeburn  2748:     }
1.586     raeburn  2749:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2750:     if ($authtype eq '') {
                   2751:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2752:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2753:                     $jscall.'" />';
                   2754:     }
                   2755:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2756:                $locarg.'" onchange="'.$jscall.'" />';
                   2757:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2758:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2759:     return $result;
                   2760: }
                   2761: 
1.1075.2.20  raeburn  2762: sub authform_filesystem {
1.32      matthew  2763:     my %in = (
                   2764:               formname => 'document.cu',
                   2765:               kerb_def_dom => 'MSU.EDU',
                   2766:               @_,
                   2767:               );
1.586     raeburn  2768:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2769:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2770:     if (defined($in{'curr_authtype'})) {
                   2771:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2772:             if ($can_assign{'fsys'}) {
1.772     bisitz   2773:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2774:                 if (defined($in{'mode'})) {
                   2775:                     if ($in{'mode'} eq 'modifyuser') {
                   2776:                         $fsyscheck = '';
                   2777:                     }
                   2778:                 }
1.586     raeburn  2779:             } else {
                   2780:                 $result = &mt('Currently Filesystem Authenticated.');
                   2781:                 return $result;
                   2782:             }           
                   2783:         }
                   2784:     } else {
                   2785:         if ($authnum == 1) {
1.784     bisitz   2786:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2787:         }
                   2788:     }
                   2789:     if (!$can_assign{'fsys'}) {
                   2790:         return;
1.587     raeburn  2791:     } elsif ($authtype eq '') {
1.591     raeburn  2792:         if (defined($in{'mode'})) {
1.587     raeburn  2793:             if ($in{'mode'} eq 'modifycourse') {
                   2794:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2795:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2796:                 }
                   2797:             }
                   2798:         }
1.586     raeburn  2799:     }
                   2800:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2801:     if ($authtype eq '') {
                   2802:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2803:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2804:                     $jscall.'" />';
                   2805:     }
                   2806:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2807:                ' onchange="'.$jscall.'" />';
                   2808:     $result = &mt
1.144     matthew  2809:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2810:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2811:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2812:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2813:                   'onchange="'.$jscall.'" />');
1.32      matthew  2814:     return $result;
                   2815: }
                   2816: 
1.586     raeburn  2817: sub get_assignable_auth {
                   2818:     my ($dom) = @_;
                   2819:     if ($dom eq '') {
                   2820:         $dom = $env{'request.role.domain'};
                   2821:     }
                   2822:     my %can_assign = (
                   2823:                           krb4 => 1,
                   2824:                           krb5 => 1,
                   2825:                           int  => 1,
                   2826:                           loc  => 1,
                   2827:                      );
                   2828:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2829:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2830:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2831:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2832:             my $context;
                   2833:             if ($env{'request.role'} =~ /^au/) {
                   2834:                 $context = 'author';
                   2835:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2836:                 $context = 'domain';
                   2837:             } elsif ($env{'request.course.id'}) {
                   2838:                 $context = 'course';
                   2839:             }
                   2840:             if ($context) {
                   2841:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2842:                    %can_assign = %{$authhash->{$context}}; 
                   2843:                 }
                   2844:             }
                   2845:         }
                   2846:     }
                   2847:     my $authnum = 0;
                   2848:     foreach my $key (keys(%can_assign)) {
                   2849:         if ($can_assign{$key}) {
                   2850:             $authnum ++;
                   2851:         }
                   2852:     }
                   2853:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2854:         $authnum --;
                   2855:     }
                   2856:     return ($authnum,%can_assign);
                   2857: }
                   2858: 
1.80      albertel 2859: ###############################################################
                   2860: ##    Get Kerberos Defaults for Domain                 ##
                   2861: ###############################################################
                   2862: ##
                   2863: ## Returns default kerberos version and an associated argument
                   2864: ## as listed in file domain.tab. If not listed, provides
                   2865: ## appropriate default domain and kerberos version.
                   2866: ##
                   2867: #-------------------------------------------
                   2868: 
                   2869: =pod
                   2870: 
1.648     raeburn  2871: =item * &get_kerberos_defaults()
1.80      albertel 2872: 
                   2873: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2874: version and domain. If not found, it defaults to version 4 and the 
                   2875: domain of the server.
1.80      albertel 2876: 
1.648     raeburn  2877: =over 4
                   2878: 
1.80      albertel 2879: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2880: 
1.648     raeburn  2881: =back
                   2882: 
                   2883: =back
                   2884: 
1.80      albertel 2885: =cut
                   2886: 
                   2887: #-------------------------------------------
                   2888: sub get_kerberos_defaults {
                   2889:     my $domain=shift;
1.641     raeburn  2890:     my ($krbdef,$krbdefdom);
                   2891:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2892:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2893:         $krbdef = $domdefaults{'auth_def'};
                   2894:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2895:     } else {
1.80      albertel 2896:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2897:         my $krbdefdom=$1;
                   2898:         $krbdefdom=~tr/a-z/A-Z/;
                   2899:         $krbdef = "krb4";
                   2900:     }
                   2901:     return ($krbdef,$krbdefdom);
                   2902: }
1.112     bowersj2 2903: 
1.32      matthew  2904: 
1.46      matthew  2905: ###############################################################
                   2906: ##                Thesaurus Functions                        ##
                   2907: ###############################################################
1.20      www      2908: 
1.46      matthew  2909: =pod
1.20      www      2910: 
1.112     bowersj2 2911: =head1 Thesaurus Functions
                   2912: 
                   2913: =over 4
                   2914: 
1.648     raeburn  2915: =item * &initialize_keywords()
1.46      matthew  2916: 
                   2917: Initializes the package variable %Keywords if it is empty.  Uses the
                   2918: package variable $thesaurus_db_file.
                   2919: 
                   2920: =cut
                   2921: 
                   2922: ###################################################
                   2923: 
                   2924: sub initialize_keywords {
                   2925:     return 1 if (scalar keys(%Keywords));
                   2926:     # If we are here, %Keywords is empty, so fill it up
                   2927:     #   Make sure the file we need exists...
                   2928:     if (! -e $thesaurus_db_file) {
                   2929:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2930:                                  " failed because it does not exist");
                   2931:         return 0;
                   2932:     }
                   2933:     #   Set up the hash as a database
                   2934:     my %thesaurus_db;
                   2935:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2936:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2937:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2938:                                  $thesaurus_db_file);
                   2939:         return 0;
                   2940:     } 
                   2941:     #  Get the average number of appearances of a word.
                   2942:     my $avecount = $thesaurus_db{'average.count'};
                   2943:     #  Put keywords (those that appear > average) into %Keywords
                   2944:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2945:         my ($count,undef) = split /:/,$data;
                   2946:         $Keywords{$word}++ if ($count > $avecount);
                   2947:     }
                   2948:     untie %thesaurus_db;
                   2949:     # Remove special values from %Keywords.
1.356     albertel 2950:     foreach my $value ('total.count','average.count') {
                   2951:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2952:   }
1.46      matthew  2953:     return 1;
                   2954: }
                   2955: 
                   2956: ###################################################
                   2957: 
                   2958: =pod
                   2959: 
1.648     raeburn  2960: =item * &keyword($word)
1.46      matthew  2961: 
                   2962: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2963: than the average number of times in the thesaurus database.  Calls 
                   2964: &initialize_keywords
                   2965: 
                   2966: =cut
                   2967: 
                   2968: ###################################################
1.20      www      2969: 
                   2970: sub keyword {
1.46      matthew  2971:     return if (!&initialize_keywords());
                   2972:     my $word=lc(shift());
                   2973:     $word=~s/\W//g;
                   2974:     return exists($Keywords{$word});
1.20      www      2975: }
1.46      matthew  2976: 
                   2977: ###############################################################
                   2978: 
                   2979: =pod 
1.20      www      2980: 
1.648     raeburn  2981: =item * &get_related_words()
1.46      matthew  2982: 
1.160     matthew  2983: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2984: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2985: will be returned.  The order of the words returned is determined by the
                   2986: database which holds them.
                   2987: 
                   2988: Uses global $thesaurus_db_file.
                   2989: 
1.1057    foxr     2990: 
1.46      matthew  2991: =cut
                   2992: 
                   2993: ###############################################################
                   2994: sub get_related_words {
                   2995:     my $keyword = shift;
                   2996:     my %thesaurus_db;
                   2997:     if (! -e $thesaurus_db_file) {
                   2998:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2999:                                  "failed because the file does not exist");
                   3000:         return ();
                   3001:     }
                   3002:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3003:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3004:         return ();
                   3005:     } 
                   3006:     my @Words=();
1.429     www      3007:     my $count=0;
1.46      matthew  3008:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3009: 	# The first element is the number of times
                   3010: 	# the word appears.  We do not need it now.
1.429     www      3011: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3012: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3013: 	my $threshold=$mostfrequentcount/10;
                   3014:         foreach my $possibleword (@RelatedWords) {
                   3015:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3016:             if ($wordcount>$threshold) {
                   3017: 		push(@Words,$word);
                   3018:                 $count++;
                   3019:                 if ($count>10) { last; }
                   3020: 	    }
1.20      www      3021:         }
                   3022:     }
1.46      matthew  3023:     untie %thesaurus_db;
                   3024:     return @Words;
1.14      harris41 3025: }
1.46      matthew  3026: 
1.112     bowersj2 3027: =pod
                   3028: 
                   3029: =back
                   3030: 
                   3031: =cut
1.61      www      3032: 
                   3033: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3034: =pod
                   3035: 
1.112     bowersj2 3036: =head1 User Name Functions
                   3037: 
                   3038: =over 4
                   3039: 
1.648     raeburn  3040: =item * &plainname($uname,$udom,$first)
1.81      albertel 3041: 
1.112     bowersj2 3042: Takes a users logon name and returns it as a string in
1.226     albertel 3043: "first middle last generation" form 
                   3044: if $first is set to 'lastname' then it returns it as
                   3045: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3046: 
                   3047: =cut
1.61      www      3048: 
1.295     www      3049: 
1.81      albertel 3050: ###############################################################
1.61      www      3051: sub plainname {
1.226     albertel 3052:     my ($uname,$udom,$first)=@_;
1.537     albertel 3053:     return if (!defined($uname) || !defined($udom));
1.295     www      3054:     my %names=&getnames($uname,$udom);
1.226     albertel 3055:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3056: 					  $names{'middlename'},
                   3057: 					  $names{'lastname'},
                   3058: 					  $names{'generation'},$first);
                   3059:     $name=~s/^\s+//;
1.62      www      3060:     $name=~s/\s+$//;
                   3061:     $name=~s/\s+/ /g;
1.353     albertel 3062:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3063:     return $name;
1.61      www      3064: }
1.66      www      3065: 
                   3066: # -------------------------------------------------------------------- Nickname
1.81      albertel 3067: =pod
                   3068: 
1.648     raeburn  3069: =item * &nickname($uname,$udom)
1.81      albertel 3070: 
                   3071: Gets a users name and returns it as a string as
                   3072: 
                   3073: "&quot;nickname&quot;"
1.66      www      3074: 
1.81      albertel 3075: if the user has a nickname or
                   3076: 
                   3077: "first middle last generation"
                   3078: 
                   3079: if the user does not
                   3080: 
                   3081: =cut
1.66      www      3082: 
                   3083: sub nickname {
                   3084:     my ($uname,$udom)=@_;
1.537     albertel 3085:     return if (!defined($uname) || !defined($udom));
1.295     www      3086:     my %names=&getnames($uname,$udom);
1.68      albertel 3087:     my $name=$names{'nickname'};
1.66      www      3088:     if ($name) {
                   3089:        $name='&quot;'.$name.'&quot;'; 
                   3090:     } else {
                   3091:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3092: 	     $names{'lastname'}.' '.$names{'generation'};
                   3093:        $name=~s/\s+$//;
                   3094:        $name=~s/\s+/ /g;
                   3095:     }
                   3096:     return $name;
                   3097: }
                   3098: 
1.295     www      3099: sub getnames {
                   3100:     my ($uname,$udom)=@_;
1.537     albertel 3101:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3102:     if ($udom eq 'public' && $uname eq 'public') {
                   3103: 	return ('lastname' => &mt('Public'));
                   3104:     }
1.295     www      3105:     my $id=$uname.':'.$udom;
                   3106:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3107:     if ($cached) {
                   3108: 	return %{$names};
                   3109:     } else {
                   3110: 	my %loadnames=&Apache::lonnet::get('environment',
                   3111:                     ['firstname','middlename','lastname','generation','nickname'],
                   3112: 					 $udom,$uname);
                   3113: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3114: 	return %loadnames;
                   3115:     }
                   3116: }
1.61      www      3117: 
1.542     raeburn  3118: # -------------------------------------------------------------------- getemails
1.648     raeburn  3119: 
1.542     raeburn  3120: =pod
                   3121: 
1.648     raeburn  3122: =item * &getemails($uname,$udom)
1.542     raeburn  3123: 
                   3124: Gets a user's email information and returns it as a hash with keys:
                   3125: notification, critnotification, permanentemail
                   3126: 
                   3127: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3128: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3129:  
1.648     raeburn  3130: 
1.542     raeburn  3131: =cut
                   3132: 
1.648     raeburn  3133: 
1.466     albertel 3134: sub getemails {
                   3135:     my ($uname,$udom)=@_;
                   3136:     if ($udom eq 'public' && $uname eq 'public') {
                   3137: 	return;
                   3138:     }
1.467     www      3139:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3140:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3141:     my $id=$uname.':'.$udom;
                   3142:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3143:     if ($cached) {
                   3144: 	return %{$names};
                   3145:     } else {
                   3146: 	my %loadnames=&Apache::lonnet::get('environment',
                   3147:                     			   ['notification','critnotification',
                   3148: 					    'permanentemail'],
                   3149: 					   $udom,$uname);
                   3150: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3151: 	return %loadnames;
                   3152:     }
                   3153: }
                   3154: 
1.551     albertel 3155: sub flush_email_cache {
                   3156:     my ($uname,$udom)=@_;
                   3157:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3158:     if (!$uname) { $uname=$env{'user.name'};   }
                   3159:     return if ($udom eq 'public' && $uname eq 'public');
                   3160:     my $id=$uname.':'.$udom;
                   3161:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3162: }
                   3163: 
1.728     raeburn  3164: # -------------------------------------------------------------------- getlangs
                   3165: 
                   3166: =pod
                   3167: 
                   3168: =item * &getlangs($uname,$udom)
                   3169: 
                   3170: Gets a user's language preference and returns it as a hash with key:
                   3171: language.
                   3172: 
                   3173: =cut
                   3174: 
                   3175: 
                   3176: sub getlangs {
                   3177:     my ($uname,$udom) = @_;
                   3178:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3179:     if (!$uname) { $uname=$env{'user.name'};   }
                   3180:     my $id=$uname.':'.$udom;
                   3181:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3182:     if ($cached) {
                   3183:         return %{$langs};
                   3184:     } else {
                   3185:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3186:                                            $udom,$uname);
                   3187:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3188:         return %loadlangs;
                   3189:     }
                   3190: }
                   3191: 
                   3192: sub flush_langs_cache {
                   3193:     my ($uname,$udom)=@_;
                   3194:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3195:     if (!$uname) { $uname=$env{'user.name'};   }
                   3196:     return if ($udom eq 'public' && $uname eq 'public');
                   3197:     my $id=$uname.':'.$udom;
                   3198:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3199: }
                   3200: 
1.61      www      3201: # ------------------------------------------------------------------ Screenname
1.81      albertel 3202: 
                   3203: =pod
                   3204: 
1.648     raeburn  3205: =item * &screenname($uname,$udom)
1.81      albertel 3206: 
                   3207: Gets a users screenname and returns it as a string
                   3208: 
                   3209: =cut
1.61      www      3210: 
                   3211: sub screenname {
                   3212:     my ($uname,$udom)=@_;
1.258     albertel 3213:     if ($uname eq $env{'user.name'} &&
                   3214: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3215:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3216:     return $names{'screenname'};
1.62      www      3217: }
                   3218: 
1.212     albertel 3219: 
1.802     bisitz   3220: # ------------------------------------------------------------- Confirm Wrapper
                   3221: =pod
                   3222: 
                   3223: =item confirmwrapper
                   3224: 
                   3225: Wrap messages about completion of operation in box
                   3226: 
                   3227: =cut
                   3228: 
                   3229: sub confirmwrapper {
                   3230:     my ($message)=@_;
                   3231:     if ($message) {
                   3232:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3233:                .$message."\n"
                   3234:                .'</div>'."\n";
                   3235:     } else {
                   3236:         return $message;
                   3237:     }
                   3238: }
                   3239: 
1.62      www      3240: # ------------------------------------------------------------- Message Wrapper
                   3241: 
                   3242: sub messagewrapper {
1.369     www      3243:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3244:     return 
1.441     albertel 3245:         '<a href="/adm/email?compose=individual&amp;'.
                   3246:         'recname='.$username.'&amp;recdom='.$domain.
                   3247: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3248:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3249: }
1.802     bisitz   3250: 
1.74      www      3251: # --------------------------------------------------------------- Notes Wrapper
                   3252: 
                   3253: sub noteswrapper {
                   3254:     my ($link,$un,$do)=@_;
                   3255:     return 
1.896     amueller 3256: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3257: }
1.802     bisitz   3258: 
1.62      www      3259: # ------------------------------------------------------------- Aboutme Wrapper
                   3260: 
                   3261: sub aboutmewrapper {
1.1070    raeburn  3262:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3263:     if (!defined($username)  && !defined($domain)) {
                   3264:         return;
                   3265:     }
1.1075.2.15  raeburn  3266:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3267: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3268: }
                   3269: 
                   3270: # ------------------------------------------------------------ Syllabus Wrapper
                   3271: 
                   3272: sub syllabuswrapper {
1.707     bisitz   3273:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3274:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3275: }
1.14      harris41 3276: 
1.802     bisitz   3277: # -----------------------------------------------------------------------------
                   3278: 
1.208     matthew  3279: sub track_student_link {
1.887     raeburn  3280:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3281:     my $link ="/adm/trackstudent?";
1.208     matthew  3282:     my $title = 'View recent activity';
                   3283:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3284:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3285:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3286:         $title .= ' of this student';
1.268     albertel 3287:     } 
1.208     matthew  3288:     if (defined($target) && $target !~ /^\s*$/) {
                   3289:         $target = qq{target="$target"};
                   3290:     } else {
                   3291:         $target = '';
                   3292:     }
1.268     albertel 3293:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3294:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3295:     $title = &mt($title);
                   3296:     $linktext = &mt($linktext);
1.448     albertel 3297:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3298: 	&help_open_topic('View_recent_activity');
1.208     matthew  3299: }
                   3300: 
1.781     raeburn  3301: sub slot_reservations_link {
                   3302:     my ($linktext,$sname,$sdom,$target) = @_;
                   3303:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3304:     my $title = 'View slot reservation history';
                   3305:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3306:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3307:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3308:         $title .= ' of this student';
                   3309:     }
                   3310:     if (defined($target) && $target !~ /^\s*$/) {
                   3311:         $target = qq{target="$target"};
                   3312:     } else {
                   3313:         $target = '';
                   3314:     }
                   3315:     $title = &mt($title);
                   3316:     $linktext = &mt($linktext);
                   3317:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3318: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3319: 
                   3320: }
                   3321: 
1.508     www      3322: # ===================================================== Display a student photo
                   3323: 
                   3324: 
1.509     albertel 3325: sub student_image_tag {
1.508     www      3326:     my ($domain,$user)=@_;
                   3327:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3328:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3329: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3330:     } else {
                   3331: 	return '';
                   3332:     }
                   3333: }
                   3334: 
1.112     bowersj2 3335: =pod
                   3336: 
                   3337: =back
                   3338: 
                   3339: =head1 Access .tab File Data
                   3340: 
                   3341: =over 4
                   3342: 
1.648     raeburn  3343: =item * &languageids() 
1.112     bowersj2 3344: 
                   3345: returns list of all language ids
                   3346: 
                   3347: =cut
                   3348: 
1.14      harris41 3349: sub languageids {
1.16      harris41 3350:     return sort(keys(%language));
1.14      harris41 3351: }
                   3352: 
1.112     bowersj2 3353: =pod
                   3354: 
1.648     raeburn  3355: =item * &languagedescription() 
1.112     bowersj2 3356: 
                   3357: returns description of a specified language id
                   3358: 
                   3359: =cut
                   3360: 
1.14      harris41 3361: sub languagedescription {
1.125     www      3362:     my $code=shift;
                   3363:     return  ($supported_language{$code}?'* ':'').
                   3364:             $language{$code}.
1.126     www      3365: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3366: }
                   3367: 
1.1048    foxr     3368: =pod
                   3369: 
                   3370: =item * &plainlanguagedescription
                   3371: 
                   3372: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3373: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3374: 
                   3375: =cut
                   3376: 
1.145     www      3377: sub plainlanguagedescription {
                   3378:     my $code=shift;
                   3379:     return $language{$code};
                   3380: }
                   3381: 
1.1048    foxr     3382: =pod
                   3383: 
                   3384: =item * &supportedlanguagecode
                   3385: 
                   3386: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3387: code.
                   3388: 
                   3389: =cut
                   3390: 
1.145     www      3391: sub supportedlanguagecode {
                   3392:     my $code=shift;
                   3393:     return $supported_language{$code};
1.97      www      3394: }
                   3395: 
1.112     bowersj2 3396: =pod
                   3397: 
1.1048    foxr     3398: =item * &latexlanguage()
                   3399: 
                   3400: Given a language key code returns the correspondnig language to use
                   3401: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3402: is no supported hyphenation for the language code.
                   3403: 
                   3404: =cut
                   3405: 
                   3406: sub latexlanguage {
                   3407:     my $code = shift;
                   3408:     return $latex_language{$code};
                   3409: }
                   3410: 
                   3411: =pod
                   3412: 
                   3413: =item * &latexhyphenation()
                   3414: 
                   3415: Same as above but what's supplied is the language as it might be stored
                   3416: in the metadata.
                   3417: 
                   3418: =cut
                   3419: 
                   3420: sub latexhyphenation {
                   3421:     my $key = shift;
                   3422:     return $latex_language_bykey{$key};
                   3423: }
                   3424: 
                   3425: =pod
                   3426: 
1.648     raeburn  3427: =item * &copyrightids() 
1.112     bowersj2 3428: 
                   3429: returns list of all copyrights
                   3430: 
                   3431: =cut
                   3432: 
                   3433: sub copyrightids {
                   3434:     return sort(keys(%cprtag));
                   3435: }
                   3436: 
                   3437: =pod
                   3438: 
1.648     raeburn  3439: =item * &copyrightdescription() 
1.112     bowersj2 3440: 
                   3441: returns description of a specified copyright id
                   3442: 
                   3443: =cut
                   3444: 
                   3445: sub copyrightdescription {
1.166     www      3446:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3447: }
1.197     matthew  3448: 
                   3449: =pod
                   3450: 
1.648     raeburn  3451: =item * &source_copyrightids() 
1.192     taceyjo1 3452: 
                   3453: returns list of all source copyrights
                   3454: 
                   3455: =cut
                   3456: 
                   3457: sub source_copyrightids {
                   3458:     return sort(keys(%scprtag));
                   3459: }
                   3460: 
                   3461: =pod
                   3462: 
1.648     raeburn  3463: =item * &source_copyrightdescription() 
1.192     taceyjo1 3464: 
                   3465: returns description of a specified source copyright id
                   3466: 
                   3467: =cut
                   3468: 
                   3469: sub source_copyrightdescription {
                   3470:     return &mt($scprtag{shift(@_)});
                   3471: }
1.112     bowersj2 3472: 
                   3473: =pod
                   3474: 
1.648     raeburn  3475: =item * &filecategories() 
1.112     bowersj2 3476: 
                   3477: returns list of all file categories
                   3478: 
                   3479: =cut
                   3480: 
                   3481: sub filecategories {
                   3482:     return sort(keys(%category_extensions));
                   3483: }
                   3484: 
                   3485: =pod
                   3486: 
1.648     raeburn  3487: =item * &filecategorytypes() 
1.112     bowersj2 3488: 
                   3489: returns list of file types belonging to a given file
                   3490: category
                   3491: 
                   3492: =cut
                   3493: 
                   3494: sub filecategorytypes {
1.356     albertel 3495:     my ($cat) = @_;
                   3496:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3497: }
                   3498: 
                   3499: =pod
                   3500: 
1.648     raeburn  3501: =item * &fileembstyle() 
1.112     bowersj2 3502: 
                   3503: returns embedding style for a specified file type
                   3504: 
                   3505: =cut
                   3506: 
                   3507: sub fileembstyle {
                   3508:     return $fe{lc(shift(@_))};
1.169     www      3509: }
                   3510: 
1.351     www      3511: sub filemimetype {
                   3512:     return $fm{lc(shift(@_))};
                   3513: }
                   3514: 
1.169     www      3515: 
                   3516: sub filecategoryselect {
                   3517:     my ($name,$value)=@_;
1.189     matthew  3518:     return &select_form($value,$name,
1.970     raeburn  3519:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3520: }
                   3521: 
                   3522: =pod
                   3523: 
1.648     raeburn  3524: =item * &filedescription() 
1.112     bowersj2 3525: 
                   3526: returns description for a specified file type
                   3527: 
                   3528: =cut
                   3529: 
                   3530: sub filedescription {
1.188     matthew  3531:     my $file_description = $fd{lc(shift())};
                   3532:     $file_description =~ s:([\[\]]):~$1:g;
                   3533:     return &mt($file_description);
1.112     bowersj2 3534: }
                   3535: 
                   3536: =pod
                   3537: 
1.648     raeburn  3538: =item * &filedescriptionex() 
1.112     bowersj2 3539: 
                   3540: returns description for a specified file type with
                   3541: extra formatting
                   3542: 
                   3543: =cut
                   3544: 
                   3545: sub filedescriptionex {
                   3546:     my $ex=shift;
1.188     matthew  3547:     my $file_description = $fd{lc($ex)};
                   3548:     $file_description =~ s:([\[\]]):~$1:g;
                   3549:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3550: }
                   3551: 
                   3552: # End of .tab access
                   3553: =pod
                   3554: 
                   3555: =back
                   3556: 
                   3557: =cut
                   3558: 
                   3559: # ------------------------------------------------------------------ File Types
                   3560: sub fileextensions {
                   3561:     return sort(keys(%fe));
                   3562: }
                   3563: 
1.97      www      3564: # ----------------------------------------------------------- Display Languages
                   3565: # returns a hash with all desired display languages
                   3566: #
                   3567: 
                   3568: sub display_languages {
                   3569:     my %languages=();
1.695     raeburn  3570:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3571: 	$languages{$lang}=1;
1.97      www      3572:     }
                   3573:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3574:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3575: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3576: 	    $languages{$lang}=1;
1.97      www      3577:         }
                   3578:     }
                   3579:     return %languages;
1.14      harris41 3580: }
                   3581: 
1.582     albertel 3582: sub languages {
                   3583:     my ($possible_langs) = @_;
1.695     raeburn  3584:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3585:     if (!ref($possible_langs)) {
                   3586: 	if( wantarray ) {
                   3587: 	    return @preferred_langs;
                   3588: 	} else {
                   3589: 	    return $preferred_langs[0];
                   3590: 	}
                   3591:     }
                   3592:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3593:     my @preferred_possibilities;
                   3594:     foreach my $preferred_lang (@preferred_langs) {
                   3595: 	if (exists($possibilities{$preferred_lang})) {
                   3596: 	    push(@preferred_possibilities, $preferred_lang);
                   3597: 	}
                   3598:     }
                   3599:     if( wantarray ) {
                   3600: 	return @preferred_possibilities;
                   3601:     }
                   3602:     return $preferred_possibilities[0];
                   3603: }
                   3604: 
1.742     raeburn  3605: sub user_lang {
                   3606:     my ($touname,$toudom,$fromcid) = @_;
                   3607:     my @userlangs;
                   3608:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3609:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3610:                     $env{'course.'.$fromcid.'.languages'}));
                   3611:     } else {
                   3612:         my %langhash = &getlangs($touname,$toudom);
                   3613:         if ($langhash{'languages'} ne '') {
                   3614:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3615:         } else {
                   3616:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3617:             if ($domdefs{'lang_def'} ne '') {
                   3618:                 @userlangs = ($domdefs{'lang_def'});
                   3619:             }
                   3620:         }
                   3621:     }
                   3622:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3623:     my $user_lh = Apache::localize->get_handle(@languages);
                   3624:     return $user_lh;
                   3625: }
                   3626: 
                   3627: 
1.112     bowersj2 3628: ###############################################################
                   3629: ##               Student Answer Attempts                     ##
                   3630: ###############################################################
                   3631: 
                   3632: =pod
                   3633: 
                   3634: =head1 Alternate Problem Views
                   3635: 
                   3636: =over 4
                   3637: 
1.648     raeburn  3638: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3639:     $getattempt, $regexp, $gradesub)
                   3640: 
                   3641: Return string with previous attempt on problem. Arguments:
                   3642: 
                   3643: =over 4
                   3644: 
                   3645: =item * $symb: Problem, including path
                   3646: 
                   3647: =item * $username: username of the desired student
                   3648: 
                   3649: =item * $domain: domain of the desired student
1.14      harris41 3650: 
1.112     bowersj2 3651: =item * $course: Course ID
1.14      harris41 3652: 
1.112     bowersj2 3653: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3654:     something
1.14      harris41 3655: 
1.112     bowersj2 3656: =item * $regexp: if string matches this regexp, the string will be
                   3657:     sent to $gradesub
1.14      harris41 3658: 
1.112     bowersj2 3659: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3660: 
1.112     bowersj2 3661: =back
1.14      harris41 3662: 
1.112     bowersj2 3663: The output string is a table containing all desired attempts, if any.
1.16      harris41 3664: 
1.112     bowersj2 3665: =cut
1.1       albertel 3666: 
                   3667: sub get_previous_attempt {
1.43      ng       3668:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3669:   my $prevattempts='';
1.43      ng       3670:   no strict 'refs';
1.1       albertel 3671:   if ($symb) {
1.3       albertel 3672:     my (%returnhash)=
                   3673:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3674:     if ($returnhash{'version'}) {
                   3675:       my %lasthash=();
                   3676:       my $version;
                   3677:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3678:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3679: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3680:         }
1.1       albertel 3681:       }
1.596     albertel 3682:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3683:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3684:       my (%typeparts,%lasthidden);
1.945     raeburn  3685:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3686:       foreach my $key (sort(keys(%lasthash))) {
                   3687: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3688: 	if ($#parts > 0) {
1.31      albertel 3689: 	  my $data=$parts[-1];
1.989     raeburn  3690:           next if ($data eq 'foilorder');
1.31      albertel 3691: 	  pop(@parts);
1.1010    www      3692:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3693:           if ($data eq 'type') {
                   3694:               unless ($showsurv) {
                   3695:                   my $id = join(',',@parts);
                   3696:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3697:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3698:                       $lasthidden{$ign.'.'.$id} = 1;
                   3699:                   }
1.945     raeburn  3700:               }
1.1010    www      3701:           } 
1.31      albertel 3702: 	} else {
1.41      ng       3703: 	  if ($#parts == 0) {
                   3704: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3705: 	  } else {
                   3706: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3707: 	  }
1.31      albertel 3708: 	}
1.16      harris41 3709:       }
1.596     albertel 3710:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3711:       if ($getattempt eq '') {
                   3712: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3713:             my @hidden;
                   3714:             if (%typeparts) {
                   3715:                 foreach my $id (keys(%typeparts)) {
                   3716:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3717:                         push(@hidden,$id);
                   3718:                     }
                   3719:                 }
                   3720:             }
                   3721:             $prevattempts.=&start_data_table_row().
                   3722:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3723:             if (@hidden) {
                   3724:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3725:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3726:                     my $hide;
                   3727:                     foreach my $id (@hidden) {
                   3728:                         if ($key =~ /^\Q$id\E/) {
                   3729:                             $hide = 1;
                   3730:                             last;
                   3731:                         }
                   3732:                     }
                   3733:                     if ($hide) {
                   3734:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3735:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3736:                             my $value = &format_previous_attempt_value($key,
                   3737:                                              $returnhash{$version.':'.$key});
                   3738:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3739:                         } else {
                   3740:                             $prevattempts.='<td>&nbsp;</td>';
                   3741:                         }
                   3742:                     } else {
                   3743:                         if ($key =~ /\./) {
                   3744:                             my $value = &format_previous_attempt_value($key,
                   3745:                                               $returnhash{$version.':'.$key});
                   3746:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3747:                         } else {
                   3748:                             $prevattempts.='<td>&nbsp;</td>';
                   3749:                         }
                   3750:                     }
                   3751:                 }
                   3752:             } else {
                   3753: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3754:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3755: 		    my $value = &format_previous_attempt_value($key,
                   3756: 			            $returnhash{$version.':'.$key});
                   3757: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3758: 	        }
                   3759:             }
                   3760: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3761: 	 }
1.1       albertel 3762:       }
1.945     raeburn  3763:       my @currhidden = keys(%lasthidden);
1.596     albertel 3764:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3765:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3766:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3767:           if (%typeparts) {
                   3768:               my $hidden;
                   3769:               foreach my $id (@currhidden) {
                   3770:                   if ($key =~ /^\Q$id\E/) {
                   3771:                       $hidden = 1;
                   3772:                       last;
                   3773:                   }
                   3774:               }
                   3775:               if ($hidden) {
                   3776:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3777:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3778:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3779:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3780:                           $value = &$gradesub($value);
                   3781:                       }
                   3782:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3783:                   } else {
                   3784:                       $prevattempts.='<td>&nbsp;</td>';
                   3785:                   }
                   3786:               } else {
                   3787:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3788:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3789:                       $value = &$gradesub($value);
                   3790:                   }
                   3791:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3792:               }
                   3793:           } else {
                   3794: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3795: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3796:                   $value = &$gradesub($value);
                   3797:               }
                   3798: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3799:           }
1.16      harris41 3800:       }
1.596     albertel 3801:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3802:     } else {
1.596     albertel 3803:       $prevattempts=
                   3804: 	  &start_data_table().&start_data_table_row().
                   3805: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3806: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3807:     }
                   3808:   } else {
1.596     albertel 3809:     $prevattempts=
                   3810: 	  &start_data_table().&start_data_table_row().
                   3811: 	  '<td>'.&mt('No data.').'</td>'.
                   3812: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3813:   }
1.10      albertel 3814: }
                   3815: 
1.581     albertel 3816: sub format_previous_attempt_value {
                   3817:     my ($key,$value) = @_;
1.1011    www      3818:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3819: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3820:     } elsif (ref($value) eq 'ARRAY') {
                   3821: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3822:     } elsif ($key =~ /answerstring$/) {
                   3823:         my %answers = &Apache::lonnet::str2hash($value);
                   3824:         my @anskeys = sort(keys(%answers));
                   3825:         if (@anskeys == 1) {
                   3826:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3827:             if ($answer =~ m{\0}) {
                   3828:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3829:             }
                   3830:             my $tag_internal_answer_name = 'INTERNAL';
                   3831:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3832:                 $value = $answer; 
                   3833:             } else {
                   3834:                 $value = $anskeys[0].'='.$answer;
                   3835:             }
                   3836:         } else {
                   3837:             foreach my $ans (@anskeys) {
                   3838:                 my $answer = $answers{$ans};
1.1001    raeburn  3839:                 if ($answer =~ m{\0}) {
                   3840:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3841:                 }
                   3842:                 $value .=  $ans.'='.$answer.'<br />';;
                   3843:             } 
                   3844:         }
1.581     albertel 3845:     } else {
                   3846: 	$value = &unescape($value);
                   3847:     }
                   3848:     return $value;
                   3849: }
                   3850: 
                   3851: 
1.107     albertel 3852: sub relative_to_absolute {
                   3853:     my ($url,$output)=@_;
                   3854:     my $parser=HTML::TokeParser->new(\$output);
                   3855:     my $token;
                   3856:     my $thisdir=$url;
                   3857:     my @rlinks=();
                   3858:     while ($token=$parser->get_token) {
                   3859: 	if ($token->[0] eq 'S') {
                   3860: 	    if ($token->[1] eq 'a') {
                   3861: 		if ($token->[2]->{'href'}) {
                   3862: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3863: 		}
                   3864: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3865: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3866: 	    } elsif ($token->[1] eq 'base') {
                   3867: 		$thisdir=$token->[2]->{'href'};
                   3868: 	    }
                   3869: 	}
                   3870:     }
                   3871:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3872:     foreach my $link (@rlinks) {
1.726     raeburn  3873: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3874: 		($link=~/^\//) ||
                   3875: 		($link=~/^javascript:/i) ||
                   3876: 		($link=~/^mailto:/i) ||
                   3877: 		($link=~/^\#/)) {
                   3878: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3879: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3880: 	}
                   3881:     }
                   3882: # -------------------------------------------------- Deal with Applet codebases
                   3883:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3884:     return $output;
                   3885: }
                   3886: 
1.112     bowersj2 3887: =pod
                   3888: 
1.648     raeburn  3889: =item * &get_student_view()
1.112     bowersj2 3890: 
                   3891: show a snapshot of what student was looking at
                   3892: 
                   3893: =cut
                   3894: 
1.10      albertel 3895: sub get_student_view {
1.186     albertel 3896:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3897:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3898:   my (%form);
1.10      albertel 3899:   my @elements=('symb','courseid','domain','username');
                   3900:   foreach my $element (@elements) {
1.186     albertel 3901:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3902:   }
1.186     albertel 3903:   if (defined($moreenv)) {
                   3904:       %form=(%form,%{$moreenv});
                   3905:   }
1.236     albertel 3906:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3907:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3908:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3909:   $userview=~s/\<body[^\>]*\>//gi;
                   3910:   $userview=~s/\<\/body\>//gi;
                   3911:   $userview=~s/\<html\>//gi;
                   3912:   $userview=~s/\<\/html\>//gi;
                   3913:   $userview=~s/\<head\>//gi;
                   3914:   $userview=~s/\<\/head\>//gi;
                   3915:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3916:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3917:   if (wantarray) {
                   3918:      return ($userview,$response);
                   3919:   } else {
                   3920:      return $userview;
                   3921:   }
                   3922: }
                   3923: 
                   3924: sub get_student_view_with_retries {
                   3925:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3926: 
                   3927:     my $ok = 0;                 # True if we got a good response.
                   3928:     my $content;
                   3929:     my $response;
                   3930: 
                   3931:     # Try to get the student_view done. within the retries count:
                   3932:     
                   3933:     do {
                   3934:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3935:          $ok      = $response->is_success;
                   3936:          if (!$ok) {
                   3937:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3938:          }
                   3939:          $retries--;
                   3940:     } while (!$ok && ($retries > 0));
                   3941:     
                   3942:     if (!$ok) {
                   3943:        $content = '';          # On error return an empty content.
                   3944:     }
1.651     www      3945:     if (wantarray) {
                   3946:        return ($content, $response);
                   3947:     } else {
                   3948:        return $content;
                   3949:     }
1.11      albertel 3950: }
                   3951: 
1.112     bowersj2 3952: =pod
                   3953: 
1.648     raeburn  3954: =item * &get_student_answers() 
1.112     bowersj2 3955: 
                   3956: show a snapshot of how student was answering problem
                   3957: 
                   3958: =cut
                   3959: 
1.11      albertel 3960: sub get_student_answers {
1.100     sakharuk 3961:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3962:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3963:   my (%moreenv);
1.11      albertel 3964:   my @elements=('symb','courseid','domain','username');
                   3965:   foreach my $element (@elements) {
1.186     albertel 3966:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3967:   }
1.186     albertel 3968:   $moreenv{'grade_target'}='answer';
                   3969:   %moreenv=(%form,%moreenv);
1.497     raeburn  3970:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3971:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3972:   return $userview;
1.1       albertel 3973: }
1.116     albertel 3974: 
                   3975: =pod
                   3976: 
                   3977: =item * &submlink()
                   3978: 
1.242     albertel 3979: Inputs: $text $uname $udom $symb $target
1.116     albertel 3980: 
                   3981: Returns: A link to grades.pm such as to see the SUBM view of a student
                   3982: 
                   3983: =cut
                   3984: 
                   3985: ###############################################
                   3986: sub submlink {
1.242     albertel 3987:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 3988:     if (!($uname && $udom)) {
                   3989: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 3990: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 3991: 	if (!$symb) { $symb=$cursymb; }
                   3992:     }
1.254     matthew  3993:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      3994:     $symb=&escape($symb);
1.960     bisitz   3995:     if ($target) { $target=" target=\"$target\""; }
                   3996:     return
                   3997:         '<a href="/adm/grades?command=submission'.
                   3998:         '&amp;symb='.$symb.
                   3999:         '&amp;student='.$uname.
                   4000:         '&amp;userdom='.$udom.'"'.
                   4001:         $target.'>'.$text.'</a>';
1.242     albertel 4002: }
                   4003: ##############################################
                   4004: 
                   4005: =pod
                   4006: 
                   4007: =item * &pgrdlink()
                   4008: 
                   4009: Inputs: $text $uname $udom $symb $target
                   4010: 
                   4011: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4012: 
                   4013: =cut
                   4014: 
                   4015: ###############################################
                   4016: sub pgrdlink {
                   4017:     my $link=&submlink(@_);
                   4018:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4019:     return $link;
                   4020: }
                   4021: ##############################################
                   4022: 
                   4023: =pod
                   4024: 
                   4025: =item * &pprmlink()
                   4026: 
                   4027: Inputs: $text $uname $udom $symb $target
                   4028: 
                   4029: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4030: student and a specific resource
1.242     albertel 4031: 
                   4032: =cut
                   4033: 
                   4034: ###############################################
                   4035: sub pprmlink {
                   4036:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4037:     if (!($uname && $udom)) {
                   4038: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4039: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4040: 	if (!$symb) { $symb=$cursymb; }
                   4041:     }
1.254     matthew  4042:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4043:     $symb=&escape($symb);
1.242     albertel 4044:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4045:     return '<a href="/adm/parmset?command=set&amp;'.
                   4046: 	'symb='.$symb.'&amp;uname='.$uname.
                   4047: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4048: }
                   4049: ##############################################
1.37      matthew  4050: 
1.112     bowersj2 4051: =pod
                   4052: 
                   4053: =back
                   4054: 
                   4055: =cut
                   4056: 
1.37      matthew  4057: ###############################################
1.51      www      4058: 
                   4059: 
                   4060: sub timehash {
1.687     raeburn  4061:     my ($thistime) = @_;
                   4062:     my $timezone = &Apache::lonlocal::gettimezone();
                   4063:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4064:                      ->set_time_zone($timezone);
                   4065:     my $wday = $dt->day_of_week();
                   4066:     if ($wday == 7) { $wday = 0; }
                   4067:     return ( 'second' => $dt->second(),
                   4068:              'minute' => $dt->minute(),
                   4069:              'hour'   => $dt->hour(),
                   4070:              'day'     => $dt->day_of_month(),
                   4071:              'month'   => $dt->month(),
                   4072:              'year'    => $dt->year(),
                   4073:              'weekday' => $wday,
                   4074:              'dayyear' => $dt->day_of_year(),
                   4075:              'dlsav'   => $dt->is_dst() );
1.51      www      4076: }
                   4077: 
1.370     www      4078: sub utc_string {
                   4079:     my ($date)=@_;
1.371     www      4080:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4081: }
                   4082: 
1.51      www      4083: sub maketime {
                   4084:     my %th=@_;
1.687     raeburn  4085:     my ($epoch_time,$timezone,$dt);
                   4086:     $timezone = &Apache::lonlocal::gettimezone();
                   4087:     eval {
                   4088:         $dt = DateTime->new( year   => $th{'year'},
                   4089:                              month  => $th{'month'},
                   4090:                              day    => $th{'day'},
                   4091:                              hour   => $th{'hour'},
                   4092:                              minute => $th{'minute'},
                   4093:                              second => $th{'second'},
                   4094:                              time_zone => $timezone,
                   4095:                          );
                   4096:     };
                   4097:     if (!$@) {
                   4098:         $epoch_time = $dt->epoch;
                   4099:         if ($epoch_time) {
                   4100:             return $epoch_time;
                   4101:         }
                   4102:     }
1.51      www      4103:     return POSIX::mktime(
                   4104:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4105:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4106: }
                   4107: 
                   4108: #########################################
1.51      www      4109: 
                   4110: sub findallcourses {
1.482     raeburn  4111:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4112:     my %roles;
                   4113:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4114:     my %courses;
1.51      www      4115:     my $now=time;
1.482     raeburn  4116:     if (!defined($uname)) {
                   4117:         $uname = $env{'user.name'};
                   4118:     }
                   4119:     if (!defined($udom)) {
                   4120:         $udom = $env{'user.domain'};
                   4121:     }
                   4122:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4123:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4124:         if (!%roles) {
                   4125:             %roles = (
                   4126:                        cc => 1,
1.907     raeburn  4127:                        co => 1,
1.482     raeburn  4128:                        in => 1,
                   4129:                        ep => 1,
                   4130:                        ta => 1,
                   4131:                        cr => 1,
                   4132:                        st => 1,
                   4133:              );
                   4134:         }
                   4135:         foreach my $entry (keys(%roleshash)) {
                   4136:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4137:             if ($trole =~ /^cr/) { 
                   4138:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4139:             } else {
                   4140:                 next if (!exists($roles{$trole}));
                   4141:             }
                   4142:             if ($tend) {
                   4143:                 next if ($tend < $now);
                   4144:             }
                   4145:             if ($tstart) {
                   4146:                 next if ($tstart > $now);
                   4147:             }
1.1058    raeburn  4148:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4149:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4150:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4151:             if ($secpart eq '') {
                   4152:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4153:                 $sec = 'none';
1.1058    raeburn  4154:                 $value .= $cnum.'/';
1.482     raeburn  4155:             } else {
                   4156:                 $cnum = $cnumpart;
                   4157:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4158:                 $value .= $cnum.'/'.$sec;
                   4159:             }
                   4160:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4161:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4162:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4163:                 }
                   4164:             } else {
                   4165:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4166:             }
1.482     raeburn  4167:         }
                   4168:     } else {
                   4169:         foreach my $key (keys(%env)) {
1.483     albertel 4170: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4171:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4172: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4173: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4174: 	        next if (%roles && !exists($roles{$role}));
                   4175: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4176:                 my $active=1;
                   4177:                 if ($starttime) {
                   4178: 		    if ($now<$starttime) { $active=0; }
                   4179:                 }
                   4180:                 if ($endtime) {
                   4181:                     if ($now>$endtime) { $active=0; }
                   4182:                 }
                   4183:                 if ($active) {
1.1058    raeburn  4184:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4185:                     if ($sec eq '') {
                   4186:                         $sec = 'none';
1.1058    raeburn  4187:                     } else {
                   4188:                         $value .= $sec;
                   4189:                     }
                   4190:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4191:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4192:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4193:                         }
                   4194:                     } else {
                   4195:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4196:                     }
1.474     raeburn  4197:                 }
                   4198:             }
1.51      www      4199:         }
                   4200:     }
1.474     raeburn  4201:     return %courses;
1.51      www      4202: }
1.37      matthew  4203: 
1.54      www      4204: ###############################################
1.474     raeburn  4205: 
                   4206: sub blockcheck {
1.1062    raeburn  4207:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4208: 
                   4209:     if (!defined($udom)) {
                   4210:         $udom = $env{'user.domain'};
                   4211:     }
                   4212:     if (!defined($uname)) {
                   4213:         $uname = $env{'user.name'};
                   4214:     }
                   4215: 
                   4216:     # If uname and udom are for a course, check for blocks in the course.
                   4217: 
                   4218:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4219:         my ($startblock,$endblock,$triggerblock) = 
                   4220:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4221:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4222:     }
1.474     raeburn  4223: 
1.502     raeburn  4224:     my $startblock = 0;
                   4225:     my $endblock = 0;
1.1062    raeburn  4226:     my $triggerblock = '';
1.482     raeburn  4227:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4228: 
1.490     raeburn  4229:     # If uname is for a user, and activity is course-specific, i.e.,
                   4230:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4231: 
1.490     raeburn  4232:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4233:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4234:         foreach my $key (keys(%live_courses)) {
                   4235:             if ($key ne $env{'request.course.id'}) {
                   4236:                 delete($live_courses{$key});
                   4237:             }
                   4238:         }
                   4239:     }
                   4240: 
                   4241:     my $otheruser = 0;
                   4242:     my %own_courses;
                   4243:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4244:         # Resource belongs to user other than current user.
                   4245:         $otheruser = 1;
                   4246:         # Gather courses for current user
                   4247:         %own_courses = 
                   4248:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4249:     }
                   4250: 
                   4251:     # Gather active course roles - course coordinator, instructor, 
                   4252:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4253: 
                   4254:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4255:         my ($cdom,$cnum);
                   4256:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4257:             $cdom = $env{'course.'.$course.'.domain'};
                   4258:             $cnum = $env{'course.'.$course.'.num'};
                   4259:         } else {
1.490     raeburn  4260:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4261:         }
                   4262:         my $no_ownblock = 0;
                   4263:         my $no_userblock = 0;
1.533     raeburn  4264:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4265:             # Check if current user has 'evb' priv for this
                   4266:             if (defined($own_courses{$course})) {
                   4267:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4268:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4269:                     if ($sec ne 'none') {
                   4270:                         $checkrole .= '/'.$sec;
                   4271:                     }
                   4272:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4273:                         $no_ownblock = 1;
                   4274:                         last;
                   4275:                     }
                   4276:                 }
                   4277:             }
                   4278:             # if they have 'evb' priv and are currently not playing student
                   4279:             next if (($no_ownblock) &&
                   4280:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4281:         }
1.474     raeburn  4282:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4283:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4284:             if ($sec ne 'none') {
1.482     raeburn  4285:                 $checkrole .= '/'.$sec;
1.474     raeburn  4286:             }
1.490     raeburn  4287:             if ($otheruser) {
                   4288:                 # Resource belongs to user other than current user.
                   4289:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4290:                 my (%allroles,%userroles);
                   4291:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4292:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4293:                         my ($trole,$tdom,$tnum,$tsec);
                   4294:                         if ($entry =~ /^cr/) {
                   4295:                             ($trole,$tdom,$tnum,$tsec) = 
                   4296:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4297:                         } else {
                   4298:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4299:                         }
                   4300:                         my ($spec,$area,$trest);
                   4301:                         $area = '/'.$tdom.'/'.$tnum;
                   4302:                         $trest = $tnum;
                   4303:                         if ($tsec ne '') {
                   4304:                             $area .= '/'.$tsec;
                   4305:                             $trest .= '/'.$tsec;
                   4306:                         }
                   4307:                         $spec = $trole.'.'.$area;
                   4308:                         if ($trole =~ /^cr/) {
                   4309:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4310:                                                               $tdom,$spec,$trest,$area);
                   4311:                         } else {
                   4312:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4313:                                                                 $tdom,$spec,$trest,$area);
                   4314:                         }
                   4315:                     }
                   4316:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4317:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4318:                         if ($1) {
                   4319:                             $no_userblock = 1;
                   4320:                             last;
                   4321:                         }
1.486     raeburn  4322:                     }
                   4323:                 }
1.490     raeburn  4324:             } else {
                   4325:                 # Resource belongs to current user
                   4326:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4327:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4328:                     $no_ownblock = 1;
                   4329:                     last;
                   4330:                 }
1.474     raeburn  4331:             }
                   4332:         }
                   4333:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4334:         next if (($no_ownblock) &&
1.491     albertel 4335:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4336:         next if ($no_userblock);
1.474     raeburn  4337: 
1.866     kalberla 4338:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4339:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4340:         
1.1062    raeburn  4341:         my ($start,$end,$trigger) = 
                   4342:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4343:         if (($start != 0) && 
                   4344:             (($startblock == 0) || ($startblock > $start))) {
                   4345:             $startblock = $start;
1.1062    raeburn  4346:             if ($trigger ne '') {
                   4347:                 $triggerblock = $trigger;
                   4348:             }
1.502     raeburn  4349:         }
                   4350:         if (($end != 0)  &&
                   4351:             (($endblock == 0) || ($endblock < $end))) {
                   4352:             $endblock = $end;
1.1062    raeburn  4353:             if ($trigger ne '') {
                   4354:                 $triggerblock = $trigger;
                   4355:             }
1.502     raeburn  4356:         }
1.490     raeburn  4357:     }
1.1062    raeburn  4358:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4359: }
                   4360: 
                   4361: sub get_blocks {
1.1062    raeburn  4362:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4363:     my $startblock = 0;
                   4364:     my $endblock = 0;
1.1062    raeburn  4365:     my $triggerblock = '';
1.490     raeburn  4366:     my $course = $cdom.'_'.$cnum;
                   4367:     $setters->{$course} = {};
                   4368:     $setters->{$course}{'staff'} = [];
                   4369:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4370:     $setters->{$course}{'triggers'} = [];
                   4371:     my (@blockers,%triggered);
                   4372:     my $now = time;
                   4373:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4374:     if ($activity eq 'docs') {
                   4375:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4376:         foreach my $block (@blockers) {
                   4377:             if ($block =~ /^firstaccess____(.+)$/) {
                   4378:                 my $item = $1;
                   4379:                 my $type = 'map';
                   4380:                 my $timersymb = $item;
                   4381:                 if ($item eq 'course') {
                   4382:                     $type = 'course';
                   4383:                 } elsif ($item =~ /___\d+___/) {
                   4384:                     $type = 'resource';
                   4385:                 } else {
                   4386:                     $timersymb = &Apache::lonnet::symbread($item);
                   4387:                 }
                   4388:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4389:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4390:                 $triggered{$block} = {
                   4391:                                        start => $start,
                   4392:                                        end   => $end,
                   4393:                                        type  => $type,
                   4394:                                      };
                   4395:             }
                   4396:         }
                   4397:     } else {
                   4398:         foreach my $block (keys(%commblocks)) {
                   4399:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4400:                 my ($start,$end) = ($1,$2);
                   4401:                 if ($start <= time && $end >= time) {
                   4402:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4403:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4404:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4405:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4406:                                     push(@blockers,$block);
                   4407:                                 }
                   4408:                             }
                   4409:                         }
                   4410:                     }
                   4411:                 }
                   4412:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4413:                 my $item = $1;
                   4414:                 my $timersymb = $item; 
                   4415:                 my $type = 'map';
                   4416:                 if ($item eq 'course') {
                   4417:                     $type = 'course';
                   4418:                 } elsif ($item =~ /___\d+___/) {
                   4419:                     $type = 'resource';
                   4420:                 } else {
                   4421:                     $timersymb = &Apache::lonnet::symbread($item);
                   4422:                 }
                   4423:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4424:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4425:                 if ($start && $end) {
                   4426:                     if (($start <= time) && ($end >= time)) {
                   4427:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4428:                             push(@blockers,$block);
                   4429:                             $triggered{$block} = {
                   4430:                                                    start => $start,
                   4431:                                                    end   => $end,
                   4432:                                                    type  => $type,
                   4433:                                                  };
                   4434:                         }
                   4435:                     }
1.490     raeburn  4436:                 }
1.1062    raeburn  4437:             }
                   4438:         }
                   4439:     }
                   4440:     foreach my $blocker (@blockers) {
                   4441:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4442:             &parse_block_record($commblocks{$blocker});
                   4443:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4444:         my ($start,$end,$triggertype);
                   4445:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4446:             ($start,$end) = ($1,$2);
                   4447:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4448:             $start = $triggered{$blocker}{'start'};
                   4449:             $end = $triggered{$blocker}{'end'};
                   4450:             $triggertype = $triggered{$blocker}{'type'};
                   4451:         }
                   4452:         if ($start) {
                   4453:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4454:             if ($triggertype) {
                   4455:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4456:             } else {
                   4457:                 push(@{$$setters{$course}{'triggers'}},0);
                   4458:             }
                   4459:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4460:                 $startblock = $start;
                   4461:                 if ($triggertype) {
                   4462:                     $triggerblock = $blocker;
1.474     raeburn  4463:                 }
                   4464:             }
1.1062    raeburn  4465:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4466:                $endblock = $end;
                   4467:                if ($triggertype) {
                   4468:                    $triggerblock = $blocker;
                   4469:                }
                   4470:             }
1.474     raeburn  4471:         }
                   4472:     }
1.1062    raeburn  4473:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4474: }
                   4475: 
                   4476: sub parse_block_record {
                   4477:     my ($record) = @_;
                   4478:     my ($setuname,$setudom,$title,$blocks);
                   4479:     if (ref($record) eq 'HASH') {
                   4480:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4481:         $title = &unescape($record->{'event'});
                   4482:         $blocks = $record->{'blocks'};
                   4483:     } else {
                   4484:         my @data = split(/:/,$record,3);
                   4485:         if (scalar(@data) eq 2) {
                   4486:             $title = $data[1];
                   4487:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4488:         } else {
                   4489:             ($setuname,$setudom,$title) = @data;
                   4490:         }
                   4491:         $blocks = { 'com' => 'on' };
                   4492:     }
                   4493:     return ($setuname,$setudom,$title,$blocks);
                   4494: }
                   4495: 
1.854     kalberla 4496: sub blocking_status {
1.1062    raeburn  4497:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4498:     my %setters;
1.890     droeschl 4499: 
1.1061    raeburn  4500: # check for active blocking
1.1062    raeburn  4501:     my ($startblock,$endblock,$triggerblock) = 
                   4502:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4503:     my $blocked = 0;
                   4504:     if ($startblock && $endblock) {
                   4505:         $blocked = 1;
                   4506:     }
1.890     droeschl 4507: 
1.1061    raeburn  4508: # caller just wants to know whether a block is active
                   4509:     if (!wantarray) { return $blocked; }
                   4510: 
                   4511: # build a link to a popup window containing the details
                   4512:     my $querystring  = "?activity=$activity";
                   4513: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4514:     if ($activity eq 'port') {
                   4515:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4516:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4517:     } elsif ($activity eq 'docs') {
                   4518:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4519:     }
1.1061    raeburn  4520: 
                   4521:     my $output .= <<'END_MYBLOCK';
                   4522: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4523:     var options = "width=" + w + ",height=" + h + ",";
                   4524:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4525:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4526:     var newWin = window.open(url, wdwName, options);
                   4527:     newWin.focus();
                   4528: }
1.890     droeschl 4529: END_MYBLOCK
1.854     kalberla 4530: 
1.1061    raeburn  4531:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4532:   
1.1061    raeburn  4533:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4534:     my $text = &mt('Communication Blocked');
                   4535:     if ($activity eq 'docs') {
                   4536:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4537:     } elsif ($activity eq 'printout') {
                   4538:         $text = &mt('Printing Blocked');
1.1062    raeburn  4539:     }
1.1061    raeburn  4540:     $output .= <<"END_BLOCK";
1.867     kalberla 4541: <div class='LC_comblock'>
1.869     kalberla 4542:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4543:   title='$text'>
                   4544:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4545:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4546:   title='$text'>$text</a>
1.867     kalberla 4547: </div>
                   4548: 
                   4549: END_BLOCK
1.474     raeburn  4550: 
1.1061    raeburn  4551:     return ($blocked, $output);
1.854     kalberla 4552: }
1.490     raeburn  4553: 
1.60      matthew  4554: ###############################################
                   4555: 
1.682     raeburn  4556: sub check_ip_acc {
                   4557:     my ($acc)=@_;
                   4558:     &Apache::lonxml::debug("acc is $acc");
                   4559:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4560:         return 1;
                   4561:     }
                   4562:     my $allowed=0;
                   4563:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4564: 
                   4565:     my $name;
                   4566:     foreach my $pattern (split(',',$acc)) {
                   4567:         $pattern =~ s/^\s*//;
                   4568:         $pattern =~ s/\s*$//;
                   4569:         if ($pattern =~ /\*$/) {
                   4570:             #35.8.*
                   4571:             $pattern=~s/\*//;
                   4572:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4573:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4574:             #35.8.3.[34-56]
                   4575:             my $low=$2;
                   4576:             my $high=$3;
                   4577:             $pattern=$1;
                   4578:             if ($ip =~ /^\Q$pattern\E/) {
                   4579:                 my $last=(split(/\./,$ip))[3];
                   4580:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4581:             }
                   4582:         } elsif ($pattern =~ /^\*/) {
                   4583:             #*.msu.edu
                   4584:             $pattern=~s/\*//;
                   4585:             if (!defined($name)) {
                   4586:                 use Socket;
                   4587:                 my $netaddr=inet_aton($ip);
                   4588:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4589:             }
                   4590:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4591:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4592:             #127.0.0.1
                   4593:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4594:         } else {
                   4595:             #some.name.com
                   4596:             if (!defined($name)) {
                   4597:                 use Socket;
                   4598:                 my $netaddr=inet_aton($ip);
                   4599:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4600:             }
                   4601:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4602:         }
                   4603:         if ($allowed) { last; }
                   4604:     }
                   4605:     return $allowed;
                   4606: }
                   4607: 
                   4608: ###############################################
                   4609: 
1.60      matthew  4610: =pod
                   4611: 
1.112     bowersj2 4612: =head1 Domain Template Functions
                   4613: 
                   4614: =over 4
                   4615: 
                   4616: =item * &determinedomain()
1.60      matthew  4617: 
                   4618: Inputs: $domain (usually will be undef)
                   4619: 
1.63      www      4620: Returns: Determines which domain should be used for designs
1.60      matthew  4621: 
                   4622: =cut
1.54      www      4623: 
1.60      matthew  4624: ###############################################
1.63      www      4625: sub determinedomain {
                   4626:     my $domain=shift;
1.531     albertel 4627:     if (! $domain) {
1.60      matthew  4628:         # Determine domain if we have not been given one
1.893     raeburn  4629:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4630:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4631:         if ($env{'request.role.domain'}) { 
                   4632:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4633:         }
                   4634:     }
1.63      www      4635:     return $domain;
                   4636: }
                   4637: ###############################################
1.517     raeburn  4638: 
1.518     albertel 4639: sub devalidate_domconfig_cache {
                   4640:     my ($udom)=@_;
                   4641:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4642: }
                   4643: 
                   4644: # ---------------------- Get domain configuration for a domain
                   4645: sub get_domainconf {
                   4646:     my ($udom) = @_;
                   4647:     my $cachetime=1800;
                   4648:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4649:     if (defined($cached)) { return %{$result}; }
                   4650: 
                   4651:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4652: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4653:     my (%designhash,%legacy);
1.518     albertel 4654:     if (keys(%domconfig) > 0) {
                   4655:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4656:             if (keys(%{$domconfig{'login'}})) {
                   4657:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4658:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4659:                         if ($key eq 'loginvia') {
                   4660:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4661:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4662:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4663:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4664:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4665:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4666:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4667: 
                   4668:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4669:                                             } else {
1.1013    raeburn  4670:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4671:                                             }
                   4672:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4673:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4674:                                             }
1.946     raeburn  4675:                                         }
                   4676:                                     }
                   4677:                                 }
                   4678:                             }
                   4679:                         } else {
                   4680:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4681:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4682:                                     $domconfig{'login'}{$key}{$img};
                   4683:                             }
1.699     raeburn  4684:                         }
                   4685:                     } else {
                   4686:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4687:                     }
1.632     raeburn  4688:                 }
                   4689:             } else {
                   4690:                 $legacy{'login'} = 1;
1.518     albertel 4691:             }
1.632     raeburn  4692:         } else {
                   4693:             $legacy{'login'} = 1;
1.518     albertel 4694:         }
                   4695:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4696:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4697:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4698:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4699:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4700:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4701:                         }
1.518     albertel 4702:                     }
                   4703:                 }
1.632     raeburn  4704:             } else {
                   4705:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4706:             }
1.632     raeburn  4707:         } else {
                   4708:             $legacy{'rolecolors'} = 1;
1.518     albertel 4709:         }
1.948     raeburn  4710:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4711:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4712:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4713:             }
                   4714:         }
1.632     raeburn  4715:         if (keys(%legacy) > 0) {
                   4716:             my %legacyhash = &get_legacy_domconf($udom);
                   4717:             foreach my $item (keys(%legacyhash)) {
                   4718:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4719:                     if ($legacy{'login'}) { 
                   4720:                         $designhash{$item} = $legacyhash{$item};
                   4721:                     }
                   4722:                 } else {
                   4723:                     if ($legacy{'rolecolors'}) {
                   4724:                         $designhash{$item} = $legacyhash{$item};
                   4725:                     }
1.518     albertel 4726:                 }
                   4727:             }
                   4728:         }
1.632     raeburn  4729:     } else {
                   4730:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4731:     }
                   4732:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4733: 				  $cachetime);
                   4734:     return %designhash;
                   4735: }
                   4736: 
1.632     raeburn  4737: sub get_legacy_domconf {
                   4738:     my ($udom) = @_;
                   4739:     my %legacyhash;
                   4740:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4741:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4742:     if (-e $designfile) {
                   4743:         if ( open (my $fh,"<$designfile") ) {
                   4744:             while (my $line = <$fh>) {
                   4745:                 next if ($line =~ /^\#/);
                   4746:                 chomp($line);
                   4747:                 my ($key,$val)=(split(/\=/,$line));
                   4748:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4749:             }
                   4750:             close($fh);
                   4751:         }
                   4752:     }
1.1026    raeburn  4753:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4754:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4755:     }
                   4756:     return %legacyhash;
                   4757: }
                   4758: 
1.63      www      4759: =pod
                   4760: 
1.112     bowersj2 4761: =item * &domainlogo()
1.63      www      4762: 
                   4763: Inputs: $domain (usually will be undef)
                   4764: 
                   4765: Returns: A link to a domain logo, if the domain logo exists.
                   4766: If the domain logo does not exist, a description of the domain.
                   4767: 
                   4768: =cut
1.112     bowersj2 4769: 
1.63      www      4770: ###############################################
                   4771: sub domainlogo {
1.517     raeburn  4772:     my $domain = &determinedomain(shift);
1.518     albertel 4773:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4774:     # See if there is a logo
                   4775:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4776:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4777:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4778: 	    if ($imgsrc =~ m{^/res/}) {
                   4779: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4780: 		&Apache::lonnet::repcopy($local_name);
                   4781: 	    }
                   4782: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4783:         } 
                   4784:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4785:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4786:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4787:     } else {
1.60      matthew  4788:         return '';
1.59      www      4789:     }
                   4790: }
1.63      www      4791: ##############################################
                   4792: 
                   4793: =pod
                   4794: 
1.112     bowersj2 4795: =item * &designparm()
1.63      www      4796: 
                   4797: Inputs: $which parameter; $domain (usually will be undef)
                   4798: 
                   4799: Returns: value of designparamter $which
                   4800: 
                   4801: =cut
1.112     bowersj2 4802: 
1.397     albertel 4803: 
1.400     albertel 4804: ##############################################
1.397     albertel 4805: sub designparm {
                   4806:     my ($which,$domain)=@_;
                   4807:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4808:         return $env{'environment.color.'.$which};
1.96      www      4809:     }
1.63      www      4810:     $domain=&determinedomain($domain);
1.1016    raeburn  4811:     my %domdesign;
                   4812:     unless ($domain eq 'public') {
                   4813:         %domdesign = &get_domainconf($domain);
                   4814:     }
1.520     raeburn  4815:     my $output;
1.517     raeburn  4816:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4817:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4818:     } else {
1.520     raeburn  4819:         $output = $defaultdesign{$which};
                   4820:     }
                   4821:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4822:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4823:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4824:             if ($output =~ m{^/res/}) {
                   4825:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4826:                 &Apache::lonnet::repcopy($local_name);
                   4827:             }
1.520     raeburn  4828:             $output = &lonhttpdurl($output);
                   4829:         }
1.63      www      4830:     }
1.520     raeburn  4831:     return $output;
1.63      www      4832: }
1.59      www      4833: 
1.822     bisitz   4834: ##############################################
                   4835: =pod
                   4836: 
1.832     bisitz   4837: =item * &authorspace()
                   4838: 
1.1028    raeburn  4839: Inputs: $url (usually will be undef).
1.832     bisitz   4840: 
1.1028    raeburn  4841: Returns: Path to Construction Space containing the resource or 
                   4842:          directory being viewed (or for which action is being taken). 
                   4843:          If $url is provided, and begins /priv/<domain>/<uname>
                   4844:          the path will be that portion of the $context argument.
                   4845:          Otherwise the path will be for the author space of the current
                   4846:          user when the current role is author, or for that of the 
                   4847:          co-author/assistant co-author space when the current role 
                   4848:          is co-author or assistant co-author.
1.832     bisitz   4849: 
                   4850: =cut
                   4851: 
                   4852: sub authorspace {
1.1028    raeburn  4853:     my ($url) = @_;
                   4854:     if ($url ne '') {
                   4855:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4856:            return $1;
                   4857:         }
                   4858:     }
1.832     bisitz   4859:     my $caname = '';
1.1024    www      4860:     my $cadom = '';
1.1028    raeburn  4861:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4862:         ($cadom,$caname) =
1.832     bisitz   4863:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4864:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4865:         $caname = $env{'user.name'};
1.1024    www      4866:         $cadom = $env{'user.domain'};
1.832     bisitz   4867:     }
1.1028    raeburn  4868:     if (($caname ne '') && ($cadom ne '')) {
                   4869:         return "/priv/$cadom/$caname/";
                   4870:     }
                   4871:     return;
1.832     bisitz   4872: }
                   4873: 
                   4874: ##############################################
                   4875: =pod
                   4876: 
1.822     bisitz   4877: =item * &head_subbox()
                   4878: 
                   4879: Inputs: $content (contains HTML code with page functions, etc.)
                   4880: 
                   4881: Returns: HTML div with $content
                   4882:          To be included in page header
                   4883: 
                   4884: =cut
                   4885: 
                   4886: sub head_subbox {
                   4887:     my ($content)=@_;
                   4888:     my $output =
1.993     raeburn  4889:         '<div class="LC_head_subbox">'
1.822     bisitz   4890:        .$content
                   4891:        .'</div>'
                   4892: }
                   4893: 
                   4894: ##############################################
                   4895: =pod
                   4896: 
                   4897: =item * &CSTR_pageheader()
                   4898: 
1.1026    raeburn  4899: Input: (optional) filename from which breadcrumb trail is built.
                   4900:        In most cases no input as needed, as $env{'request.filename'}
                   4901:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4902: 
                   4903: Returns: HTML div with CSTR path and recent box
                   4904:          To be included on Construction Space pages
                   4905: 
                   4906: =cut
                   4907: 
                   4908: sub CSTR_pageheader {
1.1026    raeburn  4909:     my ($trailfile) = @_;
                   4910:     if ($trailfile eq '') {
                   4911:         $trailfile = $env{'request.filename'};
                   4912:     }
                   4913: 
                   4914: # this is for resources; directories have customtitle, and crumbs
                   4915: # and select recent are created in lonpubdir.pm
                   4916: 
                   4917:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      4918:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  4919:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  4920:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   4921:     $formaction =~ s{/+}{/}g;
1.822     bisitz   4922: 
                   4923:     my $parentpath = '';
                   4924:     my $lastitem = '';
                   4925:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4926:         $parentpath = $1;
                   4927:         $lastitem = $2;
                   4928:     } else {
                   4929:         $lastitem = $thisdisfn;
                   4930:     }
1.921     bisitz   4931: 
                   4932:     my $output =
1.822     bisitz   4933:          '<div>'
                   4934:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
                   4935:         .'<b>'.&mt('Construction Space:').'</b> '
                   4936:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   4937:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      4938:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   4939: 
                   4940:     if ($lastitem) {
                   4941:         $output .=
                   4942:              '<span class="LC_filename">'
                   4943:             .$lastitem
                   4944:             .'</span>';
                   4945:     }
                   4946:     $output .=
                   4947:          '<br />'
1.822     bisitz   4948:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   4949:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4950:         .'</form>'
                   4951:         .&Apache::lonmenu::constspaceform()
                   4952:         .'</div>';
1.921     bisitz   4953: 
                   4954:     return $output;
1.822     bisitz   4955: }
                   4956: 
1.60      matthew  4957: ###############################################
                   4958: ###############################################
                   4959: 
                   4960: =pod
                   4961: 
1.112     bowersj2 4962: =back
                   4963: 
1.549     albertel 4964: =head1 HTML Helpers
1.112     bowersj2 4965: 
                   4966: =over 4
                   4967: 
                   4968: =item * &bodytag()
1.60      matthew  4969: 
                   4970: Returns a uniform header for LON-CAPA web pages.
                   4971: 
                   4972: Inputs: 
                   4973: 
1.112     bowersj2 4974: =over 4
                   4975: 
                   4976: =item * $title, A title to be displayed on the page.
                   4977: 
                   4978: =item * $function, the current role (can be undef).
                   4979: 
                   4980: =item * $addentries, extra parameters for the <body> tag.
                   4981: 
                   4982: =item * $bodyonly, if defined, only return the <body> tag.
                   4983: 
                   4984: =item * $domain, if defined, force a given domain.
                   4985: 
                   4986: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      4987:             text interface only)
1.60      matthew  4988: 
1.814     bisitz   4989: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   4990:                      navigational links
1.317     albertel 4991: 
1.338     albertel 4992: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   4993: 
1.1075.2.12  raeburn  4994: =item * $no_inline_link, if true and in remote mode, don't show the
                   4995:          'Switch To Inline Menu' link
                   4996: 
1.460     albertel 4997: =item * $args, optional argument valid values are
                   4998:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 4999:             inherit_jsmath -> when creating popup window in a page,
                   5000:                               should it have jsmath forced on by the
                   5001:                               current page
1.460     albertel 5002: 
1.1075.2.15  raeburn  5003: =item * $advtoolsref, optional argument, ref to an array containing
                   5004:             inlineremote items to be added in "Functions" menu below
                   5005:             breadcrumbs.
                   5006: 
1.112     bowersj2 5007: =back
                   5008: 
1.60      matthew  5009: Returns: A uniform header for LON-CAPA web pages.  
                   5010: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5011: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5012: other decorations will be returned.
                   5013: 
                   5014: =cut
                   5015: 
1.54      www      5016: sub bodytag {
1.831     bisitz   5017:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5018:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5019: 
1.954     raeburn  5020:     my $public;
                   5021:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5022:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5023:         $public = 1;
                   5024:     }
1.460     albertel 5025:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 5026: 
1.183     matthew  5027:     $function = &get_users_function() if (!$function);
1.339     albertel 5028:     my $img =    &designparm($function.'.img',$domain);
                   5029:     my $font =   &designparm($function.'.font',$domain);
                   5030:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5031: 
1.803     bisitz   5032:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5033: 		   'bgcolor' => $pgbg,
1.339     albertel 5034: 		   'text'    => $font,
                   5035:                    'alink'   => &designparm($function.'.alink',$domain),
                   5036: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5037: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5038:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5039: 
1.63      www      5040:  # role and realm
1.378     raeburn  5041:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5042:     if ($role  eq 'ca') {
1.479     albertel 5043:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5044:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5045:     } 
1.55      www      5046: # realm
1.258     albertel 5047:     if ($env{'request.course.id'}) {
1.378     raeburn  5048:         if ($env{'request.role'} !~ /^cr/) {
                   5049:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5050:         }
1.898     raeburn  5051:         if ($env{'request.course.sec'}) {
                   5052:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5053:         }   
1.359     albertel 5054: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5055:     } else {
                   5056:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5057:     }
1.433     albertel 5058: 
1.359     albertel 5059:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5060: 
1.438     albertel 5061:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5062: 
1.101     www      5063: # construct main body tag
1.359     albertel 5064:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5065: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5066: 
1.1075.2.38! raeburn  5067:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
        !          5068: 
        !          5069:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5070:         return $bodytag;
1.1075.2.38! raeburn  5071:     }
1.359     albertel 5072: 
1.954     raeburn  5073:     if ($public) {
1.433     albertel 5074: 	undef($role);
                   5075:     }
1.359     albertel 5076:     
1.762     bisitz   5077:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5078:     #
                   5079:     # Extra info if you are the DC
                   5080:     my $dc_info = '';
                   5081:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5082:                         $env{'course.'.$env{'request.course.id'}.
                   5083:                                  '.domain'}.'/'})) {
                   5084:         my $cid = $env{'request.course.id'};
1.917     raeburn  5085:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5086:         $dc_info =~ s/\s+$//;
1.359     albertel 5087:     }
                   5088: 
1.898     raeburn  5089:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.903     droeschl 5090: 
1.1075.2.13  raeburn  5091:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5092: 
1.1075.2.38! raeburn  5093: 
        !          5094: 
1.1075.2.21  raeburn  5095:     my $funclist;
                   5096:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
                   5097:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions(), 'start')."\n".
                   5098:                     Apache::lonmenu::serverform();
                   5099:         my $forbodytag;
                   5100:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5101:                                             $forcereg,$args->{'group'},
                   5102:                                             $args->{'bread_crumbs'},
                   5103:                                             $advtoolsref,'',\$forbodytag);
                   5104:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5105:             $funclist = $forbodytag;
                   5106:         }
                   5107:     } else {
1.903     droeschl 5108: 
                   5109:         #    if ($env{'request.state'} eq 'construct') {
                   5110:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5111:         #    }
                   5112: 
1.1075.2.38! raeburn  5113:         $bodytag .= Apache::lonhtmlcommon::scripttag(
        !          5114:             Apache::lonmenu::utilityfunctions(), 'start');
1.359     albertel 5115: 
1.1075.2.38! raeburn  5116:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5117: 
1.916     droeschl 5118:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5119:             if ($dc_info) {
                   5120:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5121:             }
1.1075.2.38! raeburn  5122:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5123:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5124:             return $bodytag;
                   5125:         }
1.894     droeschl 5126: 
1.927     raeburn  5127:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38! raeburn  5128:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5129:         }
1.916     droeschl 5130: 
1.1075.2.38! raeburn  5131:         $bodytag .= $right;
1.852     droeschl 5132: 
1.917     raeburn  5133:         if ($dc_info) {
                   5134:             $dc_info = &dc_courseid_toggle($dc_info);
                   5135:         }
                   5136:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5137: 
1.903     droeschl 5138:         #don't show menus for public users
1.954     raeburn  5139:         if (!$public){
1.903     droeschl 5140:             $bodytag .= Apache::lonmenu::secondary_menu();
                   5141:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5142:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5143:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5144:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5145:                                 $args->{'bread_crumbs'});
                   5146:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5147:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5148:                                                             $args->{'group'});
1.1075.2.15  raeburn  5149:             } else {
1.1075.2.21  raeburn  5150:                 my $forbodytag;
                   5151:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5152:                                                     $forcereg,$args->{'group'},
                   5153:                                                     $args->{'bread_crumbs'},
                   5154:                                                     $advtoolsref,'',\$forbodytag);
                   5155:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5156:                     $bodytag .= $forbodytag;
                   5157:                 }
1.920     raeburn  5158:             }
1.903     droeschl 5159:         }else{
                   5160:             # this is to seperate menu from content when there's no secondary
                   5161:             # menu. Especially needed for public accessible ressources.
                   5162:             $bodytag .= '<hr style="clear:both" />';
                   5163:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5164:         }
1.903     droeschl 5165: 
1.235     raeburn  5166:         return $bodytag;
1.1075.2.12  raeburn  5167:     }
                   5168: 
                   5169: #
                   5170: # Top frame rendering, Remote is up
                   5171: #
                   5172: 
                   5173:     my $imgsrc = $img;
                   5174:     if ($img =~ /^\/adm/) {
                   5175:         $imgsrc = &lonhttpdurl($img);
                   5176:     }
                   5177:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5178: 
                   5179:     # Explicit link to get inline menu
                   5180:     my $menu= ($no_inline_link?''
                   5181:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5182: 
                   5183:     if ($dc_info) {
                   5184:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5185:     }
                   5186: 
1.1075.2.38! raeburn  5187:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
        !          5188:     unless ($public) {
        !          5189:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
        !          5190:                                 undef,'LC_menubuttons_link');
        !          5191:     }
        !          5192: 
1.1075.2.12  raeburn  5193:     unless ($env{'form.inhibitmenu'}) {
                   5194:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38! raeburn  5195:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.12  raeburn  5196:                        <li>$menu</li>
                   5197:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5198:     }
1.1075.2.13  raeburn  5199:     if ($env{'request.state'} eq 'construct') {
                   5200:         if (!$public){
                   5201:             if ($env{'request.state'} eq 'construct') {
                   5202:                 $funclist = &Apache::lonhtmlcommon::scripttag(
                   5203:                                 &Apache::lonmenu::utilityfunctions(), 'start').
                   5204:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5205:                             &Apache::lonmenu::innerregister($forcereg,
                   5206:                                                             $args->{'bread_crumbs'});
                   5207:             }
                   5208:         }
                   5209:     }
1.1075.2.21  raeburn  5210:     return $bodytag."\n".$funclist;
1.182     matthew  5211: }
                   5212: 
1.917     raeburn  5213: sub dc_courseid_toggle {
                   5214:     my ($dc_info) = @_;
1.980     raeburn  5215:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5216:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5217:            &mt('(More ...)').'</a></span>'.
                   5218:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5219: }
                   5220: 
1.330     albertel 5221: sub make_attr_string {
                   5222:     my ($register,$attr_ref) = @_;
                   5223: 
                   5224:     if ($attr_ref && !ref($attr_ref)) {
                   5225: 	die("addentries Must be a hash ref ".
                   5226: 	    join(':',caller(1))." ".
                   5227: 	    join(':',caller(0))." ");
                   5228:     }
                   5229: 
                   5230:     if ($register) {
1.339     albertel 5231: 	my ($on_load,$on_unload);
                   5232: 	foreach my $key (keys(%{$attr_ref})) {
                   5233: 	    if      (lc($key) eq 'onload') {
                   5234: 		$on_load.=$attr_ref->{$key}.';';
                   5235: 		delete($attr_ref->{$key});
                   5236: 
                   5237: 	    } elsif (lc($key) eq 'onunload') {
                   5238: 		$on_unload.=$attr_ref->{$key}.';';
                   5239: 		delete($attr_ref->{$key});
                   5240: 	    }
                   5241: 	}
1.1075.2.12  raeburn  5242:         if ($env{'environment.remote'} eq 'on') {
                   5243:             $attr_ref->{'onload'}  =
                   5244:                 &Apache::lonmenu::loadevents().  $on_load;
                   5245:             $attr_ref->{'onunload'}=
                   5246:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5247:         } else {  
                   5248: 	    $attr_ref->{'onload'}  = $on_load;
                   5249: 	    $attr_ref->{'onunload'}= $on_unload;
                   5250:         }
1.330     albertel 5251:     }
1.339     albertel 5252: 
1.330     albertel 5253:     my $attr_string;
                   5254:     foreach my $attr (keys(%$attr_ref)) {
                   5255: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5256:     }
                   5257:     return $attr_string;
                   5258: }
                   5259: 
                   5260: 
1.182     matthew  5261: ###############################################
1.251     albertel 5262: ###############################################
                   5263: 
                   5264: =pod
                   5265: 
                   5266: =item * &endbodytag()
                   5267: 
                   5268: Returns a uniform footer for LON-CAPA web pages.
                   5269: 
1.635     raeburn  5270: Inputs: 1 - optional reference to an args hash
                   5271: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5272: a 'Continue' link is not displayed if the page contains an
                   5273: internal redirect in the <head></head> section,
                   5274: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5275: 
                   5276: =cut
                   5277: 
                   5278: sub endbodytag {
1.635     raeburn  5279:     my ($args) = @_;
1.1075.2.6  raeburn  5280:     my $endbodytag;
                   5281:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5282:         $endbodytag='</body>';
                   5283:     }
1.269     albertel 5284:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5285:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5286:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5287: 	    $endbodytag=
                   5288: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5289: 	        &mt('Continue').'</a>'.
                   5290: 	        $endbodytag;
                   5291:         }
1.315     albertel 5292:     }
1.251     albertel 5293:     return $endbodytag;
                   5294: }
                   5295: 
1.352     albertel 5296: =pod
                   5297: 
                   5298: =item * &standard_css()
                   5299: 
                   5300: Returns a style sheet
                   5301: 
                   5302: Inputs: (all optional)
                   5303:             domain         -> force to color decorate a page for a specific
                   5304:                                domain
                   5305:             function       -> force usage of a specific rolish color scheme
                   5306:             bgcolor        -> override the default page bgcolor
                   5307: 
                   5308: =cut
                   5309: 
1.343     albertel 5310: sub standard_css {
1.345     albertel 5311:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5312:     $function  = &get_users_function() if (!$function);
                   5313:     my $img    = &designparm($function.'.img',   $domain);
                   5314:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5315:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5316:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5317: #second colour for later usage
1.345     albertel 5318:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5319:     my $pgbg_or_bgcolor =
                   5320: 	         $bgcolor ||
1.352     albertel 5321: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5322:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5323:     my $alink  = &designparm($function.'.alink', $domain);
                   5324:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5325:     my $link   = &designparm($function.'.link',  $domain);
                   5326: 
1.602     albertel 5327:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5328:     my $mono                 = 'monospace';
1.850     bisitz   5329:     my $data_table_head      = $sidebg;
                   5330:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5331:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5332:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5333:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5334:     my $mail_new             = '#FFBB77';
                   5335:     my $mail_new_hover       = '#DD9955';
                   5336:     my $mail_read            = '#BBBB77';
                   5337:     my $mail_read_hover      = '#999944';
                   5338:     my $mail_replied         = '#AAAA88';
                   5339:     my $mail_replied_hover   = '#888855';
                   5340:     my $mail_other           = '#99BBBB';
                   5341:     my $mail_other_hover     = '#669999';
1.391     albertel 5342:     my $table_header         = '#DDDDDD';
1.489     raeburn  5343:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5344:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5345:     my $button_hover         = '#BF2317';
1.392     albertel 5346: 
1.608     albertel 5347:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5348:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5349:                                              : '0 3px 0 4px';
1.448     albertel 5350: 
1.523     albertel 5351: 
1.343     albertel 5352:     return <<END;
1.947     droeschl 5353: 
                   5354: /* needed for iframe to allow 100% height in FF */
                   5355: body, html { 
                   5356:     margin: 0;
                   5357:     padding: 0 0.5%;
                   5358:     height: 99%; /* to avoid scrollbars */
                   5359: }
                   5360: 
1.795     www      5361: body {
1.911     bisitz   5362:   font-family: $sans;
                   5363:   line-height:130%;
                   5364:   font-size:0.83em;
                   5365:   color:$font;
1.795     www      5366: }
                   5367: 
1.959     onken    5368: a:focus,
                   5369: a:focus img {
1.795     www      5370:   color: red;
                   5371: }
1.698     harmsja  5372: 
1.911     bisitz   5373: form, .inline {
                   5374:   display: inline;
1.795     www      5375: }
1.721     harmsja  5376: 
1.795     www      5377: .LC_right {
1.911     bisitz   5378:   text-align:right;
1.795     www      5379: }
                   5380: 
                   5381: .LC_middle {
1.911     bisitz   5382:   vertical-align:middle;
1.795     www      5383: }
1.721     harmsja  5384: 
1.1075.2.38! raeburn  5385: .LC_floatleft {
        !          5386:   float: left;
        !          5387: }
        !          5388: 
        !          5389: .LC_floatright {
        !          5390:   float: right;
        !          5391: }
        !          5392: 
1.911     bisitz   5393: .LC_400Box {
                   5394:   width:400px;
                   5395: }
1.721     harmsja  5396: 
1.947     droeschl 5397: .LC_iframecontainer {
                   5398:     width: 98%;
                   5399:     margin: 0;
                   5400:     position: fixed;
                   5401:     top: 8.5em;
                   5402:     bottom: 0;
                   5403: }
                   5404: 
                   5405: .LC_iframecontainer iframe{
                   5406:     border: none;
                   5407:     width: 100%;
                   5408:     height: 100%;
                   5409: }
                   5410: 
1.778     bisitz   5411: .LC_filename {
                   5412:   font-family: $mono;
                   5413:   white-space:pre;
1.921     bisitz   5414:   font-size: 120%;
1.778     bisitz   5415: }
                   5416: 
                   5417: .LC_fileicon {
                   5418:   border: none;
                   5419:   height: 1.3em;
                   5420:   vertical-align: text-bottom;
                   5421:   margin-right: 0.3em;
                   5422:   text-decoration:none;
                   5423: }
                   5424: 
1.1008    www      5425: .LC_setting {
                   5426:   text-decoration:underline;
                   5427: }
                   5428: 
1.350     albertel 5429: .LC_error {
                   5430:   color: red;
                   5431: }
1.795     www      5432: 
1.1075.2.15  raeburn  5433: .LC_warning {
                   5434:   color: darkorange;
                   5435: }
                   5436: 
1.457     albertel 5437: .LC_diff_removed {
1.733     bisitz   5438:   color: red;
1.394     albertel 5439: }
1.532     albertel 5440: 
                   5441: .LC_info,
1.457     albertel 5442: .LC_success,
                   5443: .LC_diff_added {
1.350     albertel 5444:   color: green;
                   5445: }
1.795     www      5446: 
1.802     bisitz   5447: div.LC_confirm_box {
                   5448:   background-color: #FAFAFA;
                   5449:   border: 1px solid $lg_border_color;
                   5450:   margin-right: 0;
                   5451:   padding: 5px;
                   5452: }
                   5453: 
                   5454: div.LC_confirm_box .LC_error img,
                   5455: div.LC_confirm_box .LC_success img {
                   5456:   vertical-align: middle;
                   5457: }
                   5458: 
1.440     albertel 5459: .LC_icon {
1.771     droeschl 5460:   border: none;
1.790     droeschl 5461:   vertical-align: middle;
1.771     droeschl 5462: }
                   5463: 
1.543     albertel 5464: .LC_docs_spacer {
                   5465:   width: 25px;
                   5466:   height: 1px;
1.771     droeschl 5467:   border: none;
1.543     albertel 5468: }
1.346     albertel 5469: 
1.532     albertel 5470: .LC_internal_info {
1.735     bisitz   5471:   color: #999999;
1.532     albertel 5472: }
                   5473: 
1.794     www      5474: .LC_discussion {
1.1050    www      5475:   background: $data_table_dark;
1.911     bisitz   5476:   border: 1px solid black;
                   5477:   margin: 2px;
1.794     www      5478: }
                   5479: 
                   5480: .LC_disc_action_left {
1.1050    www      5481:   background: $sidebg;
1.911     bisitz   5482:   text-align: left;
1.1050    www      5483:   padding: 4px;
                   5484:   margin: 2px;
1.794     www      5485: }
                   5486: 
                   5487: .LC_disc_action_right {
1.1050    www      5488:   background: $sidebg;
1.911     bisitz   5489:   text-align: right;
1.1050    www      5490:   padding: 4px;
                   5491:   margin: 2px;
1.794     www      5492: }
                   5493: 
                   5494: .LC_disc_new_item {
1.911     bisitz   5495:   background: white;
                   5496:   border: 2px solid red;
1.1050    www      5497:   margin: 4px;
                   5498:   padding: 4px;
1.794     www      5499: }
                   5500: 
                   5501: .LC_disc_old_item {
1.911     bisitz   5502:   background: white;
1.1050    www      5503:   margin: 4px;
                   5504:   padding: 4px;
1.794     www      5505: }
                   5506: 
1.458     albertel 5507: table.LC_pastsubmission {
                   5508:   border: 1px solid black;
                   5509:   margin: 2px;
                   5510: }
                   5511: 
1.924     bisitz   5512: table#LC_menubuttons {
1.345     albertel 5513:   width: 100%;
                   5514:   background: $pgbg;
1.392     albertel 5515:   border: 2px;
1.402     albertel 5516:   border-collapse: separate;
1.803     bisitz   5517:   padding: 0;
1.345     albertel 5518: }
1.392     albertel 5519: 
1.801     tempelho 5520: table#LC_title_bar a {
                   5521:   color: $fontmenu;
                   5522: }
1.836     bisitz   5523: 
1.807     droeschl 5524: table#LC_title_bar {
1.819     tempelho 5525:   clear: both;
1.836     bisitz   5526:   display: none;
1.807     droeschl 5527: }
                   5528: 
1.795     www      5529: table#LC_title_bar,
1.933     droeschl 5530: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5531: table#LC_title_bar.LC_with_remote {
1.359     albertel 5532:   width: 100%;
1.392     albertel 5533:   border-color: $pgbg;
                   5534:   border-style: solid;
                   5535:   border-width: $border;
1.379     albertel 5536:   background: $pgbg;
1.801     tempelho 5537:   color: $fontmenu;
1.392     albertel 5538:   border-collapse: collapse;
1.803     bisitz   5539:   padding: 0;
1.819     tempelho 5540:   margin: 0;
1.359     albertel 5541: }
1.795     www      5542: 
1.933     droeschl 5543: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5544:     margin: 0;
                   5545:     padding: 0;
1.933     droeschl 5546:     position: relative;
                   5547:     list-style: none;
1.913     droeschl 5548: }
1.933     droeschl 5549: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5550:     display: inline;
                   5551: }
1.933     droeschl 5552: 
                   5553: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5554:     padding: 0;
1.933     droeschl 5555:     margin: 0;
                   5556:     float: left;
1.913     droeschl 5557: }
1.933     droeschl 5558: .LC_breadcrumb_tools_tools {
                   5559:     padding: 0;
                   5560:     margin: 0;
1.913     droeschl 5561:     float: right;
                   5562: }
                   5563: 
1.359     albertel 5564: table#LC_title_bar td {
                   5565:   background: $tabbg;
                   5566: }
1.795     www      5567: 
1.911     bisitz   5568: table#LC_menubuttons img {
1.803     bisitz   5569:   border: none;
1.346     albertel 5570: }
1.795     www      5571: 
1.842     droeschl 5572: .LC_breadcrumbs_component {
1.911     bisitz   5573:   float: right;
                   5574:   margin: 0 1em;
1.357     albertel 5575: }
1.842     droeschl 5576: .LC_breadcrumbs_component img {
1.911     bisitz   5577:   vertical-align: middle;
1.777     tempelho 5578: }
1.795     www      5579: 
1.383     albertel 5580: td.LC_table_cell_checkbox {
                   5581:   text-align: center;
                   5582: }
1.795     www      5583: 
                   5584: .LC_fontsize_small {
1.911     bisitz   5585:   font-size: 70%;
1.705     tempelho 5586: }
                   5587: 
1.844     bisitz   5588: #LC_breadcrumbs {
1.911     bisitz   5589:   clear:both;
                   5590:   background: $sidebg;
                   5591:   border-bottom: 1px solid $lg_border_color;
                   5592:   line-height: 2.5em;
1.933     droeschl 5593:   overflow: hidden;
1.911     bisitz   5594:   margin: 0;
                   5595:   padding: 0;
1.995     raeburn  5596:   text-align: left;
1.819     tempelho 5597: }
1.862     bisitz   5598: 
1.1075.2.16  raeburn  5599: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5600:   clear:both;
                   5601:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5602:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5603:   margin: 0 0 10px 0;
1.966     bisitz   5604:   padding: 3px;
1.995     raeburn  5605:   text-align: left;
1.822     bisitz   5606: }
                   5607: 
1.795     www      5608: .LC_fontsize_medium {
1.911     bisitz   5609:   font-size: 85%;
1.705     tempelho 5610: }
                   5611: 
1.795     www      5612: .LC_fontsize_large {
1.911     bisitz   5613:   font-size: 120%;
1.705     tempelho 5614: }
                   5615: 
1.346     albertel 5616: .LC_menubuttons_inline_text {
                   5617:   color: $font;
1.698     harmsja  5618:   font-size: 90%;
1.701     harmsja  5619:   padding-left:3px;
1.346     albertel 5620: }
                   5621: 
1.934     droeschl 5622: .LC_menubuttons_inline_text img{
                   5623:   vertical-align: middle;
                   5624: }
                   5625: 
1.1051    www      5626: li.LC_menubuttons_inline_text img {
1.951     onken    5627:   cursor:pointer;
1.1002    droeschl 5628:   text-decoration: none;
1.951     onken    5629: }
                   5630: 
1.526     www      5631: .LC_menubuttons_link {
                   5632:   text-decoration: none;
                   5633: }
1.795     www      5634: 
1.522     albertel 5635: .LC_menubuttons_category {
1.521     www      5636:   color: $font;
1.526     www      5637:   background: $pgbg;
1.521     www      5638:   font-size: larger;
                   5639:   font-weight: bold;
                   5640: }
                   5641: 
1.346     albertel 5642: td.LC_menubuttons_text {
1.911     bisitz   5643:   color: $font;
1.346     albertel 5644: }
1.706     harmsja  5645: 
1.346     albertel 5646: .LC_current_location {
                   5647:   background: $tabbg;
                   5648: }
1.795     www      5649: 
1.938     bisitz   5650: table.LC_data_table {
1.347     albertel 5651:   border: 1px solid #000000;
1.402     albertel 5652:   border-collapse: separate;
1.426     albertel 5653:   border-spacing: 1px;
1.610     albertel 5654:   background: $pgbg;
1.347     albertel 5655: }
1.795     www      5656: 
1.422     albertel 5657: .LC_data_table_dense {
                   5658:   font-size: small;
                   5659: }
1.795     www      5660: 
1.507     raeburn  5661: table.LC_nested_outer {
                   5662:   border: 1px solid #000000;
1.589     raeburn  5663:   border-collapse: collapse;
1.803     bisitz   5664:   border-spacing: 0;
1.507     raeburn  5665:   width: 100%;
                   5666: }
1.795     www      5667: 
1.879     raeburn  5668: table.LC_innerpickbox,
1.507     raeburn  5669: table.LC_nested {
1.803     bisitz   5670:   border: none;
1.589     raeburn  5671:   border-collapse: collapse;
1.803     bisitz   5672:   border-spacing: 0;
1.507     raeburn  5673:   width: 100%;
                   5674: }
1.795     www      5675: 
1.911     bisitz   5676: table.LC_data_table tr th,
                   5677: table.LC_calendar tr th,
1.879     raeburn  5678: table.LC_prior_tries tr th,
                   5679: table.LC_innerpickbox tr th {
1.349     albertel 5680:   font-weight: bold;
                   5681:   background-color: $data_table_head;
1.801     tempelho 5682:   color:$fontmenu;
1.701     harmsja  5683:   font-size:90%;
1.347     albertel 5684: }
1.795     www      5685: 
1.879     raeburn  5686: table.LC_innerpickbox tr th,
                   5687: table.LC_innerpickbox tr td {
                   5688:   vertical-align: top;
                   5689: }
                   5690: 
1.711     raeburn  5691: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5692:   background-color: #CCCCCC;
1.711     raeburn  5693:   font-weight: bold;
                   5694:   text-align: left;
                   5695: }
1.795     www      5696: 
1.912     bisitz   5697: table.LC_data_table tr.LC_odd_row > td {
                   5698:   background-color: $data_table_light;
                   5699:   padding: 2px;
                   5700:   vertical-align: top;
                   5701: }
                   5702: 
1.809     bisitz   5703: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5704:   background-color: $data_table_light;
1.912     bisitz   5705:   vertical-align: top;
                   5706: }
                   5707: 
                   5708: table.LC_data_table tr.LC_even_row > td {
                   5709:   background-color: $data_table_dark;
1.425     albertel 5710:   padding: 2px;
1.900     bisitz   5711:   vertical-align: top;
1.347     albertel 5712: }
1.795     www      5713: 
1.809     bisitz   5714: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5715:   background-color: $data_table_dark;
1.900     bisitz   5716:   vertical-align: top;
1.347     albertel 5717: }
1.795     www      5718: 
1.425     albertel 5719: table.LC_data_table tr.LC_data_table_highlight td {
                   5720:   background-color: $data_table_darker;
                   5721: }
1.795     www      5722: 
1.639     raeburn  5723: table.LC_data_table tr td.LC_leftcol_header {
                   5724:   background-color: $data_table_head;
                   5725:   font-weight: bold;
                   5726: }
1.795     www      5727: 
1.451     albertel 5728: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5729: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5730:   font-weight: bold;
                   5731:   font-style: italic;
                   5732:   text-align: center;
                   5733:   padding: 8px;
1.347     albertel 5734: }
1.795     www      5735: 
1.1075.2.30  raeburn  5736: table.LC_data_table tr.LC_empty_row td,
                   5737: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5738:   background-color: $sidebg;
                   5739: }
                   5740: 
                   5741: table.LC_nested tr.LC_empty_row td {
                   5742:   background-color: #FFFFFF;
                   5743: }
                   5744: 
1.890     droeschl 5745: table.LC_caption {
                   5746: }
                   5747: 
1.507     raeburn  5748: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5749:   padding: 4ex
                   5750: }
1.795     www      5751: 
1.507     raeburn  5752: table.LC_nested_outer tr th {
                   5753:   font-weight: bold;
1.801     tempelho 5754:   color:$fontmenu;
1.507     raeburn  5755:   background-color: $data_table_head;
1.701     harmsja  5756:   font-size: small;
1.507     raeburn  5757:   border-bottom: 1px solid #000000;
                   5758: }
1.795     www      5759: 
1.507     raeburn  5760: table.LC_nested_outer tr td.LC_subheader {
                   5761:   background-color: $data_table_head;
                   5762:   font-weight: bold;
                   5763:   font-size: small;
                   5764:   border-bottom: 1px solid #000000;
                   5765:   text-align: right;
1.451     albertel 5766: }
1.795     www      5767: 
1.507     raeburn  5768: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5769:   background-color: #CCCCCC;
1.451     albertel 5770:   font-weight: bold;
                   5771:   font-size: small;
1.507     raeburn  5772:   text-align: center;
                   5773: }
1.795     www      5774: 
1.589     raeburn  5775: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5776: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5777:   text-align: left;
1.451     albertel 5778: }
1.795     www      5779: 
1.507     raeburn  5780: table.LC_nested td {
1.735     bisitz   5781:   background-color: #FFFFFF;
1.451     albertel 5782:   font-size: small;
1.507     raeburn  5783: }
1.795     www      5784: 
1.507     raeburn  5785: table.LC_nested_outer tr th.LC_right_item,
                   5786: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5787: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5788: table.LC_nested tr td.LC_right_item {
1.451     albertel 5789:   text-align: right;
                   5790: }
                   5791: 
1.507     raeburn  5792: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5793:   background-color: #EEEEEE;
1.451     albertel 5794: }
                   5795: 
1.473     raeburn  5796: table.LC_createuser {
                   5797: }
                   5798: 
                   5799: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5800:   font-size: small;
1.473     raeburn  5801: }
                   5802: 
                   5803: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5804:   background-color: #CCCCCC;
1.473     raeburn  5805:   font-weight: bold;
                   5806:   text-align: center;
                   5807: }
                   5808: 
1.349     albertel 5809: table.LC_calendar {
                   5810:   border: 1px solid #000000;
                   5811:   border-collapse: collapse;
1.917     raeburn  5812:   width: 98%;
1.349     albertel 5813: }
1.795     www      5814: 
1.349     albertel 5815: table.LC_calendar_pickdate {
                   5816:   font-size: xx-small;
                   5817: }
1.795     www      5818: 
1.349     albertel 5819: table.LC_calendar tr td {
                   5820:   border: 1px solid #000000;
                   5821:   vertical-align: top;
1.917     raeburn  5822:   width: 14%;
1.349     albertel 5823: }
1.795     www      5824: 
1.349     albertel 5825: table.LC_calendar tr td.LC_calendar_day_empty {
                   5826:   background-color: $data_table_dark;
                   5827: }
1.795     www      5828: 
1.779     bisitz   5829: table.LC_calendar tr td.LC_calendar_day_current {
                   5830:   background-color: $data_table_highlight;
1.777     tempelho 5831: }
1.795     www      5832: 
1.938     bisitz   5833: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5834:   background-color: $mail_new;
                   5835: }
1.795     www      5836: 
1.938     bisitz   5837: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5838:   background-color: $mail_new_hover;
                   5839: }
1.795     www      5840: 
1.938     bisitz   5841: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5842:   background-color: $mail_read;
                   5843: }
1.795     www      5844: 
1.938     bisitz   5845: /*
                   5846: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5847:   background-color: $mail_read_hover;
                   5848: }
1.938     bisitz   5849: */
1.795     www      5850: 
1.938     bisitz   5851: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5852:   background-color: $mail_replied;
                   5853: }
1.795     www      5854: 
1.938     bisitz   5855: /*
                   5856: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5857:   background-color: $mail_replied_hover;
                   5858: }
1.938     bisitz   5859: */
1.795     www      5860: 
1.938     bisitz   5861: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5862:   background-color: $mail_other;
                   5863: }
1.795     www      5864: 
1.938     bisitz   5865: /*
                   5866: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5867:   background-color: $mail_other_hover;
                   5868: }
1.938     bisitz   5869: */
1.494     raeburn  5870: 
1.777     tempelho 5871: table.LC_data_table tr > td.LC_browser_file,
                   5872: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5873:   background: #AAEE77;
1.389     albertel 5874: }
1.795     www      5875: 
1.777     tempelho 5876: table.LC_data_table tr > td.LC_browser_file_locked,
                   5877: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5878:   background: #FFAA99;
1.387     albertel 5879: }
1.795     www      5880: 
1.777     tempelho 5881: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5882:   background: #888888;
1.779     bisitz   5883: }
1.795     www      5884: 
1.777     tempelho 5885: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5886: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5887:   background: #F8F866;
1.777     tempelho 5888: }
1.795     www      5889: 
1.696     bisitz   5890: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5891:   background: #E0E8FF;
1.387     albertel 5892: }
1.696     bisitz   5893: 
1.707     bisitz   5894: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5895:   /* background: #77FF77; */
1.707     bisitz   5896: }
1.795     www      5897: 
1.707     bisitz   5898: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5899:   border-right: 8px solid #FFFF77;
1.707     bisitz   5900: }
1.795     www      5901: 
1.707     bisitz   5902: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5903:   border-right: 8px solid #FFAA77;
1.707     bisitz   5904: }
1.795     www      5905: 
1.707     bisitz   5906: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5907:   border-right: 8px solid #FF7777;
1.707     bisitz   5908: }
1.795     www      5909: 
1.707     bisitz   5910: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5911:   border-right: 8px solid #AAFF77;
1.707     bisitz   5912: }
1.795     www      5913: 
1.707     bisitz   5914: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5915:   border-right: 8px solid #11CC55;
1.707     bisitz   5916: }
                   5917: 
1.388     albertel 5918: span.LC_current_location {
1.701     harmsja  5919:   font-size:larger;
1.388     albertel 5920:   background: $pgbg;
                   5921: }
1.387     albertel 5922: 
1.1029    www      5923: span.LC_current_nav_location {
                   5924:   font-weight:bold;
                   5925:   background: $sidebg;
                   5926: }
                   5927: 
1.395     albertel 5928: span.LC_parm_menu_item {
                   5929:   font-size: larger;
                   5930: }
1.795     www      5931: 
1.395     albertel 5932: span.LC_parm_scope_all {
                   5933:   color: red;
                   5934: }
1.795     www      5935: 
1.395     albertel 5936: span.LC_parm_scope_folder {
                   5937:   color: green;
                   5938: }
1.795     www      5939: 
1.395     albertel 5940: span.LC_parm_scope_resource {
                   5941:   color: orange;
                   5942: }
1.795     www      5943: 
1.395     albertel 5944: span.LC_parm_part {
                   5945:   color: blue;
                   5946: }
1.795     www      5947: 
1.911     bisitz   5948: span.LC_parm_folder,
                   5949: span.LC_parm_symb {
1.395     albertel 5950:   font-size: x-small;
                   5951:   font-family: $mono;
                   5952:   color: #AAAAAA;
                   5953: }
                   5954: 
1.977     bisitz   5955: ul.LC_parm_parmlist li {
                   5956:   display: inline-block;
                   5957:   padding: 0.3em 0.8em;
                   5958:   vertical-align: top;
                   5959:   width: 150px;
                   5960:   border-top:1px solid $lg_border_color;
                   5961: }
                   5962: 
1.795     www      5963: td.LC_parm_overview_level_menu,
                   5964: td.LC_parm_overview_map_menu,
                   5965: td.LC_parm_overview_parm_selectors,
                   5966: td.LC_parm_overview_restrictions  {
1.396     albertel 5967:   border: 1px solid black;
                   5968:   border-collapse: collapse;
                   5969: }
1.795     www      5970: 
1.396     albertel 5971: table.LC_parm_overview_restrictions td {
                   5972:   border-width: 1px 4px 1px 4px;
                   5973:   border-style: solid;
                   5974:   border-color: $pgbg;
                   5975:   text-align: center;
                   5976: }
1.795     www      5977: 
1.396     albertel 5978: table.LC_parm_overview_restrictions th {
                   5979:   background: $tabbg;
                   5980:   border-width: 1px 4px 1px 4px;
                   5981:   border-style: solid;
                   5982:   border-color: $pgbg;
                   5983: }
1.795     www      5984: 
1.398     albertel 5985: table#LC_helpmenu {
1.803     bisitz   5986:   border: none;
1.398     albertel 5987:   height: 55px;
1.803     bisitz   5988:   border-spacing: 0;
1.398     albertel 5989: }
                   5990: 
                   5991: table#LC_helpmenu fieldset legend {
                   5992:   font-size: larger;
                   5993: }
1.795     www      5994: 
1.397     albertel 5995: table#LC_helpmenu_links {
                   5996:   width: 100%;
                   5997:   border: 1px solid black;
                   5998:   background: $pgbg;
1.803     bisitz   5999:   padding: 0;
1.397     albertel 6000:   border-spacing: 1px;
                   6001: }
1.795     www      6002: 
1.397     albertel 6003: table#LC_helpmenu_links tr td {
                   6004:   padding: 1px;
                   6005:   background: $tabbg;
1.399     albertel 6006:   text-align: center;
                   6007:   font-weight: bold;
1.397     albertel 6008: }
1.396     albertel 6009: 
1.795     www      6010: table#LC_helpmenu_links a:link,
                   6011: table#LC_helpmenu_links a:visited,
1.397     albertel 6012: table#LC_helpmenu_links a:active {
                   6013:   text-decoration: none;
                   6014:   color: $font;
                   6015: }
1.795     www      6016: 
1.397     albertel 6017: table#LC_helpmenu_links a:hover {
                   6018:   text-decoration: underline;
                   6019:   color: $vlink;
                   6020: }
1.396     albertel 6021: 
1.417     albertel 6022: .LC_chrt_popup_exists {
                   6023:   border: 1px solid #339933;
                   6024:   margin: -1px;
                   6025: }
1.795     www      6026: 
1.417     albertel 6027: .LC_chrt_popup_up {
                   6028:   border: 1px solid yellow;
                   6029:   margin: -1px;
                   6030: }
1.795     www      6031: 
1.417     albertel 6032: .LC_chrt_popup {
                   6033:   border: 1px solid #8888FF;
                   6034:   background: #CCCCFF;
                   6035: }
1.795     www      6036: 
1.421     albertel 6037: table.LC_pick_box {
                   6038:   border-collapse: separate;
                   6039:   background: white;
                   6040:   border: 1px solid black;
                   6041:   border-spacing: 1px;
                   6042: }
1.795     www      6043: 
1.421     albertel 6044: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6045:   background: $sidebg;
1.421     albertel 6046:   font-weight: bold;
1.900     bisitz   6047:   text-align: left;
1.740     bisitz   6048:   vertical-align: top;
1.421     albertel 6049:   width: 184px;
                   6050:   padding: 8px;
                   6051: }
1.795     www      6052: 
1.579     raeburn  6053: table.LC_pick_box td.LC_pick_box_value {
                   6054:   text-align: left;
                   6055:   padding: 8px;
                   6056: }
1.795     www      6057: 
1.579     raeburn  6058: table.LC_pick_box td.LC_pick_box_select {
                   6059:   text-align: left;
                   6060:   padding: 8px;
                   6061: }
1.795     www      6062: 
1.424     albertel 6063: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6064:   padding: 0;
1.421     albertel 6065:   height: 1px;
                   6066:   background: black;
                   6067: }
1.795     www      6068: 
1.421     albertel 6069: table.LC_pick_box td.LC_pick_box_submit {
                   6070:   text-align: right;
                   6071: }
1.795     www      6072: 
1.579     raeburn  6073: table.LC_pick_box td.LC_evenrow_value {
                   6074:   text-align: left;
                   6075:   padding: 8px;
                   6076:   background-color: $data_table_light;
                   6077: }
1.795     www      6078: 
1.579     raeburn  6079: table.LC_pick_box td.LC_oddrow_value {
                   6080:   text-align: left;
                   6081:   padding: 8px;
                   6082:   background-color: $data_table_light;
                   6083: }
1.795     www      6084: 
1.579     raeburn  6085: span.LC_helpform_receipt_cat {
                   6086:   font-weight: bold;
                   6087: }
1.795     www      6088: 
1.424     albertel 6089: table.LC_group_priv_box {
                   6090:   background: white;
                   6091:   border: 1px solid black;
                   6092:   border-spacing: 1px;
                   6093: }
1.795     www      6094: 
1.424     albertel 6095: table.LC_group_priv_box td.LC_pick_box_title {
                   6096:   background: $tabbg;
                   6097:   font-weight: bold;
                   6098:   text-align: right;
                   6099:   width: 184px;
                   6100: }
1.795     www      6101: 
1.424     albertel 6102: table.LC_group_priv_box td.LC_groups_fixed {
                   6103:   background: $data_table_light;
                   6104:   text-align: center;
                   6105: }
1.795     www      6106: 
1.424     albertel 6107: table.LC_group_priv_box td.LC_groups_optional {
                   6108:   background: $data_table_dark;
                   6109:   text-align: center;
                   6110: }
1.795     www      6111: 
1.424     albertel 6112: table.LC_group_priv_box td.LC_groups_functionality {
                   6113:   background: $data_table_darker;
                   6114:   text-align: center;
                   6115:   font-weight: bold;
                   6116: }
1.795     www      6117: 
1.424     albertel 6118: table.LC_group_priv td {
                   6119:   text-align: left;
1.803     bisitz   6120:   padding: 0;
1.424     albertel 6121: }
                   6122: 
                   6123: .LC_navbuttons {
                   6124:   margin: 2ex 0ex 2ex 0ex;
                   6125: }
1.795     www      6126: 
1.423     albertel 6127: .LC_topic_bar {
                   6128:   font-weight: bold;
                   6129:   background: $tabbg;
1.918     wenzelju 6130:   margin: 1em 0em 1em 2em;
1.805     bisitz   6131:   padding: 3px;
1.918     wenzelju 6132:   font-size: 1.2em;
1.423     albertel 6133: }
1.795     www      6134: 
1.423     albertel 6135: .LC_topic_bar span {
1.918     wenzelju 6136:   left: 0.5em;
                   6137:   position: absolute;
1.423     albertel 6138:   vertical-align: middle;
1.918     wenzelju 6139:   font-size: 1.2em;
1.423     albertel 6140: }
1.795     www      6141: 
1.423     albertel 6142: table.LC_course_group_status {
                   6143:   margin: 20px;
                   6144: }
1.795     www      6145: 
1.423     albertel 6146: table.LC_status_selector td {
                   6147:   vertical-align: top;
                   6148:   text-align: center;
1.424     albertel 6149:   padding: 4px;
                   6150: }
1.795     www      6151: 
1.599     albertel 6152: div.LC_feedback_link {
1.616     albertel 6153:   clear: both;
1.829     kalberla 6154:   background: $sidebg;
1.779     bisitz   6155:   width: 100%;
1.829     kalberla 6156:   padding-bottom: 10px;
                   6157:   border: 1px $tabbg solid;
1.833     kalberla 6158:   height: 22px;
                   6159:   line-height: 22px;
                   6160:   padding-top: 5px;
                   6161: }
                   6162: 
                   6163: div.LC_feedback_link img {
                   6164:   height: 22px;
1.867     kalberla 6165:   vertical-align:middle;
1.829     kalberla 6166: }
                   6167: 
1.911     bisitz   6168: div.LC_feedback_link a {
1.829     kalberla 6169:   text-decoration: none;
1.489     raeburn  6170: }
1.795     www      6171: 
1.867     kalberla 6172: div.LC_comblock {
1.911     bisitz   6173:   display:inline;
1.867     kalberla 6174:   color:$font;
                   6175:   font-size:90%;
                   6176: }
                   6177: 
                   6178: div.LC_feedback_link div.LC_comblock {
                   6179:   padding-left:5px;
                   6180: }
                   6181: 
                   6182: div.LC_feedback_link div.LC_comblock a {
                   6183:   color:$font;
                   6184: }
                   6185: 
1.489     raeburn  6186: span.LC_feedback_link {
1.858     bisitz   6187:   /* background: $feedback_link_bg; */
1.599     albertel 6188:   font-size: larger;
                   6189: }
1.795     www      6190: 
1.599     albertel 6191: span.LC_message_link {
1.858     bisitz   6192:   /* background: $feedback_link_bg; */
1.599     albertel 6193:   font-size: larger;
                   6194:   position: absolute;
                   6195:   right: 1em;
1.489     raeburn  6196: }
1.421     albertel 6197: 
1.515     albertel 6198: table.LC_prior_tries {
1.524     albertel 6199:   border: 1px solid #000000;
                   6200:   border-collapse: separate;
                   6201:   border-spacing: 1px;
1.515     albertel 6202: }
1.523     albertel 6203: 
1.515     albertel 6204: table.LC_prior_tries td {
1.524     albertel 6205:   padding: 2px;
1.515     albertel 6206: }
1.523     albertel 6207: 
                   6208: .LC_answer_correct {
1.795     www      6209:   background: lightgreen;
                   6210:   color: darkgreen;
                   6211:   padding: 6px;
1.523     albertel 6212: }
1.795     www      6213: 
1.523     albertel 6214: .LC_answer_charged_try {
1.797     www      6215:   background: #FFAAAA;
1.795     www      6216:   color: darkred;
                   6217:   padding: 6px;
1.523     albertel 6218: }
1.795     www      6219: 
1.779     bisitz   6220: .LC_answer_not_charged_try,
1.523     albertel 6221: .LC_answer_no_grade,
                   6222: .LC_answer_late {
1.795     www      6223:   background: lightyellow;
1.523     albertel 6224:   color: black;
1.795     www      6225:   padding: 6px;
1.523     albertel 6226: }
1.795     www      6227: 
1.523     albertel 6228: .LC_answer_previous {
1.795     www      6229:   background: lightblue;
                   6230:   color: darkblue;
                   6231:   padding: 6px;
1.523     albertel 6232: }
1.795     www      6233: 
1.779     bisitz   6234: .LC_answer_no_message {
1.777     tempelho 6235:   background: #FFFFFF;
                   6236:   color: black;
1.795     www      6237:   padding: 6px;
1.779     bisitz   6238: }
1.795     www      6239: 
1.779     bisitz   6240: .LC_answer_unknown {
                   6241:   background: orange;
                   6242:   color: black;
1.795     www      6243:   padding: 6px;
1.777     tempelho 6244: }
1.795     www      6245: 
1.529     albertel 6246: span.LC_prior_numerical,
                   6247: span.LC_prior_string,
                   6248: span.LC_prior_custom,
                   6249: span.LC_prior_reaction,
                   6250: span.LC_prior_math {
1.925     bisitz   6251:   font-family: $mono;
1.523     albertel 6252:   white-space: pre;
                   6253: }
                   6254: 
1.525     albertel 6255: span.LC_prior_string {
1.925     bisitz   6256:   font-family: $mono;
1.525     albertel 6257:   white-space: pre;
                   6258: }
                   6259: 
1.523     albertel 6260: table.LC_prior_option {
                   6261:   width: 100%;
                   6262:   border-collapse: collapse;
                   6263: }
1.795     www      6264: 
1.911     bisitz   6265: table.LC_prior_rank,
1.795     www      6266: table.LC_prior_match {
1.528     albertel 6267:   border-collapse: collapse;
                   6268: }
1.795     www      6269: 
1.528     albertel 6270: table.LC_prior_option tr td,
                   6271: table.LC_prior_rank tr td,
                   6272: table.LC_prior_match tr td {
1.524     albertel 6273:   border: 1px solid #000000;
1.515     albertel 6274: }
                   6275: 
1.855     bisitz   6276: .LC_nobreak {
1.544     albertel 6277:   white-space: nowrap;
1.519     raeburn  6278: }
                   6279: 
1.576     raeburn  6280: span.LC_cusr_emph {
                   6281:   font-style: italic;
                   6282: }
                   6283: 
1.633     raeburn  6284: span.LC_cusr_subheading {
                   6285:   font-weight: normal;
                   6286:   font-size: 85%;
                   6287: }
                   6288: 
1.861     bisitz   6289: div.LC_docs_entry_move {
1.859     bisitz   6290:   border: 1px solid #BBBBBB;
1.545     albertel 6291:   background: #DDDDDD;
1.861     bisitz   6292:   width: 22px;
1.859     bisitz   6293:   padding: 1px;
                   6294:   margin: 0;
1.545     albertel 6295: }
                   6296: 
1.861     bisitz   6297: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6298: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6299:   font-size: x-small;
                   6300: }
1.795     www      6301: 
1.861     bisitz   6302: .LC_docs_entry_parameter {
                   6303:   white-space: nowrap;
                   6304: }
                   6305: 
1.544     albertel 6306: .LC_docs_copy {
1.545     albertel 6307:   color: #000099;
1.544     albertel 6308: }
1.795     www      6309: 
1.544     albertel 6310: .LC_docs_cut {
1.545     albertel 6311:   color: #550044;
1.544     albertel 6312: }
1.795     www      6313: 
1.544     albertel 6314: .LC_docs_rename {
1.545     albertel 6315:   color: #009900;
1.544     albertel 6316: }
1.795     www      6317: 
1.544     albertel 6318: .LC_docs_remove {
1.545     albertel 6319:   color: #990000;
                   6320: }
                   6321: 
1.547     albertel 6322: .LC_docs_reinit_warn,
                   6323: .LC_docs_ext_edit {
                   6324:   font-size: x-small;
                   6325: }
                   6326: 
1.545     albertel 6327: table.LC_docs_adddocs td,
                   6328: table.LC_docs_adddocs th {
                   6329:   border: 1px solid #BBBBBB;
                   6330:   padding: 4px;
                   6331:   background: #DDDDDD;
1.543     albertel 6332: }
                   6333: 
1.584     albertel 6334: table.LC_sty_begin {
                   6335:   background: #BBFFBB;
                   6336: }
1.795     www      6337: 
1.584     albertel 6338: table.LC_sty_end {
                   6339:   background: #FFBBBB;
                   6340: }
                   6341: 
1.589     raeburn  6342: table.LC_double_column {
1.803     bisitz   6343:   border-width: 0;
1.589     raeburn  6344:   border-collapse: collapse;
                   6345:   width: 100%;
                   6346:   padding: 2px;
                   6347: }
                   6348: 
                   6349: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6350:   top: 2px;
1.589     raeburn  6351:   left: 2px;
                   6352:   width: 47%;
                   6353:   vertical-align: top;
                   6354: }
                   6355: 
                   6356: table.LC_double_column tr td.LC_right_col {
                   6357:   top: 2px;
1.779     bisitz   6358:   right: 2px;
1.589     raeburn  6359:   width: 47%;
                   6360:   vertical-align: top;
                   6361: }
                   6362: 
1.591     raeburn  6363: div.LC_left_float {
                   6364:   float: left;
                   6365:   padding-right: 5%;
1.597     albertel 6366:   padding-bottom: 4px;
1.591     raeburn  6367: }
                   6368: 
                   6369: div.LC_clear_float_header {
1.597     albertel 6370:   padding-bottom: 2px;
1.591     raeburn  6371: }
                   6372: 
                   6373: div.LC_clear_float_footer {
1.597     albertel 6374:   padding-top: 10px;
1.591     raeburn  6375:   clear: both;
                   6376: }
                   6377: 
1.597     albertel 6378: div.LC_grade_show_user {
1.941     bisitz   6379: /*  border-left: 5px solid $sidebg; */
                   6380:   border-top: 5px solid #000000;
                   6381:   margin: 50px 0 0 0;
1.936     bisitz   6382:   padding: 15px 0 5px 10px;
1.597     albertel 6383: }
1.795     www      6384: 
1.936     bisitz   6385: div.LC_grade_show_user_odd_row {
1.941     bisitz   6386: /*  border-left: 5px solid #000000; */
                   6387: }
                   6388: 
                   6389: div.LC_grade_show_user div.LC_Box {
                   6390:   margin-right: 50px;
1.597     albertel 6391: }
                   6392: 
                   6393: div.LC_grade_submissions,
                   6394: div.LC_grade_message_center,
1.936     bisitz   6395: div.LC_grade_info_links {
1.597     albertel 6396:   margin: 5px;
                   6397:   width: 99%;
                   6398:   background: #FFFFFF;
                   6399: }
1.795     www      6400: 
1.597     albertel 6401: div.LC_grade_submissions_header,
1.936     bisitz   6402: div.LC_grade_message_center_header {
1.705     tempelho 6403:   font-weight: bold;
                   6404:   font-size: large;
1.597     albertel 6405: }
1.795     www      6406: 
1.597     albertel 6407: div.LC_grade_submissions_body,
1.936     bisitz   6408: div.LC_grade_message_center_body {
1.597     albertel 6409:   border: 1px solid black;
                   6410:   width: 99%;
                   6411:   background: #FFFFFF;
                   6412: }
1.795     www      6413: 
1.613     albertel 6414: table.LC_scantron_action {
                   6415:   width: 100%;
                   6416: }
1.795     www      6417: 
1.613     albertel 6418: table.LC_scantron_action tr th {
1.698     harmsja  6419:   font-weight:bold;
                   6420:   font-style:normal;
1.613     albertel 6421: }
1.795     www      6422: 
1.779     bisitz   6423: .LC_edit_problem_header,
1.614     albertel 6424: div.LC_edit_problem_footer {
1.705     tempelho 6425:   font-weight: normal;
                   6426:   font-size:  medium;
1.602     albertel 6427:   margin: 2px;
1.1060    bisitz   6428:   background-color: $sidebg;
1.600     albertel 6429: }
1.795     www      6430: 
1.600     albertel 6431: div.LC_edit_problem_header,
1.602     albertel 6432: div.LC_edit_problem_header div,
1.614     albertel 6433: div.LC_edit_problem_footer,
                   6434: div.LC_edit_problem_footer div,
1.602     albertel 6435: div.LC_edit_problem_editxml_header,
                   6436: div.LC_edit_problem_editxml_header div {
1.600     albertel 6437:   margin-top: 5px;
                   6438: }
1.795     www      6439: 
1.600     albertel 6440: div.LC_edit_problem_header_title {
1.705     tempelho 6441:   font-weight: bold;
                   6442:   font-size: larger;
1.602     albertel 6443:   background: $tabbg;
                   6444:   padding: 3px;
1.1060    bisitz   6445:   margin: 0 0 5px 0;
1.602     albertel 6446: }
1.795     www      6447: 
1.602     albertel 6448: table.LC_edit_problem_header_title {
                   6449:   width: 100%;
1.600     albertel 6450:   background: $tabbg;
1.602     albertel 6451: }
                   6452: 
                   6453: div.LC_edit_problem_discards {
                   6454:   float: left;
                   6455:   padding-bottom: 5px;
                   6456: }
1.795     www      6457: 
1.602     albertel 6458: div.LC_edit_problem_saves {
                   6459:   float: right;
                   6460:   padding-bottom: 5px;
1.600     albertel 6461: }
1.795     www      6462: 
1.1075.2.34  raeburn  6463: .LC_edit_opt {
                   6464:   padding-left: 1em;
                   6465:   white-space: nowrap;
                   6466: }
                   6467: 
1.911     bisitz   6468: img.stift {
1.803     bisitz   6469:   border-width: 0;
                   6470:   vertical-align: middle;
1.677     riegler  6471: }
1.680     riegler  6472: 
1.923     bisitz   6473: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6474:   vertical-align: top;
1.777     tempelho 6475: }
1.795     www      6476: 
1.716     raeburn  6477: div.LC_createcourse {
1.911     bisitz   6478:   margin: 10px 10px 10px 10px;
1.716     raeburn  6479: }
                   6480: 
1.917     raeburn  6481: .LC_dccid {
1.1075.2.38! raeburn  6482:   float: right;
1.917     raeburn  6483:   margin: 0.2em 0 0 0;
                   6484:   padding: 0;
                   6485:   font-size: 90%;
                   6486:   display:none;
                   6487: }
                   6488: 
1.897     wenzelju 6489: ol.LC_primary_menu a:hover,
1.721     harmsja  6490: ol#LC_MenuBreadcrumbs a:hover,
                   6491: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6492: ul#LC_secondary_menu a:hover,
1.721     harmsja  6493: .LC_FormSectionClearButton input:hover
1.795     www      6494: ul.LC_TabContent   li:hover a {
1.952     onken    6495:   color:$button_hover;
1.911     bisitz   6496:   text-decoration:none;
1.693     droeschl 6497: }
                   6498: 
1.779     bisitz   6499: h1 {
1.911     bisitz   6500:   padding: 0;
                   6501:   line-height:130%;
1.693     droeschl 6502: }
1.698     harmsja  6503: 
1.911     bisitz   6504: h2,
                   6505: h3,
                   6506: h4,
                   6507: h5,
                   6508: h6 {
                   6509:   margin: 5px 0 5px 0;
                   6510:   padding: 0;
                   6511:   line-height:130%;
1.693     droeschl 6512: }
1.795     www      6513: 
                   6514: .LC_hcell {
1.911     bisitz   6515:   padding:3px 15px 3px 15px;
                   6516:   margin: 0;
                   6517:   background-color:$tabbg;
                   6518:   color:$fontmenu;
                   6519:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6520: }
1.795     www      6521: 
1.840     bisitz   6522: .LC_Box > .LC_hcell {
1.911     bisitz   6523:   margin: 0 -10px 10px -10px;
1.835     bisitz   6524: }
                   6525: 
1.721     harmsja  6526: .LC_noBorder {
1.911     bisitz   6527:   border: 0;
1.698     harmsja  6528: }
1.693     droeschl 6529: 
1.721     harmsja  6530: .LC_FormSectionClearButton input {
1.911     bisitz   6531:   background-color:transparent;
                   6532:   border: none;
                   6533:   cursor:pointer;
                   6534:   text-decoration:underline;
1.693     droeschl 6535: }
1.763     bisitz   6536: 
                   6537: .LC_help_open_topic {
1.911     bisitz   6538:   color: #FFFFFF;
                   6539:   background-color: #EEEEFF;
                   6540:   margin: 1px;
                   6541:   padding: 4px;
                   6542:   border: 1px solid #000033;
                   6543:   white-space: nowrap;
                   6544:   /* vertical-align: middle; */
1.759     neumanie 6545: }
1.693     droeschl 6546: 
1.911     bisitz   6547: dl,
                   6548: ul,
                   6549: div,
                   6550: fieldset {
                   6551:   margin: 10px 10px 10px 0;
                   6552:   /* overflow: hidden; */
1.693     droeschl 6553: }
1.795     www      6554: 
1.838     bisitz   6555: fieldset > legend {
1.911     bisitz   6556:   font-weight: bold;
                   6557:   padding: 0 5px 0 5px;
1.838     bisitz   6558: }
                   6559: 
1.813     bisitz   6560: #LC_nav_bar {
1.911     bisitz   6561:   float: left;
1.995     raeburn  6562:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6563:   margin: 0 0 2px 0;
1.807     droeschl 6564: }
                   6565: 
1.916     droeschl 6566: #LC_realm {
                   6567:   margin: 0.2em 0 0 0;
                   6568:   padding: 0;
                   6569:   font-weight: bold;
                   6570:   text-align: center;
1.995     raeburn  6571:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6572: }
                   6573: 
1.911     bisitz   6574: #LC_nav_bar em {
                   6575:   font-weight: bold;
                   6576:   font-style: normal;
1.807     droeschl 6577: }
                   6578: 
1.897     wenzelju 6579: ol.LC_primary_menu {
1.934     droeschl 6580:   margin: 0;
1.1075.2.2  raeburn  6581:   padding: 0;
1.995     raeburn  6582:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6583: }
                   6584: 
1.852     droeschl 6585: ol#LC_PathBreadcrumbs {
1.911     bisitz   6586:   margin: 0;
1.693     droeschl 6587: }
                   6588: 
1.897     wenzelju 6589: ol.LC_primary_menu li {
1.1075.2.2  raeburn  6590:   color: RGB(80, 80, 80);
                   6591:   vertical-align: middle;
                   6592:   text-align: left;
                   6593:   list-style: none;
                   6594:   float: left;
                   6595: }
                   6596: 
                   6597: ol.LC_primary_menu li a {
                   6598:   display: block;
                   6599:   margin: 0;
                   6600:   padding: 0 5px 0 10px;
                   6601:   text-decoration: none;
                   6602: }
                   6603: 
                   6604: ol.LC_primary_menu li ul {
                   6605:   display: none;
                   6606:   width: 10em;
                   6607:   background-color: $data_table_light;
                   6608: }
                   6609: 
                   6610: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6611:   display: block;
                   6612:   position: absolute;
                   6613:   margin: 0;
                   6614:   padding: 0;
1.1075.2.5  raeburn  6615:   z-index: 2;
1.1075.2.2  raeburn  6616: }
                   6617: 
                   6618: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6619:   font-size: 90%;
1.911     bisitz   6620:   vertical-align: top;
1.1075.2.2  raeburn  6621:   float: none;
1.1075.2.5  raeburn  6622:   border-left: 1px solid black;
                   6623:   border-right: 1px solid black;
1.1075.2.2  raeburn  6624: }
                   6625: 
                   6626: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1075.2.5  raeburn  6627:   background-color:$data_table_light;
1.1075.2.2  raeburn  6628: }
                   6629: 
                   6630: ol.LC_primary_menu li li a:hover {
                   6631:    color:$button_hover;
                   6632:    background-color:$data_table_dark;
1.693     droeschl 6633: }
                   6634: 
1.897     wenzelju 6635: ol.LC_primary_menu li img {
1.911     bisitz   6636:   vertical-align: bottom;
1.934     droeschl 6637:   height: 1.1em;
1.1075.2.3  raeburn  6638:   margin: 0.2em 0 0 0;
1.693     droeschl 6639: }
                   6640: 
1.897     wenzelju 6641: ol.LC_primary_menu a {
1.911     bisitz   6642:   color: RGB(80, 80, 80);
                   6643:   text-decoration: none;
1.693     droeschl 6644: }
1.795     www      6645: 
1.949     droeschl 6646: ol.LC_primary_menu a.LC_new_message {
                   6647:   font-weight:bold;
                   6648:   color: darkred;
                   6649: }
                   6650: 
1.975     raeburn  6651: ol.LC_docs_parameters {
                   6652:   margin-left: 0;
                   6653:   padding: 0;
                   6654:   list-style: none;
                   6655: }
                   6656: 
                   6657: ol.LC_docs_parameters li {
                   6658:   margin: 0;
                   6659:   padding-right: 20px;
                   6660:   display: inline;
                   6661: }
                   6662: 
1.976     raeburn  6663: ol.LC_docs_parameters li:before {
                   6664:   content: "\\002022 \\0020";
                   6665: }
                   6666: 
                   6667: li.LC_docs_parameters_title {
                   6668:   font-weight: bold;
                   6669: }
                   6670: 
                   6671: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6672:   content: "";
                   6673: }
                   6674: 
1.897     wenzelju 6675: ul#LC_secondary_menu {
1.1075.2.23  raeburn  6676:   clear: right;
1.911     bisitz   6677:   color: $fontmenu;
                   6678:   background: $tabbg;
                   6679:   list-style: none;
                   6680:   padding: 0;
                   6681:   margin: 0;
                   6682:   width: 100%;
1.995     raeburn  6683:   text-align: left;
1.1075.2.4  raeburn  6684:   float: left;
1.808     droeschl 6685: }
                   6686: 
1.897     wenzelju 6687: ul#LC_secondary_menu li {
1.911     bisitz   6688:   font-weight: bold;
                   6689:   line-height: 1.8em;
                   6690:   border-right: 1px solid black;
                   6691:   vertical-align: middle;
1.1075.2.4  raeburn  6692:   float: left;
                   6693: }
                   6694: 
                   6695: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6696:   background-color: $data_table_light;
                   6697: }
                   6698: 
                   6699: ul#LC_secondary_menu li a {
                   6700:   padding: 0 0.8em;
                   6701: }
                   6702: 
                   6703: ul#LC_secondary_menu li ul {
                   6704:   display: none;
                   6705: }
                   6706: 
                   6707: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6708:   display: block;
                   6709:   position: absolute;
                   6710:   margin: 0;
                   6711:   padding: 0;
                   6712:   list-style:none;
                   6713:   float: none;
                   6714:   background-color: $data_table_light;
1.1075.2.5  raeburn  6715:   z-index: 2;
1.1075.2.10  raeburn  6716:   margin-left: -1px;
1.1075.2.4  raeburn  6717: }
                   6718: 
                   6719: ul#LC_secondary_menu li ul li {
                   6720:   font-size: 90%;
                   6721:   vertical-align: top;
                   6722:   border-left: 1px solid black;
                   6723:   border-right: 1px solid black;
1.1075.2.33  raeburn  6724:   background-color: $data_table_light;
1.1075.2.4  raeburn  6725:   list-style:none;
                   6726:   float: none;
                   6727: }
                   6728: 
                   6729: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6730:   background-color: $data_table_dark;
1.807     droeschl 6731: }
                   6732: 
1.847     tempelho 6733: ul.LC_TabContent {
1.911     bisitz   6734:   display:block;
                   6735:   background: $sidebg;
                   6736:   border-bottom: solid 1px $lg_border_color;
                   6737:   list-style:none;
1.1020    raeburn  6738:   margin: -1px -10px 0 -10px;
1.911     bisitz   6739:   padding: 0;
1.693     droeschl 6740: }
                   6741: 
1.795     www      6742: ul.LC_TabContent li,
                   6743: ul.LC_TabContentBigger li {
1.911     bisitz   6744:   float:left;
1.741     harmsja  6745: }
1.795     www      6746: 
1.897     wenzelju 6747: ul#LC_secondary_menu li a {
1.911     bisitz   6748:   color: $fontmenu;
                   6749:   text-decoration: none;
1.693     droeschl 6750: }
1.795     www      6751: 
1.721     harmsja  6752: ul.LC_TabContent {
1.952     onken    6753:   min-height:20px;
1.721     harmsja  6754: }
1.795     www      6755: 
                   6756: ul.LC_TabContent li {
1.911     bisitz   6757:   vertical-align:middle;
1.959     onken    6758:   padding: 0 16px 0 10px;
1.911     bisitz   6759:   background-color:$tabbg;
                   6760:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6761:   border-left: solid 1px $font;
1.721     harmsja  6762: }
1.795     www      6763: 
1.847     tempelho 6764: ul.LC_TabContent .right {
1.911     bisitz   6765:   float:right;
1.847     tempelho 6766: }
                   6767: 
1.911     bisitz   6768: ul.LC_TabContent li a,
                   6769: ul.LC_TabContent li {
                   6770:   color:rgb(47,47,47);
                   6771:   text-decoration:none;
                   6772:   font-size:95%;
                   6773:   font-weight:bold;
1.952     onken    6774:   min-height:20px;
                   6775: }
                   6776: 
1.959     onken    6777: ul.LC_TabContent li a:hover,
                   6778: ul.LC_TabContent li a:focus {
1.952     onken    6779:   color: $button_hover;
1.959     onken    6780:   background:none;
                   6781:   outline:none;
1.952     onken    6782: }
                   6783: 
                   6784: ul.LC_TabContent li:hover {
                   6785:   color: $button_hover;
                   6786:   cursor:pointer;
1.721     harmsja  6787: }
1.795     www      6788: 
1.911     bisitz   6789: ul.LC_TabContent li.active {
1.952     onken    6790:   color: $font;
1.911     bisitz   6791:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6792:   border-bottom:solid 1px #FFFFFF;
                   6793:   cursor: default;
1.744     ehlerst  6794: }
1.795     www      6795: 
1.959     onken    6796: ul.LC_TabContent li.active a {
                   6797:   color:$font;
                   6798:   background:#FFFFFF;
                   6799:   outline: none;
                   6800: }
1.1047    raeburn  6801: 
                   6802: ul.LC_TabContent li.goback {
                   6803:   float: left;
                   6804:   border-left: none;
                   6805: }
                   6806: 
1.870     tempelho 6807: #maincoursedoc {
1.911     bisitz   6808:   clear:both;
1.870     tempelho 6809: }
                   6810: 
                   6811: ul.LC_TabContentBigger {
1.911     bisitz   6812:   display:block;
                   6813:   list-style:none;
                   6814:   padding: 0;
1.870     tempelho 6815: }
                   6816: 
1.795     www      6817: ul.LC_TabContentBigger li {
1.911     bisitz   6818:   vertical-align:bottom;
                   6819:   height: 30px;
                   6820:   font-size:110%;
                   6821:   font-weight:bold;
                   6822:   color: #737373;
1.841     tempelho 6823: }
                   6824: 
1.957     onken    6825: ul.LC_TabContentBigger li.active {
                   6826:   position: relative;
                   6827:   top: 1px;
                   6828: }
                   6829: 
1.870     tempelho 6830: ul.LC_TabContentBigger li a {
1.911     bisitz   6831:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6832:   height: 30px;
                   6833:   line-height: 30px;
                   6834:   text-align: center;
                   6835:   display: block;
                   6836:   text-decoration: none;
1.958     onken    6837:   outline: none;  
1.741     harmsja  6838: }
1.795     www      6839: 
1.870     tempelho 6840: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6841:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6842:   color:$font;
1.744     ehlerst  6843: }
1.795     www      6844: 
1.870     tempelho 6845: ul.LC_TabContentBigger li b {
1.911     bisitz   6846:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6847:   display: block;
                   6848:   float: left;
                   6849:   padding: 0 30px;
1.957     onken    6850:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6851: }
                   6852: 
1.956     onken    6853: ul.LC_TabContentBigger li:hover b {
                   6854:   color:$button_hover;
                   6855: }
                   6856: 
1.870     tempelho 6857: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6858:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6859:   color:$font;
1.957     onken    6860:   border: 0;
1.741     harmsja  6861: }
1.693     droeschl 6862: 
1.870     tempelho 6863: 
1.862     bisitz   6864: ul.LC_CourseBreadcrumbs {
                   6865:   background: $sidebg;
1.1020    raeburn  6866:   height: 2em;
1.862     bisitz   6867:   padding-left: 10px;
1.1020    raeburn  6868:   margin: 0;
1.862     bisitz   6869:   list-style-position: inside;
                   6870: }
                   6871: 
1.911     bisitz   6872: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6873: ol#LC_PathBreadcrumbs {
1.911     bisitz   6874:   padding-left: 10px;
                   6875:   margin: 0;
1.933     droeschl 6876:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6877: }
                   6878: 
1.911     bisitz   6879: ol#LC_MenuBreadcrumbs li,
                   6880: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6881: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6882:   display: inline;
1.933     droeschl 6883:   white-space: normal;  
1.693     droeschl 6884: }
                   6885: 
1.823     bisitz   6886: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6887: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6888:   text-decoration: none;
                   6889:   font-size:90%;
1.693     droeschl 6890: }
1.795     www      6891: 
1.969     droeschl 6892: ol#LC_MenuBreadcrumbs h1 {
                   6893:   display: inline;
                   6894:   font-size: 90%;
                   6895:   line-height: 2.5em;
                   6896:   margin: 0;
                   6897:   padding: 0;
                   6898: }
                   6899: 
1.795     www      6900: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6901:   text-decoration:none;
                   6902:   font-size:100%;
                   6903:   font-weight:bold;
1.693     droeschl 6904: }
1.795     www      6905: 
1.840     bisitz   6906: .LC_Box {
1.911     bisitz   6907:   border: solid 1px $lg_border_color;
                   6908:   padding: 0 10px 10px 10px;
1.746     neumanie 6909: }
1.795     www      6910: 
1.1020    raeburn  6911: .LC_DocsBox {
                   6912:   border: solid 1px $lg_border_color;
                   6913:   padding: 0 0 10px 10px;
                   6914: }
                   6915: 
1.795     www      6916: .LC_AboutMe_Image {
1.911     bisitz   6917:   float:left;
                   6918:   margin-right:10px;
1.747     neumanie 6919: }
1.795     www      6920: 
                   6921: .LC_Clear_AboutMe_Image {
1.911     bisitz   6922:   clear:left;
1.747     neumanie 6923: }
1.795     www      6924: 
1.721     harmsja  6925: dl.LC_ListStyleClean dt {
1.911     bisitz   6926:   padding-right: 5px;
                   6927:   display: table-header-group;
1.693     droeschl 6928: }
                   6929: 
1.721     harmsja  6930: dl.LC_ListStyleClean dd {
1.911     bisitz   6931:   display: table-row;
1.693     droeschl 6932: }
                   6933: 
1.721     harmsja  6934: .LC_ListStyleClean,
                   6935: .LC_ListStyleSimple,
                   6936: .LC_ListStyleNormal,
1.795     www      6937: .LC_ListStyleSpecial {
1.911     bisitz   6938:   /* display:block; */
                   6939:   list-style-position: inside;
                   6940:   list-style-type: none;
                   6941:   overflow: hidden;
                   6942:   padding: 0;
1.693     droeschl 6943: }
                   6944: 
1.721     harmsja  6945: .LC_ListStyleSimple li,
                   6946: .LC_ListStyleSimple dd,
                   6947: .LC_ListStyleNormal li,
                   6948: .LC_ListStyleNormal dd,
                   6949: .LC_ListStyleSpecial li,
1.795     www      6950: .LC_ListStyleSpecial dd {
1.911     bisitz   6951:   margin: 0;
                   6952:   padding: 5px 5px 5px 10px;
                   6953:   clear: both;
1.693     droeschl 6954: }
                   6955: 
1.721     harmsja  6956: .LC_ListStyleClean li,
                   6957: .LC_ListStyleClean dd {
1.911     bisitz   6958:   padding-top: 0;
                   6959:   padding-bottom: 0;
1.693     droeschl 6960: }
                   6961: 
1.721     harmsja  6962: .LC_ListStyleSimple dd,
1.795     www      6963: .LC_ListStyleSimple li {
1.911     bisitz   6964:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6965: }
                   6966: 
1.721     harmsja  6967: .LC_ListStyleSpecial li,
                   6968: .LC_ListStyleSpecial dd {
1.911     bisitz   6969:   list-style-type: none;
                   6970:   background-color: RGB(220, 220, 220);
                   6971:   margin-bottom: 4px;
1.693     droeschl 6972: }
                   6973: 
1.721     harmsja  6974: table.LC_SimpleTable {
1.911     bisitz   6975:   margin:5px;
                   6976:   border:solid 1px $lg_border_color;
1.795     www      6977: }
1.693     droeschl 6978: 
1.721     harmsja  6979: table.LC_SimpleTable tr {
1.911     bisitz   6980:   padding: 0;
                   6981:   border:solid 1px $lg_border_color;
1.693     droeschl 6982: }
1.795     www      6983: 
                   6984: table.LC_SimpleTable thead {
1.911     bisitz   6985:   background:rgb(220,220,220);
1.693     droeschl 6986: }
                   6987: 
1.721     harmsja  6988: div.LC_columnSection {
1.911     bisitz   6989:   display: block;
                   6990:   clear: both;
                   6991:   overflow: hidden;
                   6992:   margin: 0;
1.693     droeschl 6993: }
                   6994: 
1.721     harmsja  6995: div.LC_columnSection>* {
1.911     bisitz   6996:   float: left;
                   6997:   margin: 10px 20px 10px 0;
                   6998:   overflow:hidden;
1.693     droeschl 6999: }
1.721     harmsja  7000: 
1.795     www      7001: table em {
1.911     bisitz   7002:   font-weight: bold;
                   7003:   font-style: normal;
1.748     schulted 7004: }
1.795     www      7005: 
1.779     bisitz   7006: table.LC_tableBrowseRes,
1.795     www      7007: table.LC_tableOfContent {
1.911     bisitz   7008:   border:none;
                   7009:   border-spacing: 1px;
                   7010:   padding: 3px;
                   7011:   background-color: #FFFFFF;
                   7012:   font-size: 90%;
1.753     droeschl 7013: }
1.789     droeschl 7014: 
1.911     bisitz   7015: table.LC_tableOfContent {
                   7016:   border-collapse: collapse;
1.789     droeschl 7017: }
                   7018: 
1.771     droeschl 7019: table.LC_tableBrowseRes a,
1.768     schulted 7020: table.LC_tableOfContent a {
1.911     bisitz   7021:   background-color: transparent;
                   7022:   text-decoration: none;
1.753     droeschl 7023: }
                   7024: 
1.795     www      7025: table.LC_tableOfContent img {
1.911     bisitz   7026:   border: none;
                   7027:   height: 1.3em;
                   7028:   vertical-align: text-bottom;
                   7029:   margin-right: 0.3em;
1.753     droeschl 7030: }
1.757     schulted 7031: 
1.795     www      7032: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7033:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7034: }
                   7035: 
1.795     www      7036: a#LC_content_toolbar_everything {
1.911     bisitz   7037:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7038: }
                   7039: 
1.795     www      7040: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7041:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7042: }
                   7043: 
1.795     www      7044: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7045:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7046: }
                   7047: 
1.795     www      7048: a#LC_content_toolbar_changefolder {
1.911     bisitz   7049:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7050: }
                   7051: 
1.795     www      7052: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7053:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7054: }
                   7055: 
1.1043    raeburn  7056: a#LC_content_toolbar_edittoplevel {
                   7057:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7058: }
                   7059: 
1.795     www      7060: ul#LC_toolbar li a:hover {
1.911     bisitz   7061:   background-position: bottom center;
1.757     schulted 7062: }
                   7063: 
1.795     www      7064: ul#LC_toolbar {
1.911     bisitz   7065:   padding: 0;
                   7066:   margin: 2px;
                   7067:   list-style:none;
                   7068:   position:relative;
                   7069:   background-color:white;
1.1075.2.9  raeburn  7070:   overflow: auto;
1.757     schulted 7071: }
                   7072: 
1.795     www      7073: ul#LC_toolbar li {
1.911     bisitz   7074:   border:1px solid white;
                   7075:   padding: 0;
                   7076:   margin: 0;
                   7077:   float: left;
                   7078:   display:inline;
                   7079:   vertical-align:middle;
1.1075.2.9  raeburn  7080:   white-space: nowrap;
1.911     bisitz   7081: }
1.757     schulted 7082: 
1.783     amueller 7083: 
1.795     www      7084: a.LC_toolbarItem {
1.911     bisitz   7085:   display:block;
                   7086:   padding: 0;
                   7087:   margin: 0;
                   7088:   height: 32px;
                   7089:   width: 32px;
                   7090:   color:white;
                   7091:   border: none;
                   7092:   background-repeat:no-repeat;
                   7093:   background-color:transparent;
1.757     schulted 7094: }
                   7095: 
1.915     droeschl 7096: ul.LC_funclist {
                   7097:     margin: 0;
                   7098:     padding: 0.5em 1em 0.5em 0;
                   7099: }
                   7100: 
1.933     droeschl 7101: ul.LC_funclist > li:first-child {
                   7102:     font-weight:bold; 
                   7103:     margin-left:0.8em;
                   7104: }
                   7105: 
1.915     droeschl 7106: ul.LC_funclist + ul.LC_funclist {
                   7107:     /* 
                   7108:        left border as a seperator if we have more than
                   7109:        one list 
                   7110:     */
                   7111:     border-left: 1px solid $sidebg;
                   7112:     /* 
                   7113:        this hides the left border behind the border of the 
                   7114:        outer box if element is wrapped to the next 'line' 
                   7115:     */
                   7116:     margin-left: -1px;
                   7117: }
                   7118: 
1.843     bisitz   7119: ul.LC_funclist li {
1.915     droeschl 7120:   display: inline;
1.782     bisitz   7121:   white-space: nowrap;
1.915     droeschl 7122:   margin: 0 0 0 25px;
                   7123:   line-height: 150%;
1.782     bisitz   7124: }
                   7125: 
1.974     wenzelju 7126: .LC_hidden {
                   7127:   display: none;
                   7128: }
                   7129: 
1.1030    www      7130: .LCmodal-overlay {
                   7131: 		position:fixed;
                   7132: 		top:0;
                   7133: 		right:0;
                   7134: 		bottom:0;
                   7135: 		left:0;
                   7136: 		height:100%;
                   7137: 		width:100%;
                   7138: 		margin:0;
                   7139: 		padding:0;
                   7140: 		background:#999;
                   7141: 		opacity:.75;
                   7142: 		filter: alpha(opacity=75);
                   7143: 		-moz-opacity: 0.75;
                   7144: 		z-index:101;
                   7145: }
                   7146: 
                   7147: * html .LCmodal-overlay {   
                   7148: 		position: absolute;
                   7149: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7150: }
                   7151: 
                   7152: .LCmodal-window {
                   7153: 		position:fixed;
                   7154: 		top:50%;
                   7155: 		left:50%;
                   7156: 		margin:0;
                   7157: 		padding:0;
                   7158: 		z-index:102;
                   7159: 	}
                   7160: 
                   7161: * html .LCmodal-window {
                   7162: 		position:absolute;
                   7163: }
                   7164: 
                   7165: .LCclose-window {
                   7166: 		position:absolute;
                   7167: 		width:32px;
                   7168: 		height:32px;
                   7169: 		right:8px;
                   7170: 		top:8px;
                   7171: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7172: 		text-indent:-99999px;
                   7173: 		overflow:hidden;
                   7174: 		cursor:pointer;
                   7175: }
                   7176: 
1.1075.2.17  raeburn  7177: /*
                   7178:   styles used by TTH when "Default set of options to pass to tth/m
                   7179:   when converting TeX" in course settings has been set
                   7180: 
                   7181:   option passed: -t
                   7182: 
                   7183: */
                   7184: 
                   7185: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7186: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7187: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7188: td div.norm {line-height:normal;}
                   7189: 
                   7190: /*
                   7191:   option passed -y3
                   7192: */
                   7193: 
                   7194: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7195: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7196: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7197: 
1.343     albertel 7198: END
                   7199: }
                   7200: 
1.306     albertel 7201: =pod
                   7202: 
                   7203: =item * &headtag()
                   7204: 
                   7205: Returns a uniform footer for LON-CAPA web pages.
                   7206: 
1.307     albertel 7207: Inputs: $title - optional title for the head
                   7208:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7209:         $args - optional arguments
1.319     albertel 7210:             force_register - if is true call registerurl so the remote is 
                   7211:                              informed
1.415     albertel 7212:             redirect       -> array ref of
                   7213:                                    1- seconds before redirect occurs
                   7214:                                    2- url to redirect to
                   7215:                                    3- whether the side effect should occur
1.315     albertel 7216:                            (side effect of setting 
                   7217:                                $env{'internal.head.redirect'} to the url 
                   7218:                                redirected too)
1.352     albertel 7219:             domain         -> force to color decorate a page for a specific
                   7220:                                domain
                   7221:             function       -> force usage of a specific rolish color scheme
                   7222:             bgcolor        -> override the default page bgcolor
1.460     albertel 7223:             no_auto_mt_title
                   7224:                            -> prevent &mt()ing the title arg
1.464     albertel 7225: 
1.306     albertel 7226: =cut
                   7227: 
                   7228: sub headtag {
1.313     albertel 7229:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7230:     
1.363     albertel 7231:     my $function = $args->{'function'} || &get_users_function();
                   7232:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7233:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 7234:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7235: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7236: 		   #time(),
1.418     albertel 7237: 		   $env{'environment.color.timestamp'},
1.363     albertel 7238: 		   $function,$domain,$bgcolor);
                   7239: 
1.369     www      7240:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7241: 
1.308     albertel 7242:     my $result =
                   7243: 	'<head>'.
1.461     albertel 7244: 	&font_settings();
1.319     albertel 7245: 
1.1064    raeburn  7246:     my $inhibitprint = &print_suppression();
                   7247: 
1.461     albertel 7248:     if (!$args->{'frameset'}) {
                   7249: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7250:     }
1.1075.2.12  raeburn  7251:     if ($args->{'force_register'}) {
                   7252:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7253:     }
1.436     albertel 7254:     if (!$args->{'no_nav_bar'} 
                   7255: 	&& !$args->{'only_body'}
                   7256: 	&& !$args->{'frameset'}) {
                   7257: 	$result .= &help_menu_js();
1.1032    www      7258:         $result.=&modal_window();
1.1038    www      7259:         $result.=&togglebox_script();
1.1034    www      7260:         $result.=&wishlist_window();
1.1041    www      7261:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7262:     } else {
                   7263:         if ($args->{'add_modal'}) {
                   7264:            $result.=&modal_window();
                   7265:         }
                   7266:         if ($args->{'add_wishlist'}) {
                   7267:            $result.=&wishlist_window();
                   7268:         }
1.1038    www      7269:         if ($args->{'add_togglebox'}) {
                   7270:            $result.=&togglebox_script();
                   7271:         }
1.1041    www      7272:         if ($args->{'add_progressbar'}) {
                   7273:            $result.=&LCprogressbarUpdate_script();
                   7274:         }
1.436     albertel 7275:     }
1.314     albertel 7276:     if (ref($args->{'redirect'})) {
1.414     albertel 7277: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7278: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7279: 	if (!$inhibit_continue) {
                   7280: 	    $env{'internal.head.redirect'} = $url;
                   7281: 	}
1.313     albertel 7282: 	$result.=<<ADDMETA
                   7283: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7284: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7285: ADDMETA
                   7286:     }
1.306     albertel 7287:     if (!defined($title)) {
                   7288: 	$title = 'The LearningOnline Network with CAPA';
                   7289:     }
1.460     albertel 7290:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7291:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7292: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7293:         .$inhibitprint
1.414     albertel 7294: 	.$head_extra;
1.962     droeschl 7295:     return $result.'</head>';
1.306     albertel 7296: }
                   7297: 
                   7298: =pod
                   7299: 
1.340     albertel 7300: =item * &font_settings()
                   7301: 
                   7302: Returns neccessary <meta> to set the proper encoding
                   7303: 
                   7304: Inputs: none
                   7305: 
                   7306: =cut
                   7307: 
                   7308: sub font_settings {
                   7309:     my $headerstring='';
1.647     www      7310:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 7311: 	$headerstring.=
                   7312: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   7313:     }
                   7314:     return $headerstring;
                   7315: }
                   7316: 
1.341     albertel 7317: =pod
                   7318: 
1.1064    raeburn  7319: =item * &print_suppression()
                   7320: 
                   7321: In course context returns css which causes the body to be blank when media="print",
                   7322: if printout generation is unavailable for the current resource.
                   7323: 
                   7324: This could be because:
                   7325: 
                   7326: (a) printstartdate is in the future
                   7327: 
                   7328: (b) printenddate is in the past
                   7329: 
                   7330: (c) there is an active exam block with "printout"
                   7331: functionality blocked
                   7332: 
                   7333: Users with pav, pfo or evb privileges are exempt.
                   7334: 
                   7335: Inputs: none
                   7336: 
                   7337: =cut
                   7338: 
                   7339: 
                   7340: sub print_suppression {
                   7341:     my $noprint;
                   7342:     if ($env{'request.course.id'}) {
                   7343:         my $scope = $env{'request.course.id'};
                   7344:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7345:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7346:             return;
                   7347:         }
                   7348:         if ($env{'request.course.sec'} ne '') {
                   7349:             $scope .= "/$env{'request.course.sec'}";
                   7350:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7351:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7352:                 return;
1.1064    raeburn  7353:             }
                   7354:         }
                   7355:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7356:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7357:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7358:         if ($blocked) {
                   7359:             my $checkrole = "cm./$cdom/$cnum";
                   7360:             if ($env{'request.course.sec'} ne '') {
                   7361:                 $checkrole .= "/$env{'request.course.sec'}";
                   7362:             }
                   7363:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7364:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7365:                 $noprint = 1;
                   7366:             }
                   7367:         }
                   7368:         unless ($noprint) {
                   7369:             my $symb = &Apache::lonnet::symbread();
                   7370:             if ($symb ne '') {
                   7371:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7372:                 if (ref($navmap)) {
                   7373:                     my $res = $navmap->getBySymb($symb);
                   7374:                     if (ref($res)) {
                   7375:                         if (!$res->resprintable()) {
                   7376:                             $noprint = 1;
                   7377:                         }
                   7378:                     }
                   7379:                 }
                   7380:             }
                   7381:         }
                   7382:         if ($noprint) {
                   7383:             return <<"ENDSTYLE";
                   7384: <style type="text/css" media="print">
                   7385:     body { display:none }
                   7386: </style>
                   7387: ENDSTYLE
                   7388:         }
                   7389:     }
                   7390:     return;
                   7391: }
                   7392: 
                   7393: =pod
                   7394: 
1.341     albertel 7395: =item * &xml_begin()
                   7396: 
                   7397: Returns the needed doctype and <html>
                   7398: 
                   7399: Inputs: none
                   7400: 
                   7401: =cut
                   7402: 
                   7403: sub xml_begin {
                   7404:     my $output='';
                   7405: 
                   7406:     if ($env{'browser.mathml'}) {
                   7407: 	$output='<?xml version="1.0"?>'
                   7408:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7409: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7410:             
                   7411: #	    .'<!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">] >'
                   7412: 	    .'<!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">'
                   7413:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7414: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7415:     } else {
1.849     bisitz   7416: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                   7417:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 7418:     }
                   7419:     return $output;
                   7420: }
1.340     albertel 7421: 
                   7422: =pod
                   7423: 
1.306     albertel 7424: =item * &start_page()
                   7425: 
                   7426: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7427: 
1.648     raeburn  7428: Inputs:
                   7429: 
                   7430: =over 4
                   7431: 
                   7432: $title - optional title for the page
                   7433: 
                   7434: $head_extra - optional extra HTML to incude inside the <head>
                   7435: 
                   7436: $args - additional optional args supported are:
                   7437: 
                   7438: =over 8
                   7439: 
                   7440:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7441:                                     arg on
1.814     bisitz   7442:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7443:              add_entries    -> additional attributes to add to the  <body>
                   7444:              domain         -> force to color decorate a page for a 
1.317     albertel 7445:                                     specific domain
1.648     raeburn  7446:              function       -> force usage of a specific rolish color
1.317     albertel 7447:                                     scheme
1.648     raeburn  7448:              redirect       -> see &headtag()
                   7449:              bgcolor        -> override the default page bg color
                   7450:              js_ready       -> return a string ready for being used in 
1.317     albertel 7451:                                     a javascript writeln
1.648     raeburn  7452:              html_encode    -> return a string ready for being used in 
1.320     albertel 7453:                                     a html attribute
1.648     raeburn  7454:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7455:                                     $forcereg arg
1.648     raeburn  7456:              frameset       -> if true will start with a <frameset>
1.330     albertel 7457:                                     rather than <body>
1.648     raeburn  7458:              skip_phases    -> hash ref of 
1.338     albertel 7459:                                     head -> skip the <html><head> generation
                   7460:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  7461:              no_inline_link -> if true and in remote mode, don't show the
                   7462:                                     'Switch To Inline Menu' link
1.648     raeburn  7463:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7464:              inherit_jsmath -> when creating popup window in a page,
                   7465:                                     should it have jsmath forced on by the
                   7466:                                     current page
1.867     kalberla 7467:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7468:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  7469:              group          -> includes the current group, if page is for a
                   7470:                                specific group
1.361     albertel 7471: 
1.648     raeburn  7472: =back
1.460     albertel 7473: 
1.648     raeburn  7474: =back
1.562     albertel 7475: 
1.306     albertel 7476: =cut
                   7477: 
                   7478: sub start_page {
1.309     albertel 7479:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7480:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7481: 
1.315     albertel 7482:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  7483:     my ($result,@advtools);
1.964     droeschl 7484: 
1.338     albertel 7485:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7486:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7487:     }
                   7488:     
                   7489:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7490: 	if ($args->{'frameset'}) {
                   7491: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7492: 						$args->{'add_entries'});
                   7493: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7494:         } else {
                   7495:             $result .=
                   7496:                 &bodytag($title, 
                   7497:                          $args->{'function'},       $args->{'add_entries'},
                   7498:                          $args->{'only_body'},      $args->{'domain'},
                   7499:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  7500:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  7501:                          $args,                     \@advtools);
1.831     bisitz   7502:         }
1.330     albertel 7503:     }
1.338     albertel 7504: 
1.315     albertel 7505:     if ($args->{'js_ready'}) {
1.713     kaisler  7506: 		$result = &js_ready($result);
1.315     albertel 7507:     }
1.320     albertel 7508:     if ($args->{'html_encode'}) {
1.713     kaisler  7509: 		$result = &html_encode($result);
                   7510:     }
                   7511: 
1.813     bisitz   7512:     # Preparation for new and consistent functionlist at top of screen
                   7513:     # if ($args->{'functionlist'}) {
                   7514:     #            $result .= &build_functionlist();
                   7515:     #}
                   7516: 
1.964     droeschl 7517:     # Don't add anything more if only_body wanted or in const space
                   7518:     return $result if    $args->{'only_body'} 
                   7519:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7520: 
                   7521:     #Breadcrumbs
1.758     kaisler  7522:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7523: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7524: 		#if any br links exists, add them to the breadcrumbs
                   7525: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7526: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7527: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7528: 			}
                   7529: 		}
1.1075.2.19  raeburn  7530:                 # if @advtools array contains items add then to the breadcrumbs
                   7531:                 if (@advtools > 0) {
                   7532:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7533:                 }
1.758     kaisler  7534: 
                   7535: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7536: 		if(exists($args->{'bread_crumbs_component'})){
                   7537: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7538: 		}else{
                   7539: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7540: 		}
1.1075.2.24  raeburn  7541:     } elsif (($env{'environment.remote'} eq 'on') &&
                   7542:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   7543:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   7544:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  7545:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 7546:     }
1.315     albertel 7547:     return $result;
1.306     albertel 7548: }
                   7549: 
                   7550: sub end_page {
1.315     albertel 7551:     my ($args) = @_;
                   7552:     $env{'internal.end_page'}++;
1.330     albertel 7553:     my $result;
1.335     albertel 7554:     if ($args->{'discussion'}) {
                   7555: 	my ($target,$parser);
                   7556: 	if (ref($args->{'discussion'})) {
                   7557: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7558: 				$args->{'discussion'}{'parser'});
                   7559: 	}
                   7560: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7561:     }
1.330     albertel 7562:     if ($args->{'frameset'}) {
                   7563: 	$result .= '</frameset>';
                   7564:     } else {
1.635     raeburn  7565: 	$result .= &endbodytag($args);
1.330     albertel 7566:     }
1.1075.2.6  raeburn  7567:     unless ($args->{'notbody'}) {
                   7568:         $result .= "\n</html>";
                   7569:     }
1.330     albertel 7570: 
1.315     albertel 7571:     if ($args->{'js_ready'}) {
1.317     albertel 7572: 	$result = &js_ready($result);
1.315     albertel 7573:     }
1.335     albertel 7574: 
1.320     albertel 7575:     if ($args->{'html_encode'}) {
                   7576: 	$result = &html_encode($result);
                   7577:     }
1.335     albertel 7578: 
1.315     albertel 7579:     return $result;
                   7580: }
                   7581: 
1.1034    www      7582: sub wishlist_window {
                   7583:     return(<<'ENDWISHLIST');
1.1046    raeburn  7584: <script type="text/javascript">
1.1034    www      7585: // <![CDATA[
                   7586: // <!-- BEGIN LON-CAPA Internal
                   7587: function set_wishlistlink(title, path) {
                   7588:     if (!title) {
                   7589:         title = document.title;
                   7590:         title = title.replace(/^LON-CAPA /,'');
                   7591:     }
                   7592:     if (!path) {
                   7593:         path = location.pathname;
                   7594:     }
                   7595:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7596:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7597: }
                   7598: // END LON-CAPA Internal -->
                   7599: // ]]>
                   7600: </script>
                   7601: ENDWISHLIST
                   7602: }
                   7603: 
1.1030    www      7604: sub modal_window {
                   7605:     return(<<'ENDMODAL');
1.1046    raeburn  7606: <script type="text/javascript">
1.1030    www      7607: // <![CDATA[
                   7608: // <!-- BEGIN LON-CAPA Internal
                   7609: var modalWindow = {
                   7610: 	parent:"body",
                   7611: 	windowId:null,
                   7612: 	content:null,
                   7613: 	width:null,
                   7614: 	height:null,
                   7615: 	close:function()
                   7616: 	{
                   7617: 	        $(".LCmodal-window").remove();
                   7618: 	        $(".LCmodal-overlay").remove();
                   7619: 	},
                   7620: 	open:function()
                   7621: 	{
                   7622: 		var modal = "";
                   7623: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7624: 		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;\">";
                   7625: 		modal += this.content;
                   7626: 		modal += "</div>";	
                   7627: 
                   7628: 		$(this.parent).append(modal);
                   7629: 
                   7630: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7631: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7632: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7633: 	}
                   7634: };
1.1031    www      7635: 	var openMyModal = function(source,width,height,scrolling)
1.1030    www      7636: 	{
                   7637: 		modalWindow.windowId = "myModal";
                   7638: 		modalWindow.width = width;
                   7639: 		modalWindow.height = height;
1.1031    www      7640: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
1.1030    www      7641: 		modalWindow.open();
                   7642: 	};	
                   7643: // END LON-CAPA Internal -->
                   7644: // ]]>
                   7645: </script>
                   7646: ENDMODAL
                   7647: }
                   7648: 
                   7649: sub modal_link {
1.1052    www      7650:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
1.1030    www      7651:     unless ($width) { $width=480; }
                   7652:     unless ($height) { $height=400; }
1.1031    www      7653:     unless ($scrolling) { $scrolling='yes'; }
1.1074    raeburn  7654:     my $target_attr;
                   7655:     if (defined($target)) {
                   7656:         $target_attr = 'target="'.$target.'"';
                   7657:     }
                   7658:     return <<"ENDLINK";
                   7659: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
                   7660:            $linktext</a>
                   7661: ENDLINK
1.1030    www      7662: }
                   7663: 
1.1032    www      7664: sub modal_adhoc_script {
                   7665:     my ($funcname,$width,$height,$content)=@_;
                   7666:     return (<<ENDADHOC);
1.1046    raeburn  7667: <script type="text/javascript">
1.1032    www      7668: // <![CDATA[
                   7669:         var $funcname = function()
                   7670:         {
                   7671:                 modalWindow.windowId = "myModal";
                   7672:                 modalWindow.width = $width;
                   7673:                 modalWindow.height = $height;
                   7674:                 modalWindow.content = '$content';
                   7675:                 modalWindow.open();
                   7676:         };  
                   7677: // ]]>
                   7678: </script>
                   7679: ENDADHOC
                   7680: }
                   7681: 
1.1041    www      7682: sub modal_adhoc_inner {
                   7683:     my ($funcname,$width,$height,$content)=@_;
                   7684:     my $innerwidth=$width-20;
                   7685:     $content=&js_ready(
1.1042    www      7686:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1041    www      7687:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
                   7688:                     $content.
                   7689:                  &end_scrollbox().
                   7690:                &end_page()
                   7691:              );
                   7692:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7693: }
                   7694: 
                   7695: sub modal_adhoc_window {
                   7696:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7697:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7698:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7699: }
                   7700: 
                   7701: sub modal_adhoc_launch {
                   7702:     my ($funcname,$width,$height,$content)=@_;
                   7703:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7704: <script type="text/javascript">
                   7705: // <![CDATA[
                   7706: $funcname();
                   7707: // ]]>
                   7708: </script>
                   7709: ENDLAUNCH
                   7710: }
                   7711: 
                   7712: sub modal_adhoc_close {
                   7713:     return (<<ENDCLOSE);
                   7714: <script type="text/javascript">
                   7715: // <![CDATA[
                   7716: modalWindow.close();
                   7717: // ]]>
                   7718: </script>
                   7719: ENDCLOSE
                   7720: }
                   7721: 
1.1038    www      7722: sub togglebox_script {
                   7723:    return(<<ENDTOGGLE);
                   7724: <script type="text/javascript"> 
                   7725: // <![CDATA[
                   7726: function LCtoggleDisplay(id,hidetext,showtext) {
                   7727:    link = document.getElementById(id + "link").childNodes[0];
                   7728:    with (document.getElementById(id).style) {
                   7729:       if (display == "none" ) {
                   7730:           display = "inline";
                   7731:           link.nodeValue = hidetext;
                   7732:         } else {
                   7733:           display = "none";
                   7734:           link.nodeValue = showtext;
                   7735:        }
                   7736:    }
                   7737: }
                   7738: // ]]>
                   7739: </script>
                   7740: ENDTOGGLE
                   7741: }
                   7742: 
1.1039    www      7743: sub start_togglebox {
                   7744:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7745:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7746:     unless ($showtext) { $showtext=&mt('show'); }
                   7747:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7748:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7749:     return &start_data_table().
                   7750:            &start_data_table_header_row().
                   7751:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7752:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7753:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7754:            &end_data_table_header_row().
                   7755:            '<tr id="'.$id.'" style="display:none""><td>';
                   7756: }
                   7757: 
                   7758: sub end_togglebox {
                   7759:     return '</td></tr>'.&end_data_table();
                   7760: }
                   7761: 
1.1041    www      7762: sub LCprogressbar_script {
1.1045    www      7763:    my ($id)=@_;
1.1041    www      7764:    return(<<ENDPROGRESS);
                   7765: <script type="text/javascript">
                   7766: // <![CDATA[
1.1045    www      7767: \$('#progressbar$id').progressbar({
1.1041    www      7768:   value: 0,
                   7769:   change: function(event, ui) {
                   7770:     var newVal = \$(this).progressbar('option', 'value');
                   7771:     \$('.pblabel', this).text(LCprogressTxt);
                   7772:   }
                   7773: });
                   7774: // ]]>
                   7775: </script>
                   7776: ENDPROGRESS
                   7777: }
                   7778: 
                   7779: sub LCprogressbarUpdate_script {
                   7780:    return(<<ENDPROGRESSUPDATE);
                   7781: <style type="text/css">
                   7782: .ui-progressbar { position:relative; }
                   7783: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7784: </style>
                   7785: <script type="text/javascript">
                   7786: // <![CDATA[
1.1045    www      7787: var LCprogressTxt='---';
                   7788: 
                   7789: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7790:    LCprogressTxt=progresstext;
1.1045    www      7791:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7792: }
                   7793: // ]]>
                   7794: </script>
                   7795: ENDPROGRESSUPDATE
                   7796: }
                   7797: 
1.1042    www      7798: my $LClastpercent;
1.1045    www      7799: my $LCidcnt;
                   7800: my $LCcurrentid;
1.1042    www      7801: 
1.1041    www      7802: sub LCprogressbar {
1.1042    www      7803:     my ($r)=(@_);
                   7804:     $LClastpercent=0;
1.1045    www      7805:     $LCidcnt++;
                   7806:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7807:     my $starting=&mt('Starting');
                   7808:     my $content=(<<ENDPROGBAR);
1.1045    www      7809:   <div id="progressbar$LCcurrentid">
1.1041    www      7810:     <span class="pblabel">$starting</span>
                   7811:   </div>
                   7812: ENDPROGBAR
1.1045    www      7813:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7814: }
                   7815: 
                   7816: sub LCprogressbarUpdate {
1.1042    www      7817:     my ($r,$val,$text)=@_;
                   7818:     unless ($val) { 
                   7819:        if ($LClastpercent) {
                   7820:            $val=$LClastpercent;
                   7821:        } else {
                   7822:            $val=0;
                   7823:        }
                   7824:     }
1.1041    www      7825:     if ($val<0) { $val=0; }
                   7826:     if ($val>100) { $val=0; }
1.1042    www      7827:     $LClastpercent=$val;
1.1041    www      7828:     unless ($text) { $text=$val.'%'; }
                   7829:     $text=&js_ready($text);
1.1044    www      7830:     &r_print($r,<<ENDUPDATE);
1.1041    www      7831: <script type="text/javascript">
                   7832: // <![CDATA[
1.1045    www      7833: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7834: // ]]>
                   7835: </script>
                   7836: ENDUPDATE
1.1035    www      7837: }
                   7838: 
1.1042    www      7839: sub LCprogressbarClose {
                   7840:     my ($r)=@_;
                   7841:     $LClastpercent=0;
1.1044    www      7842:     &r_print($r,<<ENDCLOSE);
1.1042    www      7843: <script type="text/javascript">
                   7844: // <![CDATA[
1.1045    www      7845: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7846: // ]]>
                   7847: </script>
                   7848: ENDCLOSE
1.1044    www      7849: }
                   7850: 
                   7851: sub r_print {
                   7852:     my ($r,$to_print)=@_;
                   7853:     if ($r) {
                   7854:       $r->print($to_print);
                   7855:       $r->rflush();
                   7856:     } else {
                   7857:       print($to_print);
                   7858:     }
1.1042    www      7859: }
                   7860: 
1.320     albertel 7861: sub html_encode {
                   7862:     my ($result) = @_;
                   7863: 
1.322     albertel 7864:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7865:     
                   7866:     return $result;
                   7867: }
1.1044    www      7868: 
1.317     albertel 7869: sub js_ready {
                   7870:     my ($result) = @_;
                   7871: 
1.323     albertel 7872:     $result =~ s/[\n\r]/ /xmsg;
                   7873:     $result =~ s/\\/\\\\/xmsg;
                   7874:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7875:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7876:     
                   7877:     return $result;
                   7878: }
                   7879: 
1.315     albertel 7880: sub validate_page {
                   7881:     if (  exists($env{'internal.start_page'})
1.316     albertel 7882: 	  &&     $env{'internal.start_page'} > 1) {
                   7883: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7884: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7885: 				 $ENV{'request.filename'});
1.315     albertel 7886:     }
                   7887:     if (  exists($env{'internal.end_page'})
1.316     albertel 7888: 	  &&     $env{'internal.end_page'} > 1) {
                   7889: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7890: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7891: 				 $env{'request.filename'});
1.315     albertel 7892:     }
                   7893:     if (     exists($env{'internal.start_page'})
                   7894: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7895: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7896: 				 $env{'request.filename'});
1.315     albertel 7897:     }
                   7898:     if (   ! exists($env{'internal.start_page'})
                   7899: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7900: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7901: 				 $env{'request.filename'});
1.315     albertel 7902:     }
1.306     albertel 7903: }
1.315     albertel 7904: 
1.996     www      7905: 
                   7906: sub start_scrollbox {
1.1075    raeburn  7907:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
1.998     raeburn  7908:     unless ($outerwidth) { $outerwidth='520px'; }
                   7909:     unless ($width) { $width='500px'; }
                   7910:     unless ($height) { $height='200px'; }
1.1075    raeburn  7911:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7912:     if ($id ne '') {
1.1020    raeburn  7913:         $table_id = " id='table_$id'";
                   7914:         $div_id = " id='div_$id'";
1.1018    raeburn  7915:     }
1.1075    raeburn  7916:     if ($bgcolor ne '') {
                   7917:         $tdcol = "background-color: $bgcolor;";
                   7918:     }
                   7919:     return <<"END";
                   7920: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
                   7921: END
1.996     www      7922: }
                   7923: 
                   7924: sub end_scrollbox {
1.1036    www      7925:     return '</div></td></tr></table>';
1.996     www      7926: }
                   7927: 
1.318     albertel 7928: sub simple_error_page {
                   7929:     my ($r,$title,$msg) = @_;
                   7930:     my $page =
                   7931: 	&Apache::loncommon::start_page($title).
1.1075.2.15  raeburn  7932: 	'<p class="LC_error">'.&mt($msg).'</p>'.
1.318     albertel 7933: 	&Apache::loncommon::end_page();
                   7934:     if (ref($r)) {
                   7935: 	$r->print($page);
1.327     albertel 7936: 	return;
1.318     albertel 7937:     }
                   7938:     return $page;
                   7939: }
1.347     albertel 7940: 
                   7941: {
1.610     albertel 7942:     my @row_count;
1.961     onken    7943: 
                   7944:     sub start_data_table_count {
                   7945:         unshift(@row_count, 0);
                   7946:         return;
                   7947:     }
                   7948: 
                   7949:     sub end_data_table_count {
                   7950:         shift(@row_count);
                   7951:         return;
                   7952:     }
                   7953: 
1.347     albertel 7954:     sub start_data_table {
1.1018    raeburn  7955: 	my ($add_class,$id) = @_;
1.422     albertel 7956: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  7957:         my $table_id;
                   7958:         if (defined($id)) {
                   7959:             $table_id = ' id="'.$id.'"';
                   7960:         }
1.961     onken    7961: 	&start_data_table_count();
1.1018    raeburn  7962: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 7963:     }
                   7964: 
                   7965:     sub end_data_table {
1.961     onken    7966: 	&end_data_table_count();
1.389     albertel 7967: 	return '</table>'."\n";;
1.347     albertel 7968:     }
                   7969: 
                   7970:     sub start_data_table_row {
1.974     wenzelju 7971: 	my ($add_class, $id) = @_;
1.610     albertel 7972: 	$row_count[0]++;
                   7973: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   7974: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 7975:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7976:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 7977:     }
1.471     banghart 7978:     
                   7979:     sub continue_data_table_row {
1.974     wenzelju 7980: 	my ($add_class, $id) = @_;
1.610     albertel 7981: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 7982: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   7983:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7984:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 7985:     }
1.347     albertel 7986: 
                   7987:     sub end_data_table_row {
1.389     albertel 7988: 	return '</tr>'."\n";;
1.347     albertel 7989:     }
1.367     www      7990: 
1.421     albertel 7991:     sub start_data_table_empty_row {
1.707     bisitz   7992: #	$row_count[0]++;
1.421     albertel 7993: 	return  '<tr class="LC_empty_row" >'."\n";;
                   7994:     }
                   7995: 
                   7996:     sub end_data_table_empty_row {
                   7997: 	return '</tr>'."\n";;
                   7998:     }
                   7999: 
1.367     www      8000:     sub start_data_table_header_row {
1.389     albertel 8001: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8002:     }
                   8003: 
                   8004:     sub end_data_table_header_row {
1.389     albertel 8005: 	return '</tr>'."\n";;
1.367     www      8006:     }
1.890     droeschl 8007: 
                   8008:     sub data_table_caption {
                   8009:         my $caption = shift;
                   8010:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8011:     }
1.347     albertel 8012: }
                   8013: 
1.548     albertel 8014: =pod
                   8015: 
                   8016: =item * &inhibit_menu_check($arg)
                   8017: 
                   8018: Checks for a inhibitmenu state and generates output to preserve it
                   8019: 
                   8020: Inputs:         $arg - can be any of
                   8021:                      - undef - in which case the return value is a string 
                   8022:                                to add  into arguments list of a uri
                   8023:                      - 'input' - in which case the return value is a HTML
                   8024:                                  <form> <input> field of type hidden to
                   8025:                                  preserve the value
                   8026:                      - a url - in which case the return value is the url with
                   8027:                                the neccesary cgi args added to preserve the
                   8028:                                inhibitmenu state
                   8029:                      - a ref to a url - no return value, but the string is
                   8030:                                         updated to include the neccessary cgi
                   8031:                                         args to preserve the inhibitmenu state
                   8032: 
                   8033: =cut
                   8034: 
                   8035: sub inhibit_menu_check {
                   8036:     my ($arg) = @_;
                   8037:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8038:     if ($arg eq 'input') {
                   8039: 	if ($env{'form.inhibitmenu'}) {
                   8040: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8041: 	} else {
                   8042: 	    return
                   8043: 	}
                   8044:     }
                   8045:     if ($env{'form.inhibitmenu'}) {
                   8046: 	if (ref($arg)) {
                   8047: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8048: 	} elsif ($arg eq '') {
                   8049: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8050: 	} else {
                   8051: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8052: 	}
                   8053:     }
                   8054:     if (!ref($arg)) {
                   8055: 	return $arg;
                   8056:     }
                   8057: }
                   8058: 
1.251     albertel 8059: ###############################################
1.182     matthew  8060: 
                   8061: =pod
                   8062: 
1.549     albertel 8063: =back
                   8064: 
                   8065: =head1 User Information Routines
                   8066: 
                   8067: =over 4
                   8068: 
1.405     albertel 8069: =item * &get_users_function()
1.182     matthew  8070: 
                   8071: Used by &bodytag to determine the current users primary role.
                   8072: Returns either 'student','coordinator','admin', or 'author'.
                   8073: 
                   8074: =cut
                   8075: 
                   8076: ###############################################
                   8077: sub get_users_function {
1.815     tempelho 8078:     my $function = 'norole';
1.818     tempelho 8079:     if ($env{'request.role'}=~/^(st)/) {
                   8080:         $function='student';
                   8081:     }
1.907     raeburn  8082:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8083:         $function='coordinator';
                   8084:     }
1.258     albertel 8085:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8086:         $function='admin';
                   8087:     }
1.826     bisitz   8088:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8089:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8090:         $function='author';
                   8091:     }
                   8092:     return $function;
1.54      www      8093: }
1.99      www      8094: 
                   8095: ###############################################
                   8096: 
1.233     raeburn  8097: =pod
                   8098: 
1.821     raeburn  8099: =item * &show_course()
                   8100: 
                   8101: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8102: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8103: 
                   8104: Inputs:
                   8105: None
                   8106: 
                   8107: Outputs:
                   8108: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8109: 
                   8110: =cut
                   8111: 
                   8112: ###############################################
                   8113: sub show_course {
                   8114:     my $course = !$env{'user.adv'};
                   8115:     if (!$env{'user.adv'}) {
                   8116:         foreach my $env (keys(%env)) {
                   8117:             next if ($env !~ m/^user\.priv\./);
                   8118:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8119:                 $course = 0;
                   8120:                 last;
                   8121:             }
                   8122:         }
                   8123:     }
                   8124:     return $course;
                   8125: }
                   8126: 
                   8127: ###############################################
                   8128: 
                   8129: =pod
                   8130: 
1.542     raeburn  8131: =item * &check_user_status()
1.274     raeburn  8132: 
                   8133: Determines current status of supplied role for a
                   8134: specific user. Roles can be active, previous or future.
                   8135: 
                   8136: Inputs: 
                   8137: user's domain, user's username, course's domain,
1.375     raeburn  8138: course's number, optional section ID.
1.274     raeburn  8139: 
                   8140: Outputs:
                   8141: role status: active, previous or future. 
                   8142: 
                   8143: =cut
                   8144: 
                   8145: sub check_user_status {
1.412     raeburn  8146:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8147:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8148:     my @uroles = keys %userinfo;
                   8149:     my $srchstr;
                   8150:     my $active_chk = 'none';
1.412     raeburn  8151:     my $now = time;
1.274     raeburn  8152:     if (@uroles > 0) {
1.908     raeburn  8153:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8154:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8155:         } else {
1.412     raeburn  8156:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8157:         }
                   8158:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8159:             my $role_end = 0;
                   8160:             my $role_start = 0;
                   8161:             $active_chk = 'active';
1.412     raeburn  8162:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8163:                 $role_end = $1;
                   8164:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8165:                     $role_start = $1;
1.274     raeburn  8166:                 }
                   8167:             }
                   8168:             if ($role_start > 0) {
1.412     raeburn  8169:                 if ($now < $role_start) {
1.274     raeburn  8170:                     $active_chk = 'future';
                   8171:                 }
                   8172:             }
                   8173:             if ($role_end > 0) {
1.412     raeburn  8174:                 if ($now > $role_end) {
1.274     raeburn  8175:                     $active_chk = 'previous';
                   8176:                 }
                   8177:             }
                   8178:         }
                   8179:     }
                   8180:     return $active_chk;
                   8181: }
                   8182: 
                   8183: ###############################################
                   8184: 
                   8185: =pod
                   8186: 
1.405     albertel 8187: =item * &get_sections()
1.233     raeburn  8188: 
                   8189: Determines all the sections for a course including
                   8190: sections with students and sections containing other roles.
1.419     raeburn  8191: Incoming parameters: 
                   8192: 
                   8193: 1. domain
                   8194: 2. course number 
                   8195: 3. reference to array containing roles for which sections should 
                   8196: be gathered (optional).
                   8197: 4. reference to array containing status types for which sections 
                   8198: should be gathered (optional).
                   8199: 
                   8200: If the third argument is undefined, sections are gathered for any role. 
                   8201: If the fourth argument is undefined, sections are gathered for any status.
                   8202: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8203:  
1.374     raeburn  8204: Returns section hash (keys are section IDs, values are
                   8205: number of users in each section), subject to the
1.419     raeburn  8206: optional roles filter, optional status filter 
1.233     raeburn  8207: 
                   8208: =cut
                   8209: 
                   8210: ###############################################
                   8211: sub get_sections {
1.419     raeburn  8212:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8213:     if (!defined($cdom) || !defined($cnum)) {
                   8214:         my $cid =  $env{'request.course.id'};
                   8215: 
                   8216: 	return if (!defined($cid));
                   8217: 
                   8218:         $cdom = $env{'course.'.$cid.'.domain'};
                   8219:         $cnum = $env{'course.'.$cid.'.num'};
                   8220:     }
                   8221: 
                   8222:     my %sectioncount;
1.419     raeburn  8223:     my $now = time;
1.240     albertel 8224: 
1.1075.2.33  raeburn  8225:     my $check_students = 1;
                   8226:     my $only_students = 0;
                   8227:     if (ref($possible_roles) eq 'ARRAY') {
                   8228:         if (grep(/^st$/,@{$possible_roles})) {
                   8229:             if (@{$possible_roles} == 1) {
                   8230:                 $only_students = 1;
                   8231:             }
                   8232:         } else {
                   8233:             $check_students = 0;
                   8234:         }
                   8235:     }
                   8236: 
                   8237:     if ($check_students) {
1.276     albertel 8238: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8239: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8240: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8241:         my $start_index = &Apache::loncoursedata::CL_START();
                   8242:         my $end_index = &Apache::loncoursedata::CL_END();
                   8243:         my $status;
1.366     albertel 8244: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8245: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8246: 				                     $data->[$status_index],
                   8247:                                                      $data->[$start_index],
                   8248:                                                      $data->[$end_index]);
                   8249:             if ($stu_status eq 'Active') {
                   8250:                 $status = 'active';
                   8251:             } elsif ($end < $now) {
                   8252:                 $status = 'previous';
                   8253:             } elsif ($start > $now) {
                   8254:                 $status = 'future';
                   8255:             } 
                   8256: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8257:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8258:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8259: 		    $sectioncount{$section}++;
                   8260:                 }
1.240     albertel 8261: 	    }
                   8262: 	}
                   8263:     }
1.1075.2.33  raeburn  8264:     if ($only_students) {
                   8265:         return %sectioncount;
                   8266:     }
1.240     albertel 8267:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8268:     foreach my $user (sort(keys(%courseroles))) {
                   8269: 	if ($user !~ /^(\w{2})/) { next; }
                   8270: 	my ($role) = ($user =~ /^(\w{2})/);
                   8271: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8272: 	my ($section,$status);
1.240     albertel 8273: 	if ($role eq 'cr' &&
                   8274: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8275: 	    $section=$1;
                   8276: 	}
                   8277: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8278: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8279:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8280:         if ($end == -1 && $start == -1) {
                   8281:             next; #deleted role
                   8282:         }
                   8283:         if (!defined($possible_status)) { 
                   8284:             $sectioncount{$section}++;
                   8285:         } else {
                   8286:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8287:                 $status = 'active';
                   8288:             } elsif ($end < $now) {
                   8289:                 $status = 'future';
                   8290:             } elsif ($start > $now) {
                   8291:                 $status = 'previous';
                   8292:             }
                   8293:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8294:                 $sectioncount{$section}++;
                   8295:             }
                   8296:         }
1.233     raeburn  8297:     }
1.366     albertel 8298:     return %sectioncount;
1.233     raeburn  8299: }
                   8300: 
1.274     raeburn  8301: ###############################################
1.294     raeburn  8302: 
                   8303: =pod
1.405     albertel 8304: 
                   8305: =item * &get_course_users()
                   8306: 
1.275     raeburn  8307: Retrieves usernames:domains for users in the specified course
                   8308: with specific role(s), and access status. 
                   8309: 
                   8310: Incoming parameters:
1.277     albertel 8311: 1. course domain
                   8312: 2. course number
                   8313: 3. access status: users must have - either active, 
1.275     raeburn  8314: previous, future, or all.
1.277     albertel 8315: 4. reference to array of permissible roles
1.288     raeburn  8316: 5. reference to array of section restrictions (optional)
                   8317: 6. reference to results object (hash of hashes).
                   8318: 7. reference to optional userdata hash
1.609     raeburn  8319: 8. reference to optional statushash
1.630     raeburn  8320: 9. flag if privileged users (except those set to unhide in
                   8321:    course settings) should be excluded    
1.609     raeburn  8322: Keys of top level results hash are roles.
1.275     raeburn  8323: Keys of inner hashes are username:domain, with 
                   8324: values set to access type.
1.288     raeburn  8325: Optional userdata hash returns an array with arguments in the 
                   8326: same order as loncoursedata::get_classlist() for student data.
                   8327: 
1.609     raeburn  8328: Optional statushash returns
                   8329: 
1.288     raeburn  8330: Entries for end, start, section and status are blank because
                   8331: of the possibility of multiple values for non-student roles.
                   8332: 
1.275     raeburn  8333: =cut
1.405     albertel 8334: 
1.275     raeburn  8335: ###############################################
1.405     albertel 8336: 
1.275     raeburn  8337: sub get_course_users {
1.630     raeburn  8338:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8339:     my %idx = ();
1.419     raeburn  8340:     my %seclists;
1.288     raeburn  8341: 
                   8342:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8343:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8344:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8345:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8346:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8347:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8348:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8349:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8350: 
1.290     albertel 8351:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8352:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8353:         my $now = time;
1.277     albertel 8354:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8355:             my $match = 0;
1.412     raeburn  8356:             my $secmatch = 0;
1.419     raeburn  8357:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8358:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8359:             if ($section eq '') {
                   8360:                 $section = 'none';
                   8361:             }
1.291     albertel 8362:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8363:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8364:                     $secmatch = 1;
                   8365:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8366:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8367:                         $secmatch = 1;
                   8368:                     }
                   8369:                 } else {  
1.419     raeburn  8370: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8371: 		        $secmatch = 1;
                   8372:                     }
1.290     albertel 8373: 		}
1.412     raeburn  8374:                 if (!$secmatch) {
                   8375:                     next;
                   8376:                 }
1.419     raeburn  8377:             }
1.275     raeburn  8378:             if (defined($$types{'active'})) {
1.288     raeburn  8379:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8380:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8381:                     $match = 1;
1.275     raeburn  8382:                 }
                   8383:             }
                   8384:             if (defined($$types{'previous'})) {
1.609     raeburn  8385:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8386:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8387:                     $match = 1;
1.275     raeburn  8388:                 }
                   8389:             }
                   8390:             if (defined($$types{'future'})) {
1.609     raeburn  8391:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8392:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8393:                     $match = 1;
1.275     raeburn  8394:                 }
                   8395:             }
1.609     raeburn  8396:             if ($match) {
                   8397:                 push(@{$seclists{$student}},$section);
                   8398:                 if (ref($userdata) eq 'HASH') {
                   8399:                     $$userdata{$student} = $$classlist{$student};
                   8400:                 }
                   8401:                 if (ref($statushash) eq 'HASH') {
                   8402:                     $statushash->{$student}{'st'}{$section} = $status;
                   8403:                 }
1.288     raeburn  8404:             }
1.275     raeburn  8405:         }
                   8406:     }
1.412     raeburn  8407:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8408:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8409:         my $now = time;
1.609     raeburn  8410:         my %displaystatus = ( previous => 'Expired',
                   8411:                               active   => 'Active',
                   8412:                               future   => 'Future',
                   8413:                             );
1.1075.2.36  raeburn  8414:         my (%nothide,@possdoms);
1.630     raeburn  8415:         if ($hidepriv) {
                   8416:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8417:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8418:                 if ($user !~ /:/) {
                   8419:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8420:                 } else {
                   8421:                     $nothide{$user} = 1;
                   8422:                 }
                   8423:             }
1.1075.2.36  raeburn  8424:             my @possdoms = ($cdom);
                   8425:             if ($coursehash{'checkforpriv'}) {
                   8426:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8427:             }
1.630     raeburn  8428:         }
1.439     raeburn  8429:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8430:             my $match = 0;
1.412     raeburn  8431:             my $secmatch = 0;
1.439     raeburn  8432:             my $status;
1.412     raeburn  8433:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8434:             $user =~ s/:$//;
1.439     raeburn  8435:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8436:             if ($end == -1 || $start == -1) {
                   8437:                 next;
                   8438:             }
                   8439:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8440:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8441:                 my ($uname,$udom) = split(/:/,$user);
                   8442:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8443:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8444:                         $secmatch = 1;
                   8445:                     } elsif ($usec eq '') {
1.420     albertel 8446:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8447:                             $secmatch = 1;
                   8448:                         }
                   8449:                     } else {
                   8450:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8451:                             $secmatch = 1;
                   8452:                         }
                   8453:                     }
                   8454:                     if (!$secmatch) {
                   8455:                         next;
                   8456:                     }
1.288     raeburn  8457:                 }
1.419     raeburn  8458:                 if ($usec eq '') {
                   8459:                     $usec = 'none';
                   8460:                 }
1.275     raeburn  8461:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8462:                     if ($hidepriv) {
1.1075.2.36  raeburn  8463:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8464:                             (!$nothide{$uname.':'.$udom})) {
                   8465:                             next;
                   8466:                         }
                   8467:                     }
1.503     raeburn  8468:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8469:                         $status = 'previous';
                   8470:                     } elsif ($start > $now) {
                   8471:                         $status = 'future';
                   8472:                     } else {
                   8473:                         $status = 'active';
                   8474:                     }
1.277     albertel 8475:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8476:                         if ($status eq $type) {
1.420     albertel 8477:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8478:                                 push(@{$$users{$role}{$user}},$type);
                   8479:                             }
1.288     raeburn  8480:                             $match = 1;
                   8481:                         }
                   8482:                     }
1.419     raeburn  8483:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8484:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8485: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8486:                         }
1.420     albertel 8487:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8488:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8489:                         }
1.609     raeburn  8490:                         if (ref($statushash) eq 'HASH') {
                   8491:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8492:                         }
1.275     raeburn  8493:                     }
                   8494:                 }
                   8495:             }
                   8496:         }
1.290     albertel 8497:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8498:             if ((defined($cdom)) && (defined($cnum))) {
                   8499:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8500:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8501:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8502:                     next if ($owner eq '');
                   8503:                     my ($ownername,$ownerdom);
                   8504:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8505:                         $ownername = $1;
                   8506:                         $ownerdom = $2;
                   8507:                     } else {
                   8508:                         $ownername = $owner;
                   8509:                         $ownerdom = $cdom;
                   8510:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8511:                     }
                   8512:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8513:                     if (defined($userdata) && 
1.609     raeburn  8514: 			!exists($$userdata{$owner})) {
                   8515: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8516:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8517:                             push(@{$seclists{$owner}},'none');
                   8518:                         }
                   8519:                         if (ref($statushash) eq 'HASH') {
                   8520:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8521:                         }
1.290     albertel 8522: 		    }
1.279     raeburn  8523:                 }
                   8524:             }
                   8525:         }
1.419     raeburn  8526:         foreach my $user (keys(%seclists)) {
                   8527:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8528:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8529:         }
1.275     raeburn  8530:     }
                   8531:     return;
                   8532: }
                   8533: 
1.288     raeburn  8534: sub get_user_info {
                   8535:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8536:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8537: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8538:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8539:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8540:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8541:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8542:     return;
                   8543: }
1.275     raeburn  8544: 
1.472     raeburn  8545: ###############################################
                   8546: 
                   8547: =pod
                   8548: 
                   8549: =item * &get_user_quota()
                   8550: 
                   8551: Retrieves quota assigned for storage of portfolio files for a user  
                   8552: 
                   8553: Incoming parameters:
                   8554: 1. user's username
                   8555: 2. user's domain
                   8556: 
                   8557: Returns:
1.536     raeburn  8558: 1. Disk quota (in Mb) assigned to student.
                   8559: 2. (Optional) Type of setting: custom or default
                   8560:    (individually assigned or default for user's 
                   8561:    institutional status).
                   8562: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8563:    or student - types as defined in localenroll::inst_usertypes 
                   8564:    for user's domain, which determines default quota for user.
                   8565: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8566: 
                   8567: If a value has been stored in the user's environment, 
1.536     raeburn  8568: it will return that, otherwise it returns the maximal default
                   8569: defined for the user's instituional status(es) in the domain.
1.472     raeburn  8570: 
                   8571: =cut
                   8572: 
                   8573: ###############################################
                   8574: 
                   8575: 
                   8576: sub get_user_quota {
                   8577:     my ($uname,$udom) = @_;
1.536     raeburn  8578:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8579:     if (!defined($udom)) {
                   8580:         $udom = $env{'user.domain'};
                   8581:     }
                   8582:     if (!defined($uname)) {
                   8583:         $uname = $env{'user.name'};
                   8584:     }
                   8585:     if (($udom eq '' || $uname eq '') ||
                   8586:         ($udom eq 'public') && ($uname eq 'public')) {
                   8587:         $quota = 0;
1.536     raeburn  8588:         $quotatype = 'default';
                   8589:         $defquota = 0; 
1.472     raeburn  8590:     } else {
1.536     raeburn  8591:         my $inststatus;
1.472     raeburn  8592:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8593:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  8594:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  8595:         } else {
1.536     raeburn  8596:             my %userenv = 
                   8597:                 &Apache::lonnet::get('environment',['portfolioquota',
                   8598:                                      'inststatus'],$udom,$uname);
1.472     raeburn  8599:             my ($tmp) = keys(%userenv);
                   8600:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8601:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  8602:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  8603:             } else {
                   8604:                 undef(%userenv);
                   8605:             }
                   8606:         }
1.536     raeburn  8607:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  8608:         if ($quota eq '') {
1.536     raeburn  8609:             $quota = $defquota;
                   8610:             $quotatype = 'default';
                   8611:         } else {
                   8612:             $quotatype = 'custom';
1.472     raeburn  8613:         }
                   8614:     }
1.536     raeburn  8615:     if (wantarray) {
                   8616:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8617:     } else {
                   8618:         return $quota;
                   8619:     }
1.472     raeburn  8620: }
                   8621: 
                   8622: ###############################################
                   8623: 
                   8624: =pod
                   8625: 
                   8626: =item * &default_quota()
                   8627: 
1.536     raeburn  8628: Retrieves default quota assigned for storage of user portfolio files,
                   8629: given an (optional) user's institutional status.
1.472     raeburn  8630: 
                   8631: Incoming parameters:
                   8632: 1. domain
1.536     raeburn  8633: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8634:    status types (e.g., faculty, staff, student etc.)
                   8635:    which apply to the user for whom the default is being retrieved.
                   8636:    If the institutional status string in undefined, the domain
                   8637:    default quota will be returned. 
1.472     raeburn  8638: 
                   8639: Returns:
                   8640: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  8641: 2. (Optional) institutional type which determined the value of the
                   8642:    default quota.
1.472     raeburn  8643: 
                   8644: If a value has been stored in the domain's configuration db,
                   8645: it will return that, otherwise it returns 20 (for backwards 
                   8646: compatibility with domains which have not set up a configuration
                   8647: db file; the original statically defined portfolio quota was 20 Mb). 
                   8648: 
1.536     raeburn  8649: If the user's status includes multiple types (e.g., staff and student),
                   8650: the largest default quota which applies to the user determines the
                   8651: default quota returned.
                   8652: 
1.780     raeburn  8653: =back
                   8654: 
1.472     raeburn  8655: =cut
                   8656: 
                   8657: ###############################################
                   8658: 
                   8659: 
                   8660: sub default_quota {
1.536     raeburn  8661:     my ($udom,$inststatus) = @_;
                   8662:     my ($defquota,$settingstatus);
                   8663:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8664:                                             ['quotas'],$udom);
                   8665:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8666:         if ($inststatus ne '') {
1.765     raeburn  8667:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8668:             foreach my $item (@statuses) {
1.711     raeburn  8669:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8670:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
                   8671:                         if ($defquota eq '') {
                   8672:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8673:                             $settingstatus = $item;
                   8674:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
                   8675:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8676:                             $settingstatus = $item;
                   8677:                         }
                   8678:                     }
                   8679:                 } else {
                   8680:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8681:                         if ($defquota eq '') {
                   8682:                             $defquota = $quotahash{'quotas'}{$item};
                   8683:                             $settingstatus = $item;
                   8684:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8685:                             $defquota = $quotahash{'quotas'}{$item};
                   8686:                             $settingstatus = $item;
                   8687:                         }
1.536     raeburn  8688:                     }
                   8689:                 }
                   8690:             }
                   8691:         }
                   8692:         if ($defquota eq '') {
1.711     raeburn  8693:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8694:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
                   8695:             } else {
                   8696:                 $defquota = $quotahash{'quotas'}{'default'};
                   8697:             }
1.536     raeburn  8698:             $settingstatus = 'default';
                   8699:         }
                   8700:     } else {
                   8701:         $settingstatus = 'default';
                   8702:         $defquota = 20;
                   8703:     }
                   8704:     if (wantarray) {
                   8705:         return ($defquota,$settingstatus);
1.472     raeburn  8706:     } else {
1.536     raeburn  8707:         return $defquota;
1.472     raeburn  8708:     }
                   8709: }
                   8710: 
1.384     raeburn  8711: sub get_secgrprole_info {
                   8712:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8713:     my %sections_count = &get_sections($cdom,$cnum);
                   8714:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8715:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8716:     my @groups = sort(keys(%curr_groups));
                   8717:     my $allroles = [];
                   8718:     my $rolehash;
                   8719:     my $accesshash = {
                   8720:                      active => 'Currently has access',
                   8721:                      future => 'Will have future access',
                   8722:                      previous => 'Previously had access',
                   8723:                   };
                   8724:     if ($needroles) {
                   8725:         $rolehash = {'all' => 'all'};
1.385     albertel 8726:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8727: 	if (&Apache::lonnet::error(%user_roles)) {
                   8728: 	    undef(%user_roles);
                   8729: 	}
                   8730:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8731:             my ($role)=split(/\:/,$item,2);
                   8732:             if ($role eq 'cr') { next; }
                   8733:             if ($role =~ /^cr/) {
                   8734:                 $$rolehash{$role} = (split('/',$role))[3];
                   8735:             } else {
                   8736:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8737:             }
                   8738:         }
                   8739:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8740:             push(@{$allroles},$key);
                   8741:         }
                   8742:         push (@{$allroles},'st');
                   8743:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8744:     }
                   8745:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8746: }
                   8747: 
1.555     raeburn  8748: sub user_picker {
1.994     raeburn  8749:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8750:     my $currdom = $dom;
                   8751:     my %curr_selected = (
                   8752:                         srchin => 'dom',
1.580     raeburn  8753:                         srchby => 'lastname',
1.555     raeburn  8754:                       );
                   8755:     my $srchterm;
1.625     raeburn  8756:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  8757:         if ($srch->{'srchby'} ne '') {
                   8758:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   8759:         }
                   8760:         if ($srch->{'srchin'} ne '') {
                   8761:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   8762:         }
                   8763:         if ($srch->{'srchtype'} ne '') {
                   8764:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   8765:         }
                   8766:         if ($srch->{'srchdomain'} ne '') {
                   8767:             $currdom = $srch->{'srchdomain'};
                   8768:         }
                   8769:         $srchterm = $srch->{'srchterm'};
                   8770:     }
                   8771:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  8772:                     'usr'       => 'Search criteria',
1.563     raeburn  8773:                     'doma'      => 'Domain/institution to search',
1.558     albertel 8774:                     'uname'     => 'username',
                   8775:                     'lastname'  => 'last name',
1.555     raeburn  8776:                     'lastfirst' => 'last name, first name',
1.558     albertel 8777:                     'crs'       => 'in this course',
1.576     raeburn  8778:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 8779:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  8780:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 8781:                     'exact'     => 'is',
                   8782:                     'contains'  => 'contains',
1.569     raeburn  8783:                     'begins'    => 'begins with',
1.571     raeburn  8784:                     'youm'      => "You must include some text to search for.",
                   8785:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   8786:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   8787:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   8788:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   8789:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   8790:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   8791:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  8792:                                        );
1.563     raeburn  8793:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   8794:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  8795: 
                   8796:     my @srchins = ('crs','dom','alc','instd');
                   8797: 
                   8798:     foreach my $option (@srchins) {
                   8799:         # FIXME 'alc' option unavailable until 
                   8800:         #       loncreateuser::print_user_query_page()
                   8801:         #       has been completed.
                   8802:         next if ($option eq 'alc');
1.880     raeburn  8803:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  8804:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  8805:         if ($curr_selected{'srchin'} eq $option) {
                   8806:             $srchinsel .= ' 
                   8807:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8808:         } else {
                   8809:             $srchinsel .= '
                   8810:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8811:         }
1.555     raeburn  8812:     }
1.563     raeburn  8813:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  8814: 
                   8815:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  8816:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  8817:         if ($curr_selected{'srchby'} eq $option) {
                   8818:             $srchbysel .= '
                   8819:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8820:         } else {
                   8821:             $srchbysel .= '
                   8822:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8823:          }
                   8824:     }
                   8825:     $srchbysel .= "\n  </select>\n";
                   8826: 
                   8827:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  8828:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  8829:         if ($curr_selected{'srchtype'} eq $option) {
                   8830:             $srchtypesel .= '
                   8831:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8832:         } else {
                   8833:             $srchtypesel .= '
                   8834:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8835:         }
                   8836:     }
                   8837:     $srchtypesel .= "\n  </select>\n";
                   8838: 
1.558     albertel 8839:     my ($newuserscript,$new_user_create);
1.994     raeburn  8840:     my $context_dom = $env{'request.role.domain'};
                   8841:     if ($context eq 'requestcrs') {
                   8842:         if ($env{'form.coursedom'} ne '') { 
                   8843:             $context_dom = $env{'form.coursedom'};
                   8844:         }
                   8845:     }
1.556     raeburn  8846:     if ($forcenewuser) {
1.576     raeburn  8847:         if (ref($srch) eq 'HASH') {
1.994     raeburn  8848:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  8849:                 if ($cancreate) {
                   8850:                     $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>';
                   8851:                 } else {
1.799     bisitz   8852:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  8853:                     my %usertypetext = (
                   8854:                         official   => 'institutional',
                   8855:                         unofficial => 'non-institutional',
                   8856:                     );
1.799     bisitz   8857:                     $new_user_create = '<p class="LC_warning">'
                   8858:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   8859:                                       .' '
                   8860:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   8861:                                           ,'<a href="'.$helplink.'">','</a>')
                   8862:                                       .'</p><br />';
1.627     raeburn  8863:                 }
1.576     raeburn  8864:             }
                   8865:         }
                   8866: 
1.556     raeburn  8867:         $newuserscript = <<"ENDSCRIPT";
                   8868: 
1.570     raeburn  8869: function setSearch(createnew,callingForm) {
1.556     raeburn  8870:     if (createnew == 1) {
1.570     raeburn  8871:         for (var i=0; i<callingForm.srchby.length; i++) {
                   8872:             if (callingForm.srchby.options[i].value == 'uname') {
                   8873:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  8874:             }
                   8875:         }
1.570     raeburn  8876:         for (var i=0; i<callingForm.srchin.length; i++) {
                   8877:             if ( callingForm.srchin.options[i].value == 'dom') {
                   8878: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  8879:             }
                   8880:         }
1.570     raeburn  8881:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   8882:             if (callingForm.srchtype.options[i].value == 'exact') {
                   8883:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  8884:             }
                   8885:         }
1.570     raeburn  8886:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  8887:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  8888:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  8889:             }
                   8890:         }
                   8891:     }
                   8892: }
                   8893: ENDSCRIPT
1.558     albertel 8894: 
1.556     raeburn  8895:     }
                   8896: 
1.555     raeburn  8897:     my $output = <<"END_BLOCK";
1.556     raeburn  8898: <script type="text/javascript">
1.824     bisitz   8899: // <![CDATA[
1.570     raeburn  8900: function validateEntry(callingForm) {
1.558     albertel 8901: 
1.556     raeburn  8902:     var checkok = 1;
1.558     albertel 8903:     var srchin;
1.570     raeburn  8904:     for (var i=0; i<callingForm.srchin.length; i++) {
                   8905: 	if ( callingForm.srchin[i].checked ) {
                   8906: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 8907: 	}
                   8908:     }
                   8909: 
1.570     raeburn  8910:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   8911:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   8912:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   8913:     var srchterm =  callingForm.srchterm.value;
                   8914:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  8915:     var msg = "";
                   8916: 
                   8917:     if (srchterm == "") {
                   8918:         checkok = 0;
1.571     raeburn  8919:         msg += "$lt{'youm'}\\n";
1.556     raeburn  8920:     }
                   8921: 
1.569     raeburn  8922:     if (srchtype== 'begins') {
                   8923:         if (srchterm.length < 2) {
                   8924:             checkok = 0;
1.571     raeburn  8925:             msg += "$lt{'thte'}\\n";
1.569     raeburn  8926:         }
                   8927:     }
                   8928: 
1.556     raeburn  8929:     if (srchtype== 'contains') {
                   8930:         if (srchterm.length < 3) {
                   8931:             checkok = 0;
1.571     raeburn  8932:             msg += "$lt{'thet'}\\n";
1.556     raeburn  8933:         }
                   8934:     }
                   8935:     if (srchin == 'instd') {
                   8936:         if (srchdomain == '') {
                   8937:             checkok = 0;
1.571     raeburn  8938:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  8939:         }
                   8940:     }
                   8941:     if (srchin == 'dom') {
                   8942:         if (srchdomain == '') {
                   8943:             checkok = 0;
1.571     raeburn  8944:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  8945:         }
                   8946:     }
                   8947:     if (srchby == 'lastfirst') {
                   8948:         if (srchterm.indexOf(",") == -1) {
                   8949:             checkok = 0;
1.571     raeburn  8950:             msg += "$lt{'whus'}\\n";
1.556     raeburn  8951:         }
                   8952:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   8953:             checkok = 0;
1.571     raeburn  8954:             msg += "$lt{'whse'}\\n";
1.556     raeburn  8955:         }
                   8956:     }
                   8957:     if (checkok == 0) {
1.571     raeburn  8958:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  8959:         return;
                   8960:     }
                   8961:     if (checkok == 1) {
1.570     raeburn  8962:         callingForm.submit();
1.556     raeburn  8963:     }
                   8964: }
                   8965: 
                   8966: $newuserscript
                   8967: 
1.824     bisitz   8968: // ]]>
1.556     raeburn  8969: </script>
1.558     albertel 8970: 
                   8971: $new_user_create
                   8972: 
1.555     raeburn  8973: END_BLOCK
1.558     albertel 8974: 
1.876     raeburn  8975:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   8976:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   8977:                $domform.
                   8978:                &Apache::lonhtmlcommon::row_closure().
                   8979:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   8980:                $srchbysel.
                   8981:                $srchtypesel. 
                   8982:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   8983:                $srchinsel.
                   8984:                &Apache::lonhtmlcommon::row_closure(1). 
                   8985:                &Apache::lonhtmlcommon::end_pick_box().
                   8986:                '<br />';
1.555     raeburn  8987:     return $output;
                   8988: }
                   8989: 
1.612     raeburn  8990: sub user_rule_check {
1.615     raeburn  8991:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  8992:     my $response;
                   8993:     if (ref($usershash) eq 'HASH') {
                   8994:         foreach my $user (keys(%{$usershash})) {
                   8995:             my ($uname,$udom) = split(/:/,$user);
                   8996:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  8997:             my ($id,$newuser);
1.612     raeburn  8998:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  8999:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9000:                 $id = $usershash->{$user}->{'id'};
                   9001:             }
                   9002:             my $inst_response;
                   9003:             if (ref($checks) eq 'HASH') {
                   9004:                 if (defined($checks->{'username'})) {
1.615     raeburn  9005:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9006:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9007:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9008:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9009:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9010:                 }
1.615     raeburn  9011:             } else {
                   9012:                 ($inst_response,%{$inst_results->{$user}}) =
                   9013:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9014:                 return;
1.612     raeburn  9015:             }
1.615     raeburn  9016:             if (!$got_rules->{$udom}) {
1.612     raeburn  9017:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9018:                                                   ['usercreation'],$udom);
                   9019:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9020:                     foreach my $item ('username','id') {
1.612     raeburn  9021:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9022:                             $$curr_rules{$udom}{$item} = 
                   9023:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9024:                         }
                   9025:                     }
                   9026:                 }
1.615     raeburn  9027:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9028:             }
1.612     raeburn  9029:             foreach my $item (keys(%{$checks})) {
                   9030:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9031:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9032:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9033:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9034:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9035:                                 if ($rule_check{$rule}) {
                   9036:                                     $$rulematch{$user}{$item} = $rule;
                   9037:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9038:                                         if (ref($inst_results) eq 'HASH') {
                   9039:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9040:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9041:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9042:                                                 }
1.612     raeburn  9043:                                             }
                   9044:                                         }
1.615     raeburn  9045:                                     }
                   9046:                                     last;
1.585     raeburn  9047:                                 }
                   9048:                             }
                   9049:                         }
                   9050:                     }
                   9051:                 }
                   9052:             }
                   9053:         }
                   9054:     }
1.612     raeburn  9055:     return;
                   9056: }
                   9057: 
                   9058: sub user_rule_formats {
                   9059:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9060:     my %text = ( 
                   9061:                  'username' => 'Usernames',
                   9062:                  'id'       => 'IDs',
                   9063:                );
                   9064:     my $output;
                   9065:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9066:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9067:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9068:             $output = '<br />'.
                   9069:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9070:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9071:                       ' <ul>';
1.612     raeburn  9072:             foreach my $rule (@{$ruleorder}) {
                   9073:                 if (ref($curr_rules) eq 'ARRAY') {
                   9074:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9075:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9076:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9077:                                         $rules->{$rule}{'desc'}.'</li>';
                   9078:                         }
                   9079:                     }
                   9080:                 }
                   9081:             }
                   9082:             $output .= '</ul>';
                   9083:         }
                   9084:     }
                   9085:     return $output;
                   9086: }
                   9087: 
                   9088: sub instrule_disallow_msg {
1.615     raeburn  9089:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9090:     my $response;
                   9091:     my %text = (
                   9092:                   item   => 'username',
                   9093:                   items  => 'usernames',
                   9094:                   match  => 'matches',
                   9095:                   do     => 'does',
                   9096:                   action => 'a username',
                   9097:                   one    => 'one',
                   9098:                );
                   9099:     if ($count > 1) {
                   9100:         $text{'item'} = 'usernames';
                   9101:         $text{'match'} ='match';
                   9102:         $text{'do'} = 'do';
                   9103:         $text{'action'} = 'usernames',
                   9104:         $text{'one'} = 'ones';
                   9105:     }
                   9106:     if ($checkitem eq 'id') {
                   9107:         $text{'items'} = 'IDs';
                   9108:         $text{'item'} = 'ID';
                   9109:         $text{'action'} = 'an ID';
1.615     raeburn  9110:         if ($count > 1) {
                   9111:             $text{'item'} = 'IDs';
                   9112:             $text{'action'} = 'IDs';
                   9113:         }
1.612     raeburn  9114:     }
1.674     bisitz   9115:     $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  9116:     if ($mode eq 'upload') {
                   9117:         if ($checkitem eq 'username') {
                   9118:             $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'}.");
                   9119:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9120:             $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  9121:         }
1.669     raeburn  9122:     } elsif ($mode eq 'selfcreate') {
                   9123:         if ($checkitem eq 'id') {
                   9124:             $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.");
                   9125:         }
1.615     raeburn  9126:     } else {
                   9127:         if ($checkitem eq 'username') {
                   9128:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9129:         } elsif ($checkitem eq 'id') {
                   9130:             $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.");
                   9131:         }
1.612     raeburn  9132:     }
                   9133:     return $response;
1.585     raeburn  9134: }
                   9135: 
1.624     raeburn  9136: sub personal_data_fieldtitles {
                   9137:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9138:                         id => 'Student/Employee ID',
                   9139:                         permanentemail => 'E-mail address',
                   9140:                         lastname => 'Last Name',
                   9141:                         firstname => 'First Name',
                   9142:                         middlename => 'Middle Name',
                   9143:                         generation => 'Generation',
                   9144:                         gen => 'Generation',
1.765     raeburn  9145:                         inststatus => 'Affiliation',
1.624     raeburn  9146:                    );
                   9147:     return %fieldtitles;
                   9148: }
                   9149: 
1.642     raeburn  9150: sub sorted_inst_types {
                   9151:     my ($dom) = @_;
                   9152:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9153:     my $othertitle = &mt('All users');
                   9154:     if ($env{'request.course.id'}) {
1.668     raeburn  9155:         $othertitle  = &mt('Any users');
1.642     raeburn  9156:     }
                   9157:     my @types;
                   9158:     if (ref($order) eq 'ARRAY') {
                   9159:         @types = @{$order};
                   9160:     }
                   9161:     if (@types == 0) {
                   9162:         if (ref($usertypes) eq 'HASH') {
                   9163:             @types = sort(keys(%{$usertypes}));
                   9164:         }
                   9165:     }
                   9166:     if (keys(%{$usertypes}) > 0) {
                   9167:         $othertitle = &mt('Other users');
                   9168:     }
                   9169:     return ($othertitle,$usertypes,\@types);
                   9170: }
                   9171: 
1.645     raeburn  9172: sub get_institutional_codes {
                   9173:     my ($settings,$allcourses,$LC_code) = @_;
                   9174: # Get complete list of course sections to update
                   9175:     my @currsections = ();
                   9176:     my @currxlists = ();
                   9177:     my $coursecode = $$settings{'internal.coursecode'};
                   9178: 
                   9179:     if ($$settings{'internal.sectionnums'} ne '') {
                   9180:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9181:     }
                   9182: 
                   9183:     if ($$settings{'internal.crosslistings'} ne '') {
                   9184:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9185:     }
                   9186: 
                   9187:     if (@currxlists > 0) {
                   9188:         foreach (@currxlists) {
                   9189:             if (m/^([^:]+):(\w*)$/) {
                   9190:                 unless (grep/^$1$/,@{$allcourses}) {
                   9191:                     push @{$allcourses},$1;
                   9192:                     $$LC_code{$1} = $2;
                   9193:                 }
                   9194:             }
                   9195:         }
                   9196:     }
                   9197:  
                   9198:     if (@currsections > 0) {
                   9199:         foreach (@currsections) {
                   9200:             if (m/^(\w+):(\w*)$/) {
                   9201:                 my $sec = $coursecode.$1;
                   9202:                 my $lc_sec = $2;
                   9203:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9204:                     push @{$allcourses},$sec;
                   9205:                     $$LC_code{$sec} = $lc_sec;
                   9206:                 }
                   9207:             }
                   9208:         }
                   9209:     }
                   9210:     return;
                   9211: }
                   9212: 
1.971     raeburn  9213: sub get_standard_codeitems {
                   9214:     return ('Year','Semester','Department','Number','Section');
                   9215: }
                   9216: 
1.112     bowersj2 9217: =pod
                   9218: 
1.780     raeburn  9219: =head1 Slot Helpers
                   9220: 
                   9221: =over 4
                   9222: 
                   9223: =item * sorted_slots()
                   9224: 
1.1040    raeburn  9225: Sorts an array of slot names in order of an optional sort key,
                   9226: default sort is by slot start time (earliest first). 
1.780     raeburn  9227: 
                   9228: Inputs:
                   9229: 
                   9230: =over 4
                   9231: 
                   9232: slotsarr  - Reference to array of unsorted slot names.
                   9233: 
                   9234: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9235: 
1.1040    raeburn  9236: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9237: 
1.549     albertel 9238: =back
                   9239: 
1.780     raeburn  9240: Returns:
                   9241: 
                   9242: =over 4
                   9243: 
1.1040    raeburn  9244: sorted   - An array of slot names sorted by a specified sort key 
                   9245:            (default sort key is start time of the slot).
1.780     raeburn  9246: 
                   9247: =back
                   9248: 
                   9249: =cut
                   9250: 
                   9251: 
                   9252: sub sorted_slots {
1.1040    raeburn  9253:     my ($slotsarr,$slots,$sortkey) = @_;
                   9254:     if ($sortkey eq '') {
                   9255:         $sortkey = 'starttime';
                   9256:     }
1.780     raeburn  9257:     my @sorted;
                   9258:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9259:         @sorted =
                   9260:             sort {
                   9261:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9262:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9263:                      }
                   9264:                      if (ref($slots->{$a})) { return -1;}
                   9265:                      if (ref($slots->{$b})) { return 1;}
                   9266:                      return 0;
                   9267:                  } @{$slotsarr};
                   9268:     }
                   9269:     return @sorted;
                   9270: }
                   9271: 
1.1040    raeburn  9272: =pod
                   9273: 
                   9274: =item * get_future_slots()
                   9275: 
                   9276: Inputs:
                   9277: 
                   9278: =over 4
                   9279: 
                   9280: cnum - course number
                   9281: 
                   9282: cdom - course domain
                   9283: 
                   9284: now - current UNIX time
                   9285: 
                   9286: symb - optional symb
                   9287: 
                   9288: =back
                   9289: 
                   9290: Returns:
                   9291: 
                   9292: =over 4
                   9293: 
                   9294: sorted_reservable - ref to array of student_schedulable slots currently 
                   9295:                     reservable, ordered by end date of reservation period.
                   9296: 
                   9297: reservable_now - ref to hash of student_schedulable slots currently
                   9298:                  reservable.
                   9299: 
                   9300:     Keys in inner hash are:
                   9301:     (a) symb: either blank or symb to which slot use is restricted.
                   9302:     (b) endreserve: end date of reservation period. 
                   9303: 
                   9304: sorted_future - ref to array of student_schedulable slots reservable in
                   9305:                 the future, ordered by start date of reservation period.
                   9306: 
                   9307: future_reservable - ref to hash of student_schedulable slots reservable
                   9308:                     in the future.
                   9309: 
                   9310:     Keys in inner hash are:
                   9311:     (a) symb: either blank or symb to which slot use is restricted.
                   9312:     (b) startreserve:  start date of reservation period.
                   9313: 
                   9314: =back
                   9315: 
                   9316: =cut
                   9317: 
                   9318: sub get_future_slots {
                   9319:     my ($cnum,$cdom,$now,$symb) = @_;
                   9320:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9321:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9322:     foreach my $slot (keys(%slots)) {
                   9323:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9324:         if ($symb) {
                   9325:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9326:                      ($slots{$slot}->{'symb'} ne $symb));
                   9327:         }
                   9328:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9329:             ($slots{$slot}->{'endtime'} > $now)) {
                   9330:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9331:                 my $userallowed = 0;
                   9332:                 if ($slots{$slot}->{'allowedsections'}) {
                   9333:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9334:                     if (!defined($env{'request.role.sec'})
                   9335:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9336:                         $userallowed=1;
                   9337:                     } else {
                   9338:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9339:                             $userallowed=1;
                   9340:                         }
                   9341:                     }
                   9342:                     unless ($userallowed) {
                   9343:                         if (defined($env{'request.course.groups'})) {
                   9344:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9345:                             foreach my $group (@groups) {
                   9346:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9347:                                     $userallowed=1;
                   9348:                                     last;
                   9349:                                 }
                   9350:                             }
                   9351:                         }
                   9352:                     }
                   9353:                 }
                   9354:                 if ($slots{$slot}->{'allowedusers'}) {
                   9355:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9356:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9357:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9358:                         $userallowed = 1;
                   9359:                     }
                   9360:                 }
                   9361:                 next unless($userallowed);
                   9362:             }
                   9363:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9364:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9365:             my $symb = $slots{$slot}->{'symb'};
                   9366:             if (($startreserve < $now) &&
                   9367:                 (!$endreserve || $endreserve > $now)) {
                   9368:                 my $lastres = $endreserve;
                   9369:                 if (!$lastres) {
                   9370:                     $lastres = $slots{$slot}->{'starttime'};
                   9371:                 }
                   9372:                 $reservable_now{$slot} = {
                   9373:                                            symb       => $symb,
                   9374:                                            endreserve => $lastres
                   9375:                                          };
                   9376:             } elsif (($startreserve > $now) &&
                   9377:                      (!$endreserve || $endreserve > $startreserve)) {
                   9378:                 $future_reservable{$slot} = {
                   9379:                                               symb         => $symb,
                   9380:                                               startreserve => $startreserve
                   9381:                                             };
                   9382:             }
                   9383:         }
                   9384:     }
                   9385:     my @unsorted_reservable = keys(%reservable_now);
                   9386:     if (@unsorted_reservable > 0) {
                   9387:         @sorted_reservable = 
                   9388:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9389:     }
                   9390:     my @unsorted_future = keys(%future_reservable);
                   9391:     if (@unsorted_future > 0) {
                   9392:         @sorted_future =
                   9393:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9394:     }
                   9395:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9396: }
1.780     raeburn  9397: 
                   9398: =pod
                   9399: 
1.1057    foxr     9400: =back
                   9401: 
1.549     albertel 9402: =head1 HTTP Helpers
                   9403: 
                   9404: =over 4
                   9405: 
1.648     raeburn  9406: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9407: 
1.258     albertel 9408: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9409: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9410: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9411: 
                   9412: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9413: $possible_names is an ref to an array of form element names.  As an example:
                   9414: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9415: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9416: 
                   9417: =cut
1.1       albertel 9418: 
1.6       albertel 9419: sub get_unprocessed_cgi {
1.25      albertel 9420:   my ($query,$possible_names)= @_;
1.26      matthew  9421:   # $Apache::lonxml::debug=1;
1.356     albertel 9422:   foreach my $pair (split(/&/,$query)) {
                   9423:     my ($name, $value) = split(/=/,$pair);
1.369     www      9424:     $name = &unescape($name);
1.25      albertel 9425:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9426:       $value =~ tr/+/ /;
                   9427:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9428:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9429:     }
1.16      harris41 9430:   }
1.6       albertel 9431: }
                   9432: 
1.112     bowersj2 9433: =pod
                   9434: 
1.648     raeburn  9435: =item * &cacheheader() 
1.112     bowersj2 9436: 
                   9437: returns cache-controlling header code
                   9438: 
                   9439: =cut
                   9440: 
1.7       albertel 9441: sub cacheheader {
1.258     albertel 9442:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9443:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9444:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9445:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9446:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9447:     return $output;
1.7       albertel 9448: }
                   9449: 
1.112     bowersj2 9450: =pod
                   9451: 
1.648     raeburn  9452: =item * &no_cache($r) 
1.112     bowersj2 9453: 
                   9454: specifies header code to not have cache
                   9455: 
                   9456: =cut
                   9457: 
1.9       albertel 9458: sub no_cache {
1.216     albertel 9459:     my ($r) = @_;
                   9460:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9461: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9462:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9463:     $r->no_cache(1);
                   9464:     $r->header_out("Expires" => $date);
                   9465:     $r->header_out("Pragma" => "no-cache");
1.123     www      9466: }
                   9467: 
                   9468: sub content_type {
1.181     albertel 9469:     my ($r,$type,$charset) = @_;
1.299     foxr     9470:     if ($r) {
                   9471: 	#  Note that printout.pl calls this with undef for $r.
                   9472: 	&no_cache($r);
                   9473:     }
1.258     albertel 9474:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9475:     unless ($charset) {
                   9476: 	$charset=&Apache::lonlocal::current_encoding;
                   9477:     }
                   9478:     if ($charset) { $type.='; charset='.$charset; }
                   9479:     if ($r) {
                   9480: 	$r->content_type($type);
                   9481:     } else {
                   9482: 	print("Content-type: $type\n\n");
                   9483:     }
1.9       albertel 9484: }
1.25      albertel 9485: 
1.112     bowersj2 9486: =pod
                   9487: 
1.648     raeburn  9488: =item * &add_to_env($name,$value) 
1.112     bowersj2 9489: 
1.258     albertel 9490: adds $name to the %env hash with value
1.112     bowersj2 9491: $value, if $name already exists, the entry is converted to an array
                   9492: reference and $value is added to the array.
                   9493: 
                   9494: =cut
                   9495: 
1.25      albertel 9496: sub add_to_env {
                   9497:   my ($name,$value)=@_;
1.258     albertel 9498:   if (defined($env{$name})) {
                   9499:     if (ref($env{$name})) {
1.25      albertel 9500:       #already have multiple values
1.258     albertel 9501:       push(@{ $env{$name} },$value);
1.25      albertel 9502:     } else {
                   9503:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9504:       my $first=$env{$name};
                   9505:       undef($env{$name});
                   9506:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9507:     }
                   9508:   } else {
1.258     albertel 9509:     $env{$name}=$value;
1.25      albertel 9510:   }
1.31      albertel 9511: }
1.149     albertel 9512: 
                   9513: =pod
                   9514: 
1.648     raeburn  9515: =item * &get_env_multiple($name) 
1.149     albertel 9516: 
1.258     albertel 9517: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9518: values may be defined and end up as an array ref.
                   9519: 
                   9520: returns an array of values
                   9521: 
                   9522: =cut
                   9523: 
                   9524: sub get_env_multiple {
                   9525:     my ($name) = @_;
                   9526:     my @values;
1.258     albertel 9527:     if (defined($env{$name})) {
1.149     albertel 9528:         # exists is it an array
1.258     albertel 9529:         if (ref($env{$name})) {
                   9530:             @values=@{ $env{$name} };
1.149     albertel 9531:         } else {
1.258     albertel 9532:             $values[0]=$env{$name};
1.149     albertel 9533:         }
                   9534:     }
                   9535:     return(@values);
                   9536: }
                   9537: 
1.660     raeburn  9538: sub ask_for_embedded_content {
                   9539:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9540:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  9541:         %currsubfile,%unused,$rem);
1.1071    raeburn  9542:     my $counter = 0;
                   9543:     my $numnew = 0;
1.987     raeburn  9544:     my $numremref = 0;
                   9545:     my $numinvalid = 0;
                   9546:     my $numpathchg = 0;
                   9547:     my $numexisting = 0;
1.1071    raeburn  9548:     my $numunused = 0;
                   9549:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
                   9550:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
                   9551:     my $heading = &mt('Upload embedded files');
                   9552:     my $buttontext = &mt('Upload');
                   9553: 
1.1075.2.35  raeburn  9554:     my ($navmap,$cdom,$cnum);
1.1075.2.11  raeburn  9555:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  9556:         if ($actionurl eq '/adm/dependencies') {
                   9557:             $navmap = Apache::lonnavmaps::navmap->new();
                   9558:         }
                   9559:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9560:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  9561:     }
1.1075.2.35  raeburn  9562:     if (($actionurl eq '/adm/portfolio') ||
                   9563:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  9564:         my $current_path='/';
                   9565:         if ($env{'form.currentpath'}) {
                   9566:             $current_path = $env{'form.currentpath'};
                   9567:         }
                   9568:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  9569:             $udom = $cdom;
                   9570:             $uname = $cnum;
1.984     raeburn  9571:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9572:         } else {
                   9573:             $udom = $env{'user.domain'};
                   9574:             $uname = $env{'user.name'};
                   9575:             $url = '/userfiles/portfolio';
                   9576:         }
1.987     raeburn  9577:         $toplevel = $url.'/';
1.984     raeburn  9578:         $url .= $current_path;
                   9579:         $getpropath = 1;
1.987     raeburn  9580:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9581:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9582:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9583:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9584:         $toplevel = $url;
1.984     raeburn  9585:         if ($rest ne '') {
1.987     raeburn  9586:             $url .= $rest;
                   9587:         }
                   9588:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9589:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9590:             $url = $args->{'docs_url'};
                   9591:             $toplevel = $url;
1.1075.2.11  raeburn  9592:             if ($args->{'context'} eq 'paste') {
                   9593:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9594:                 ($path) =
                   9595:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9596:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9597:                 $fileloc =~ s{^/}{};
                   9598:             }
1.1071    raeburn  9599:         }
                   9600:     } elsif ($actionurl eq '/adm/dependencies') {
                   9601:         if ($env{'request.course.id'} ne '') {
                   9602:             if (ref($args) eq 'HASH') {
                   9603:                 $url = $args->{'docs_url'};
                   9604:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  9605:                 $toplevel = $url;
                   9606:                 unless ($toplevel =~ m{^/}) {
                   9607:                     $toplevel = "/$url";
                   9608:                 }
1.1075.2.11  raeburn  9609:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  9610:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   9611:                     $path = $1;
                   9612:                 } else {
                   9613:                     ($path) =
                   9614:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9615:                 }
1.1071    raeburn  9616:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9617:                 $fileloc =~ s{^/}{};
                   9618:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9619:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9620:             }
1.987     raeburn  9621:         }
1.1075.2.35  raeburn  9622:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9623:         $udom = $cdom;
                   9624:         $uname = $cnum;
                   9625:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   9626:         $toplevel = $url;
                   9627:         $path = $url;
                   9628:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   9629:         $fileloc =~ s{^/}{};
                   9630:     }
                   9631:     foreach my $file (keys(%{$allfiles})) {
                   9632:         my $embed_file;
                   9633:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   9634:             $embed_file = $1;
                   9635:         } else {
                   9636:             $embed_file = $file;
                   9637:         }
1.987     raeburn  9638:         my $absolutepath;
                   9639:         if ($embed_file =~ m{^\w+://}) {
                   9640:             $newfiles{$embed_file} = 1;
                   9641:             $mapping{$embed_file} = $embed_file;
                   9642:         } else {
                   9643:             if ($embed_file =~ m{^/}) {
                   9644:                 $absolutepath = $embed_file;
                   9645:                 $embed_file =~ s{^(/+)}{};
                   9646:             }
                   9647:             if ($embed_file =~ m{/}) {
                   9648:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
                   9649:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9650:                 my $item = $fname;
                   9651:                 if ($path ne '') {
                   9652:                     $item = $path.'/'.$fname;
                   9653:                     $subdependencies{$path}{$fname} = 1;
                   9654:                 } else {
                   9655:                     $dependencies{$item} = 1;
                   9656:                 }
                   9657:                 if ($absolutepath) {
                   9658:                     $mapping{$item} = $absolutepath;
                   9659:                 } else {
                   9660:                     $mapping{$item} = $embed_file;
                   9661:                 }
                   9662:             } else {
                   9663:                 $dependencies{$embed_file} = 1;
                   9664:                 if ($absolutepath) {
                   9665:                     $mapping{$embed_file} = $absolutepath;
                   9666:                 } else {
                   9667:                     $mapping{$embed_file} = $embed_file;
                   9668:                 }
                   9669:             }
1.984     raeburn  9670:         }
                   9671:     }
1.1071    raeburn  9672:     my $dirptr = 16384;
1.984     raeburn  9673:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9674:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  9675:         if (($actionurl eq '/adm/portfolio') ||
                   9676:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9677:             my ($sublistref,$listerror) =
                   9678:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9679:             if (ref($sublistref) eq 'ARRAY') {
                   9680:                 foreach my $line (@{$sublistref}) {
                   9681:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9682:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9683:                 }
1.984     raeburn  9684:             }
1.987     raeburn  9685:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9686:             if (opendir(my $dir,$url.'/'.$path)) {
                   9687:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9688:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9689:             }
1.1075.2.11  raeburn  9690:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9691:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  9692:                   ($args->{'context'} eq 'paste')) ||
                   9693:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9694:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  9695:                 my $dir;
                   9696:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9697:                     $dir = $fileloc;
                   9698:                 } else {
                   9699:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9700:                 }
1.1071    raeburn  9701:                 if ($dir ne '') {
                   9702:                     my ($sublistref,$listerror) =
                   9703:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9704:                     if (ref($sublistref) eq 'ARRAY') {
                   9705:                         foreach my $line (@{$sublistref}) {
                   9706:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9707:                                 undef,$mtime)=split(/\&/,$line,12);
                   9708:                             unless (($testdir&$dirptr) ||
                   9709:                                     ($file_name =~ /^\.\.?$/)) {
                   9710:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9711:                             }
                   9712:                         }
                   9713:                     }
                   9714:                 }
1.984     raeburn  9715:             }
                   9716:         }
                   9717:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9718:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9719:                 my $item = $path.'/'.$file;
                   9720:                 unless ($mapping{$item} eq $item) {
                   9721:                     $pathchanges{$item} = 1;
                   9722:                 }
                   9723:                 $existing{$item} = 1;
                   9724:                 $numexisting ++;
                   9725:             } else {
                   9726:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9727:             }
                   9728:         }
1.1071    raeburn  9729:         if ($actionurl eq '/adm/dependencies') {
                   9730:             foreach my $path (keys(%currsubfile)) {
                   9731:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9732:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9733:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  9734:                              next if (($rem ne '') &&
                   9735:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9736:                                        (ref($navmap) &&
                   9737:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9738:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9739:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9740:                              $unused{$path.'/'.$file} = 1; 
                   9741:                          }
                   9742:                     }
                   9743:                 }
                   9744:             }
                   9745:         }
1.984     raeburn  9746:     }
1.987     raeburn  9747:     my %currfile;
1.1075.2.35  raeburn  9748:     if (($actionurl eq '/adm/portfolio') ||
                   9749:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9750:         my ($dirlistref,$listerror) =
                   9751:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9752:         if (ref($dirlistref) eq 'ARRAY') {
                   9753:             foreach my $line (@{$dirlistref}) {
                   9754:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   9755:                 $currfile{$file_name} = 1;
                   9756:             }
1.984     raeburn  9757:         }
1.987     raeburn  9758:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9759:         if (opendir(my $dir,$url)) {
1.987     raeburn  9760:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  9761:             map {$currfile{$_} = 1;} @dir_list;
                   9762:         }
1.1075.2.11  raeburn  9763:     } elsif (($actionurl eq '/adm/dependencies') ||
                   9764:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  9765:               ($args->{'context'} eq 'paste')) ||
                   9766:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9767:         if ($env{'request.course.id'} ne '') {
                   9768:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9769:             if ($dir ne '') {
                   9770:                 my ($dirlistref,$listerror) =
                   9771:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   9772:                 if (ref($dirlistref) eq 'ARRAY') {
                   9773:                     foreach my $line (@{$dirlistref}) {
                   9774:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   9775:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   9776:                         unless (($testdir&$dirptr) ||
                   9777:                                 ($file_name =~ /^\.\.?$/)) {
                   9778:                             $currfile{$file_name} = [$size,$mtime];
                   9779:                         }
                   9780:                     }
                   9781:                 }
                   9782:             }
                   9783:         }
1.984     raeburn  9784:     }
                   9785:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  9786:         if (exists($currfile{$file})) {
1.987     raeburn  9787:             unless ($mapping{$file} eq $file) {
                   9788:                 $pathchanges{$file} = 1;
                   9789:             }
                   9790:             $existing{$file} = 1;
                   9791:             $numexisting ++;
                   9792:         } else {
1.984     raeburn  9793:             $newfiles{$file} = 1;
                   9794:         }
                   9795:     }
1.1071    raeburn  9796:     foreach my $file (keys(%currfile)) {
                   9797:         unless (($file eq $filename) ||
                   9798:                 ($file eq $filename.'.bak') ||
                   9799:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  9800:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  9801:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   9802:                     next if (($rem ne '') &&
                   9803:                              (($env{"httpref.$rem".$file} ne '') ||
                   9804:                               (ref($navmap) &&
                   9805:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   9806:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9807:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   9808:                 }
1.1075.2.11  raeburn  9809:             }
1.1071    raeburn  9810:             $unused{$file} = 1;
                   9811:         }
                   9812:     }
1.1075.2.11  raeburn  9813:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9814:         ($args->{'context'} eq 'paste')) {
                   9815:         $counter = scalar(keys(%existing));
                   9816:         $numpathchg = scalar(keys(%pathchanges));
                   9817:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  9818:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   9819:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   9820:         $counter = scalar(keys(%existing));
                   9821:         $numpathchg = scalar(keys(%pathchanges));
                   9822:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  9823:     }
1.984     raeburn  9824:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  9825:         if ($actionurl eq '/adm/dependencies') {
                   9826:             next if ($embed_file =~ m{^\w+://});
                   9827:         }
1.660     raeburn  9828:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  9829:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  9830:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  9831:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  9832:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   9833:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  9834:         }
1.1075.2.35  raeburn  9835:         $upload_output .= '</td>';
1.1071    raeburn  9836:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  9837:             $upload_output.='<td align="right">'.
                   9838:                             '<span class="LC_info LC_fontsize_medium">'.
                   9839:                             &mt("URL points to web address").'</span>';
1.987     raeburn  9840:             $numremref++;
1.660     raeburn  9841:         } elsif ($args->{'error_on_invalid_names'}
                   9842:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  9843:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   9844:                             &mt('Invalid characters').'</span>';
1.987     raeburn  9845:             $numinvalid++;
1.660     raeburn  9846:         } else {
1.1075.2.35  raeburn  9847:             $upload_output .= '<td>'.
                   9848:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  9849:                                                      $embed_file,\%mapping,
1.1071    raeburn  9850:                                                      $allfiles,$codebase,'upload');
                   9851:             $counter ++;
                   9852:             $numnew ++;
1.987     raeburn  9853:         }
                   9854:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   9855:     }
                   9856:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  9857:         if ($actionurl eq '/adm/dependencies') {
                   9858:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   9859:             $modify_output .= &start_data_table_row().
                   9860:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   9861:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   9862:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   9863:                               '<td>'.$size.'</td>'.
                   9864:                               '<td>'.$mtime.'</td>'.
                   9865:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   9866:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   9867:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   9868:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   9869:                               &embedded_file_element('upload_embedded',$counter,
                   9870:                                                      $embed_file,\%mapping,
                   9871:                                                      $allfiles,$codebase,'modify').
                   9872:                               '</div></td>'.
                   9873:                               &end_data_table_row()."\n";
                   9874:             $counter ++;
                   9875:         } else {
                   9876:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  9877:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   9878:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   9879:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  9880:                               &Apache::loncommon::end_data_table_row()."\n";
                   9881:         }
                   9882:     }
                   9883:     my $delidx = $counter;
                   9884:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   9885:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   9886:         $delete_output .= &start_data_table_row().
                   9887:                           '<td><img src="'.&icon($oldfile).'" />'.
                   9888:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   9889:                           '<td>'.$size.'</td>'.
                   9890:                           '<td>'.$mtime.'</td>'.
                   9891:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   9892:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   9893:                           &embedded_file_element('upload_embedded',$delidx,
                   9894:                                                  $oldfile,\%mapping,$allfiles,
                   9895:                                                  $codebase,'delete').'</td>'.
                   9896:                           &end_data_table_row()."\n"; 
                   9897:         $numunused ++;
                   9898:         $delidx ++;
1.987     raeburn  9899:     }
                   9900:     if ($upload_output) {
                   9901:         $upload_output = &start_data_table().
                   9902:                          $upload_output.
                   9903:                          &end_data_table()."\n";
                   9904:     }
1.1071    raeburn  9905:     if ($modify_output) {
                   9906:         $modify_output = &start_data_table().
                   9907:                          &start_data_table_header_row().
                   9908:                          '<th>'.&mt('File').'</th>'.
                   9909:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9910:                          '<th>'.&mt('Modified').'</th>'.
                   9911:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   9912:                          &end_data_table_header_row().
                   9913:                          $modify_output.
                   9914:                          &end_data_table()."\n";
                   9915:     }
                   9916:     if ($delete_output) {
                   9917:         $delete_output = &start_data_table().
                   9918:                          &start_data_table_header_row().
                   9919:                          '<th>'.&mt('File').'</th>'.
                   9920:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9921:                          '<th>'.&mt('Modified').'</th>'.
                   9922:                          '<th>'.&mt('Delete?').'</th>'.
                   9923:                          &end_data_table_header_row().
                   9924:                          $delete_output.
                   9925:                          &end_data_table()."\n";
                   9926:     }
1.987     raeburn  9927:     my $applies = 0;
                   9928:     if ($numremref) {
                   9929:         $applies ++;
                   9930:     }
                   9931:     if ($numinvalid) {
                   9932:         $applies ++;
                   9933:     }
                   9934:     if ($numexisting) {
                   9935:         $applies ++;
                   9936:     }
1.1071    raeburn  9937:     if ($counter || $numunused) {
1.987     raeburn  9938:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   9939:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  9940:                   $state.'<h3>'.$heading.'</h3>'; 
                   9941:         if ($actionurl eq '/adm/dependencies') {
                   9942:             if ($numnew) {
                   9943:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   9944:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   9945:                            $upload_output.'<br />'."\n";
                   9946:             }
                   9947:             if ($numexisting) {
                   9948:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   9949:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   9950:                            $modify_output.'<br />'."\n";
                   9951:                            $buttontext = &mt('Save changes');
                   9952:             }
                   9953:             if ($numunused) {
                   9954:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   9955:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   9956:                            $delete_output.'<br />'."\n";
                   9957:                            $buttontext = &mt('Save changes');
                   9958:             }
                   9959:         } else {
                   9960:             $output .= $upload_output.'<br />'."\n";
                   9961:         }
                   9962:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   9963:                    $counter.'" />'."\n";
                   9964:         if ($actionurl eq '/adm/dependencies') { 
                   9965:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   9966:                        $numnew.'" />'."\n";
                   9967:         } elsif ($actionurl eq '') {
1.987     raeburn  9968:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   9969:         }
                   9970:     } elsif ($applies) {
                   9971:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   9972:         if ($applies > 1) {
                   9973:             $output .=  
1.1075.2.35  raeburn  9974:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  9975:             if ($numremref) {
                   9976:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   9977:             }
                   9978:             if ($numinvalid) {
                   9979:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   9980:             }
                   9981:             if ($numexisting) {
                   9982:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   9983:             }
                   9984:             $output .= '</ul><br />';
                   9985:         } elsif ($numremref) {
                   9986:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   9987:         } elsif ($numinvalid) {
                   9988:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   9989:         } elsif ($numexisting) {
                   9990:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   9991:         }
                   9992:         $output .= $upload_output.'<br />';
                   9993:     }
                   9994:     my ($pathchange_output,$chgcount);
1.1071    raeburn  9995:     $chgcount = $counter;
1.987     raeburn  9996:     if (keys(%pathchanges) > 0) {
                   9997:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  9998:             if ($counter) {
1.987     raeburn  9999:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10000:                                                   $embed_file,\%mapping,
1.1071    raeburn  10001:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10002:             } else {
                   10003:                 $pathchange_output .= 
                   10004:                     &start_data_table_row().
                   10005:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10006:                     $chgcount.'" checked="checked" /></td>'.
                   10007:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10008:                     '<td>'.$embed_file.
                   10009:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10010:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10011:                     '</td>'.&end_data_table_row();
1.660     raeburn  10012:             }
1.987     raeburn  10013:             $numpathchg ++;
                   10014:             $chgcount ++;
1.660     raeburn  10015:         }
                   10016:     }
1.1075.2.35  raeburn  10017:     if (($counter) || ($numunused)) {
1.987     raeburn  10018:         if ($numpathchg) {
                   10019:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10020:                        $numpathchg.'" />'."\n";
                   10021:         }
                   10022:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10023:             ($actionurl eq '/adm/imsimport')) {
                   10024:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10025:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10026:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10027:         } elsif ($actionurl eq '/adm/dependencies') {
                   10028:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10029:         }
1.1075.2.35  raeburn  10030:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10031:     } elsif ($numpathchg) {
                   10032:         my %pathchange = ();
                   10033:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10034:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10035:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10036:         }
1.987     raeburn  10037:     }
1.1071    raeburn  10038:     return ($output,$counter,$numpathchg);
1.987     raeburn  10039: }
                   10040: 
                   10041: sub embedded_file_element {
1.1071    raeburn  10042:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10043:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10044:                    (ref($codebase) eq 'HASH'));
                   10045:     my $output;
1.1071    raeburn  10046:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10047:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10048:     }
                   10049:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10050:                &escape($embed_file).'" />';
                   10051:     unless (($context eq 'upload_embedded') && 
                   10052:             ($mapping->{$embed_file} eq $embed_file)) {
                   10053:         $output .='
                   10054:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10055:     }
                   10056:     my $attrib;
                   10057:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10058:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10059:     }
                   10060:     $output .=
                   10061:         "\n\t\t".
                   10062:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10063:         $attrib.'" />';
                   10064:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10065:         $output .=
                   10066:             "\n\t\t".
                   10067:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10068:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10069:     }
1.987     raeburn  10070:     return $output;
1.660     raeburn  10071: }
                   10072: 
1.1071    raeburn  10073: sub get_dependency_details {
                   10074:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10075:     my ($size,$mtime,$showsize,$showmtime);
                   10076:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10077:         if ($embed_file =~ m{/}) {
                   10078:             my ($path,$fname) = split(/\//,$embed_file);
                   10079:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10080:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10081:             }
                   10082:         } else {
                   10083:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10084:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10085:             }
                   10086:         }
                   10087:         $showsize = $size/1024.0;
                   10088:         $showsize = sprintf("%.1f",$showsize);
                   10089:         if ($mtime > 0) {
                   10090:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10091:         }
                   10092:     }
                   10093:     return ($showsize,$showmtime);
                   10094: }
                   10095: 
                   10096: sub ask_embedded_js {
                   10097:     return <<"END";
                   10098: <script type="text/javascript"">
                   10099: // <![CDATA[
                   10100: function toggleBrowse(counter) {
                   10101:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10102:     var fileid = document.getElementById('embedded_item_'+counter);
                   10103:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10104:     if (chkboxid.checked == true) {
                   10105:         uploaddivid.style.display='block';
                   10106:     } else {
                   10107:         uploaddivid.style.display='none';
                   10108:         fileid.value = '';
                   10109:     }
                   10110: }
                   10111: // ]]>
                   10112: </script>
                   10113: 
                   10114: END
                   10115: }
                   10116: 
1.661     raeburn  10117: sub upload_embedded {
                   10118:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10119:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10120:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10121:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10122:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10123:         my $orig_uploaded_filename =
                   10124:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10125:         foreach my $type ('orig','ref','attrib','codebase') {
                   10126:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10127:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10128:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10129:             }
                   10130:         }
1.661     raeburn  10131:         my ($path,$fname) =
                   10132:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10133:         # no path, whole string is fname
                   10134:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10135:         $fname = &Apache::lonnet::clean_filename($fname);
                   10136:         # See if there is anything left
                   10137:         next if ($fname eq '');
                   10138: 
                   10139:         # Check if file already exists as a file or directory.
                   10140:         my ($state,$msg);
                   10141:         if ($context eq 'portfolio') {
                   10142:             my $port_path = $dirpath;
                   10143:             if ($group ne '') {
                   10144:                 $port_path = "groups/$group/$port_path";
                   10145:             }
1.987     raeburn  10146:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10147:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10148:                                               $dir_root,$port_path,$disk_quota,
                   10149:                                               $current_disk_usage,$uname,$udom);
                   10150:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10151:                 || $state eq 'file_locked') {
1.661     raeburn  10152:                 $output .= $msg;
                   10153:                 next;
                   10154:             }
                   10155:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10156:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10157:             if ($state eq 'exists') {
                   10158:                 $output .= $msg;
                   10159:                 next;
                   10160:             }
                   10161:         }
                   10162:         # Check if extension is valid
                   10163:         if (($fname =~ /\.(\w+)$/) &&
                   10164:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.987     raeburn  10165:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
1.661     raeburn  10166:             next;
                   10167:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10168:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10169:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10170:             next;
                   10171:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  10172:             $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  10173:             next;
                   10174:         }
                   10175:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  10176:         my $subdir = $path;
                   10177:         $subdir =~ s{/+$}{};
1.661     raeburn  10178:         if ($context eq 'portfolio') {
1.984     raeburn  10179:             my $result;
                   10180:             if ($state eq 'existingfile') {
                   10181:                 $result=
                   10182:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  10183:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10184:             } else {
1.984     raeburn  10185:                 $result=
                   10186:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10187:                                                     $dirpath.
1.1075.2.35  raeburn  10188:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10189:                 if ($result !~ m|^/uploaded/|) {
                   10190:                     $output .= '<span class="LC_error">'
                   10191:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10192:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10193:                                .'</span><br />';
                   10194:                     next;
                   10195:                 } else {
1.987     raeburn  10196:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10197:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10198:                 }
1.661     raeburn  10199:             }
1.1075.2.35  raeburn  10200:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   10201:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10202:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10203:             my $result =
1.1075.2.35  raeburn  10204:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10205:             if ($result !~ m|^/uploaded/|) {
                   10206:                 $output .= '<span class="LC_error">'
                   10207:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10208:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10209:                            .'</span><br />';
                   10210:                     next;
                   10211:             } else {
                   10212:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10213:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  10214:                 if ($context eq 'syllabus') {
                   10215:                     &Apache::lonnet::make_public_indefinitely($result);
                   10216:                 }
1.987     raeburn  10217:             }
1.661     raeburn  10218:         } else {
                   10219: # Save the file
                   10220:             my $target = $env{'form.embedded_item_'.$i};
                   10221:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10222:             my $dest = $fullpath.$fname;
                   10223:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10224:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10225:             my $count;
                   10226:             my $filepath = $dir_root;
1.1027    raeburn  10227:             foreach my $subdir (@parts) {
                   10228:                 $filepath .= "/$subdir";
                   10229:                 if (!-e $filepath) {
1.661     raeburn  10230:                     mkdir($filepath,0770);
                   10231:                 }
                   10232:             }
                   10233:             my $fh;
                   10234:             if (!open($fh,'>'.$dest)) {
                   10235:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10236:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10237:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10238:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10239:                            '</span><br />';
                   10240:             } else {
                   10241:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10242:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10243:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10244:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10245:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10246:                               '</span><br />';
                   10247:                 } else {
1.987     raeburn  10248:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10249:                                $url.'</span>').'<br />';
                   10250:                     unless ($context eq 'testbank') {
                   10251:                         $footer .= &mt('View embedded file: [_1]',
                   10252:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10253:                     }
                   10254:                 }
                   10255:                 close($fh);
                   10256:             }
                   10257:         }
                   10258:         if ($env{'form.embedded_ref_'.$i}) {
                   10259:             $pathchange{$i} = 1;
                   10260:         }
                   10261:     }
                   10262:     if ($output) {
                   10263:         $output = '<p>'.$output.'</p>';
                   10264:     }
                   10265:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10266:     $returnflag = 'ok';
1.1071    raeburn  10267:     my $numpathchgs = scalar(keys(%pathchange));
                   10268:     if ($numpathchgs > 0) {
1.987     raeburn  10269:         if ($context eq 'portfolio') {
                   10270:             $output .= '<p>'.&mt('or').'</p>';
                   10271:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10272:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10273:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10274:             $returnflag = 'modify_orightml';
                   10275:         }
                   10276:     }
1.1071    raeburn  10277:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10278: }
                   10279: 
                   10280: sub modify_html_form {
                   10281:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10282:     my $end = 0;
                   10283:     my $modifyform;
                   10284:     if ($context eq 'upload_embedded') {
                   10285:         return unless (ref($pathchange) eq 'HASH');
                   10286:         if ($env{'form.number_embedded_items'}) {
                   10287:             $end += $env{'form.number_embedded_items'};
                   10288:         }
                   10289:         if ($env{'form.number_pathchange_items'}) {
                   10290:             $end += $env{'form.number_pathchange_items'};
                   10291:         }
                   10292:         if ($end) {
                   10293:             for (my $i=0; $i<$end; $i++) {
                   10294:                 if ($i < $env{'form.number_embedded_items'}) {
                   10295:                     next unless($pathchange->{$i});
                   10296:                 }
                   10297:                 $modifyform .=
                   10298:                     &start_data_table_row().
                   10299:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10300:                     'checked="checked" /></td>'.
                   10301:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10302:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10303:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10304:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10305:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10306:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10307:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10308:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10309:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10310:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10311:                     &end_data_table_row();
1.1071    raeburn  10312:             }
1.987     raeburn  10313:         }
                   10314:     } else {
                   10315:         $modifyform = $pathchgtable;
                   10316:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10317:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10318:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10319:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10320:         }
                   10321:     }
                   10322:     if ($modifyform) {
1.1071    raeburn  10323:         if ($actionurl eq '/adm/dependencies') {
                   10324:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10325:         }
1.987     raeburn  10326:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10327:                '<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".
                   10328:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10329:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10330:                '</ol></p>'."\n".'<p>'.
                   10331:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10332:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10333:                &start_data_table()."\n".
                   10334:                &start_data_table_header_row().
                   10335:                '<th>'.&mt('Change?').'</th>'.
                   10336:                '<th>'.&mt('Current reference').'</th>'.
                   10337:                '<th>'.&mt('Required reference').'</th>'.
                   10338:                &end_data_table_header_row()."\n".
                   10339:                $modifyform.
                   10340:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10341:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10342:                '</form>'."\n";
                   10343:     }
                   10344:     return;
                   10345: }
                   10346: 
                   10347: sub modify_html_refs {
1.1075.2.35  raeburn  10348:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10349:     my $container;
                   10350:     if ($context eq 'portfolio') {
                   10351:         $container = $env{'form.container'};
                   10352:     } elsif ($context eq 'coursedoc') {
                   10353:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10354:     } elsif ($context eq 'manage_dependencies') {
                   10355:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10356:         $container = "/$container";
1.1075.2.35  raeburn  10357:     } elsif ($context eq 'syllabus') {
                   10358:         $container = $url;
1.987     raeburn  10359:     } else {
1.1027    raeburn  10360:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10361:     }
                   10362:     my (%allfiles,%codebase,$output,$content);
                   10363:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  10364:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  10365:         if (wantarray) {
                   10366:             return ('',0,0); 
                   10367:         } else {
                   10368:             return;
                   10369:         }
                   10370:     }
                   10371:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10372:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10373:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10374:             if (wantarray) {
                   10375:                 return ('',0,0);
                   10376:             } else {
                   10377:                 return;
                   10378:             }
                   10379:         } 
1.987     raeburn  10380:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10381:         if ($content eq '-1') {
                   10382:             if (wantarray) {
                   10383:                 return ('',0,0);
                   10384:             } else {
                   10385:                 return;
                   10386:             }
                   10387:         }
1.987     raeburn  10388:     } else {
1.1071    raeburn  10389:         unless ($container =~ /^\Q$dir_root\E/) {
                   10390:             if (wantarray) {
                   10391:                 return ('',0,0);
                   10392:             } else {
                   10393:                 return;
                   10394:             }
                   10395:         } 
1.987     raeburn  10396:         if (open(my $fh,"<$container")) {
                   10397:             $content = join('', <$fh>);
                   10398:             close($fh);
                   10399:         } else {
1.1071    raeburn  10400:             if (wantarray) {
                   10401:                 return ('',0,0);
                   10402:             } else {
                   10403:                 return;
                   10404:             }
1.987     raeburn  10405:         }
                   10406:     }
                   10407:     my ($count,$codebasecount) = (0,0);
                   10408:     my $mm = new File::MMagic;
                   10409:     my $mime_type = $mm->checktype_contents($content);
                   10410:     if ($mime_type eq 'text/html') {
                   10411:         my $parse_result = 
                   10412:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10413:                                                     \%codebase,\$content);
                   10414:         if ($parse_result eq 'ok') {
                   10415:             foreach my $i (@changes) {
                   10416:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10417:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10418:                 if ($allfiles{$ref}) {
                   10419:                     my $newname =  $orig;
                   10420:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10421:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10422:                     if ($attrib_regexp =~ /:/) {
                   10423:                         $attrib_regexp =~ s/\:/|/g;
                   10424:                     }
                   10425:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10426:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10427:                         $count += $numchg;
1.1075.2.35  raeburn  10428:                         $allfiles{$newname} = $allfiles{$ref};
1.987     raeburn  10429:                     }
                   10430:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10431:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10432:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10433:                         $codebasecount ++;
                   10434:                     }
                   10435:                 }
                   10436:             }
1.1075.2.35  raeburn  10437:             my $skiprewrites;
1.987     raeburn  10438:             if ($count || $codebasecount) {
                   10439:                 my $saveresult;
1.1071    raeburn  10440:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10441:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10442:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10443:                     if ($url eq $container) {
                   10444:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10445:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10446:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10447:                                             $fname.'</span>').'</p>';
1.987     raeburn  10448:                     } else {
                   10449:                          $output = '<p class="LC_error">'.
                   10450:                                    &mt('Error: update failed for: [_1].',
                   10451:                                    '<span class="LC_filename">'.
                   10452:                                    $container.'</span>').'</p>';
                   10453:                     }
1.1075.2.35  raeburn  10454:                     if ($context eq 'syllabus') {
                   10455:                         unless ($saveresult eq 'ok') {
                   10456:                             $skiprewrites = 1;
                   10457:                         }
                   10458:                     }
1.987     raeburn  10459:                 } else {
                   10460:                     if (open(my $fh,">$container")) {
                   10461:                         print $fh $content;
                   10462:                         close($fh);
                   10463:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10464:                                   $count,'<span class="LC_filename">'.
                   10465:                                   $container.'</span>').'</p>';
1.661     raeburn  10466:                     } else {
1.987     raeburn  10467:                          $output = '<p class="LC_error">'.
                   10468:                                    &mt('Error: could not update [_1].',
                   10469:                                    '<span class="LC_filename">'.
                   10470:                                    $container.'</span>').'</p>';
1.661     raeburn  10471:                     }
                   10472:                 }
                   10473:             }
1.1075.2.35  raeburn  10474:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10475:                 my ($actionurl,$state);
                   10476:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10477:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10478:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10479:                                               \%codebase,
                   10480:                                               {'context' => 'rewrites',
                   10481:                                                'ignore_remote_references' => 1,});
                   10482:                 if (ref($mapping) eq 'HASH') {
                   10483:                     my $rewrites = 0;
                   10484:                     foreach my $key (keys(%{$mapping})) {
                   10485:                         next if ($key =~ m{^https?://});
                   10486:                         my $ref = $mapping->{$key};
                   10487:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10488:                         my $attrib;
                   10489:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   10490:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   10491:                         }
                   10492:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10493:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10494:                             $rewrites += $numchg;
                   10495:                         }
                   10496:                     }
                   10497:                     if ($rewrites) {
                   10498:                         my $saveresult;
                   10499:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10500:                         if ($url eq $container) {
                   10501:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   10502:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   10503:                                             $count,'<span class="LC_filename">'.
                   10504:                                             $fname.'</span>').'</p>';
                   10505:                         } else {
                   10506:                             $output .= '<p class="LC_error">'.
                   10507:                                        &mt('Error: could not update links in [_1].',
                   10508:                                        '<span class="LC_filename">'.
                   10509:                                        $container.'</span>').'</p>';
                   10510: 
                   10511:                         }
                   10512:                     }
                   10513:                 }
                   10514:             }
1.987     raeburn  10515:         } else {
                   10516:             &logthis('Failed to parse '.$container.
                   10517:                      ' to modify references: '.$parse_result);
1.661     raeburn  10518:         }
                   10519:     }
1.1071    raeburn  10520:     if (wantarray) {
                   10521:         return ($output,$count,$codebasecount);
                   10522:     } else {
                   10523:         return $output;
                   10524:     }
1.661     raeburn  10525: }
                   10526: 
                   10527: sub check_for_existing {
                   10528:     my ($path,$fname,$element) = @_;
                   10529:     my ($state,$msg);
                   10530:     if (-d $path.'/'.$fname) {
                   10531:         $state = 'exists';
                   10532:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10533:     } elsif (-e $path.'/'.$fname) {
                   10534:         $state = 'exists';
                   10535:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10536:     }
                   10537:     if ($state eq 'exists') {
                   10538:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10539:     }
                   10540:     return ($state,$msg);
                   10541: }
                   10542: 
                   10543: sub check_for_upload {
                   10544:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10545:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10546:     my $filesize = length($env{'form.'.$element});
                   10547:     if (!$filesize) {
                   10548:         my $msg = '<span class="LC_error">'.
                   10549:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10550:                       '<span class="LC_filename">'.$fname.'</span>',
                   10551:                       $filesize).'<br />'.
1.1007    raeburn  10552:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10553:                   '</span>';
                   10554:         return ('zero_bytes',$msg);
                   10555:     }
                   10556:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10557:     my $getpropath = 1;
1.1021    raeburn  10558:     my ($dirlistref,$listerror) =
                   10559:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10560:     my $found_file = 0;
                   10561:     my $locked_file = 0;
1.991     raeburn  10562:     my @lockers;
                   10563:     my $navmap;
                   10564:     if ($env{'request.course.id'}) {
                   10565:         $navmap = Apache::lonnavmaps::navmap->new();
                   10566:     }
1.1021    raeburn  10567:     if (ref($dirlistref) eq 'ARRAY') {
                   10568:         foreach my $line (@{$dirlistref}) {
                   10569:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10570:             if ($file_name eq $fname){
                   10571:                 $file_name = $path.$file_name;
                   10572:                 if ($group ne '') {
                   10573:                     $file_name = $group.$file_name;
                   10574:                 }
                   10575:                 $found_file = 1;
                   10576:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10577:                     foreach my $lock (@lockers) {
                   10578:                         if (ref($lock) eq 'ARRAY') {
                   10579:                             my ($symb,$crsid) = @{$lock};
                   10580:                             if ($crsid eq $env{'request.course.id'}) {
                   10581:                                 if (ref($navmap)) {
                   10582:                                     my $res = $navmap->getBySymb($symb);
                   10583:                                     foreach my $part (@{$res->parts()}) { 
                   10584:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10585:                                         unless (($slot_status == $res->RESERVED) ||
                   10586:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10587:                                             $locked_file = 1;
                   10588:                                         }
1.991     raeburn  10589:                                     }
1.1021    raeburn  10590:                                 } else {
                   10591:                                     $locked_file = 1;
1.991     raeburn  10592:                                 }
                   10593:                             } else {
                   10594:                                 $locked_file = 1;
                   10595:                             }
                   10596:                         }
1.1021    raeburn  10597:                    }
                   10598:                 } else {
                   10599:                     my @info = split(/\&/,$rest);
                   10600:                     my $currsize = $info[6]/1000;
                   10601:                     if ($currsize < $filesize) {
                   10602:                         my $extra = $filesize - $currsize;
                   10603:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10604:                             my $msg = '<span class="LC_error">'.
                   10605:                                       &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.',
                   10606:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10607:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10608:                                                    $disk_quota,$current_disk_usage);
                   10609:                             return ('will_exceed_quota',$msg);
                   10610:                         }
1.984     raeburn  10611:                     }
                   10612:                 }
1.661     raeburn  10613:             }
                   10614:         }
                   10615:     }
                   10616:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10617:         my $msg = '<span class="LC_error">'.
                   10618:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10619:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10620:         return ('will_exceed_quota',$msg);
                   10621:     } elsif ($found_file) {
                   10622:         if ($locked_file) {
                   10623:             my $msg = '<span class="LC_error">';
                   10624:             $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>');
                   10625:             $msg .= '</span><br />';
                   10626:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10627:             return ('file_locked',$msg);
                   10628:         } else {
                   10629:             my $msg = '<span class="LC_error">';
1.984     raeburn  10630:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.661     raeburn  10631:             $msg .= '</span>';
1.984     raeburn  10632:             return ('existingfile',$msg);
1.661     raeburn  10633:         }
                   10634:     }
                   10635: }
                   10636: 
1.987     raeburn  10637: sub check_for_traversal {
                   10638:     my ($path,$url,$toplevel) = @_;
                   10639:     my @parts=split(/\//,$path);
                   10640:     my $cleanpath;
                   10641:     my $fullpath = $url;
                   10642:     for (my $i=0;$i<@parts;$i++) {
                   10643:         next if ($parts[$i] eq '.');
                   10644:         if ($parts[$i] eq '..') {
                   10645:             $fullpath =~ s{([^/]+/)$}{};
                   10646:         } else {
                   10647:             $fullpath .= $parts[$i].'/';
                   10648:         }
                   10649:     }
                   10650:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10651:         $cleanpath = $1;
                   10652:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10653:         my $curr_toprel = $1;
                   10654:         my @parts = split(/\//,$curr_toprel);
                   10655:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10656:         my @urlparts = split(/\//,$url_toprel);
                   10657:         my $doubledots;
                   10658:         my $startdiff = -1;
                   10659:         for (my $i=0; $i<@urlparts; $i++) {
                   10660:             if ($startdiff == -1) {
                   10661:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10662:                     $startdiff = $i;
                   10663:                     $doubledots .= '../';
                   10664:                 }
                   10665:             } else {
                   10666:                 $doubledots .= '../';
                   10667:             }
                   10668:         }
                   10669:         if ($startdiff > -1) {
                   10670:             $cleanpath = $doubledots;
                   10671:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10672:                 $cleanpath .= $parts[$i].'/';
                   10673:             }
                   10674:         }
                   10675:     }
                   10676:     $cleanpath =~ s{(/)$}{};
                   10677:     return $cleanpath;
                   10678: }
1.31      albertel 10679: 
1.1053    raeburn  10680: sub is_archive_file {
                   10681:     my ($mimetype) = @_;
                   10682:     if (($mimetype eq 'application/octet-stream') ||
                   10683:         ($mimetype eq 'application/x-stuffit') ||
                   10684:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10685:         return 1;
                   10686:     }
                   10687:     return;
                   10688: }
                   10689: 
                   10690: sub decompress_form {
1.1065    raeburn  10691:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10692:     my %lt = &Apache::lonlocal::texthash (
                   10693:         this => 'This file is an archive file.',
1.1067    raeburn  10694:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10695:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10696:         youm => 'You may wish to extract its contents.',
                   10697:         extr => 'Extract contents',
1.1067    raeburn  10698:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10699:         proa => 'Process automatically?',
1.1053    raeburn  10700:         yes  => 'Yes',
                   10701:         no   => 'No',
1.1067    raeburn  10702:         fold => 'Title for folder containing movie',
                   10703:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10704:     );
1.1065    raeburn  10705:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10706:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10707:     my $info = &list_archive_contents($fileloc,\@paths);
                   10708:     if (@paths) {
                   10709:         foreach my $path (@paths) {
                   10710:             $path =~ s{^/}{};
1.1067    raeburn  10711:             if ($path =~ m{^([^/]+)/$}) {
                   10712:                 $topdir = $1;
                   10713:             }
1.1065    raeburn  10714:             if ($path =~ m{^([^/]+)/}) {
                   10715:                 $toplevel{$1} = $path;
                   10716:             } else {
                   10717:                 $toplevel{$path} = $path;
                   10718:             }
                   10719:         }
                   10720:     }
1.1067    raeburn  10721:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
                   10722:         my @camtasia = ("$topdir/","$topdir/index.html",
                   10723:                         "$topdir/media/",
                   10724:                         "$topdir/media/$topdir.mp4",
                   10725:                         "$topdir/media/FirstFrame.png",
                   10726:                         "$topdir/media/player.swf",
                   10727:                         "$topdir/media/swfobject.js",
                   10728:                         "$topdir/media/expressInstall.swf");
                   10729:         my @diffs = &compare_arrays(\@paths,\@camtasia);
                   10730:         if (@diffs == 0) {
                   10731:             $is_camtasia = 1;
                   10732:         }
                   10733:     }
                   10734:     my $output;
                   10735:     if ($is_camtasia) {
                   10736:         $output = <<"ENDCAM";
                   10737: <script type="text/javascript" language="Javascript">
                   10738: // <![CDATA[
                   10739: 
                   10740: function camtasiaToggle() {
                   10741:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   10742:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
                   10743:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
                   10744: 
                   10745:                 document.getElementById('camtasia_titles').style.display='block';
                   10746:             } else {
                   10747:                 document.getElementById('camtasia_titles').style.display='none';
                   10748:             }
                   10749:         }
                   10750:     }
                   10751:     return;
                   10752: }
                   10753: 
                   10754: // ]]>
                   10755: </script>
                   10756: <p>$lt{'camt'}</p>
                   10757: ENDCAM
1.1065    raeburn  10758:     } else {
1.1067    raeburn  10759:         $output = '<p>'.$lt{'this'};
                   10760:         if ($info eq '') {
                   10761:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   10762:         } else {
                   10763:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   10764:                        '<div><pre>'.$info.'</pre></div>';
                   10765:         }
1.1065    raeburn  10766:     }
1.1067    raeburn  10767:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  10768:     my $duplicates;
                   10769:     my $num = 0;
                   10770:     if (ref($dirlist) eq 'ARRAY') {
                   10771:         foreach my $item (@{$dirlist}) {
                   10772:             if (ref($item) eq 'ARRAY') {
                   10773:                 if (exists($toplevel{$item->[0]})) {
                   10774:                     $duplicates .= 
                   10775:                         &start_data_table_row().
                   10776:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10777:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   10778:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10779:                         'value="1" />'.&mt('Yes').'</label>'.
                   10780:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   10781:                         '<td>'.$item->[0].'</td>';
                   10782:                     if ($item->[2]) {
                   10783:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   10784:                     } else {
                   10785:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   10786:                     }
                   10787:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   10788:                                    '<td>'.
                   10789:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   10790:                                    '</td>'.
                   10791:                                    &end_data_table_row();
                   10792:                     $num ++;
                   10793:                 }
                   10794:             }
                   10795:         }
                   10796:     }
                   10797:     my $itemcount;
                   10798:     if (@paths > 0) {
                   10799:         $itemcount = scalar(@paths);
                   10800:     } else {
                   10801:         $itemcount = 1;
                   10802:     }
1.1067    raeburn  10803:     if ($is_camtasia) {
                   10804:         $output .= $lt{'auto'}.'<br />'.
                   10805:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
                   10806:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
                   10807:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   10808:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   10809:                    $lt{'no'}.'</label></span><br />'.
                   10810:                    '<div id="camtasia_titles" style="display:block">'.
                   10811:                    &Apache::lonhtmlcommon::start_pick_box().
                   10812:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   10813:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   10814:                    &Apache::lonhtmlcommon::row_closure().
                   10815:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   10816:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   10817:                    &Apache::lonhtmlcommon::row_closure(1).
                   10818:                    &Apache::lonhtmlcommon::end_pick_box().
                   10819:                    '</div>';
                   10820:     }
1.1065    raeburn  10821:     $output .= 
                   10822:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  10823:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   10824:         "\n";
1.1065    raeburn  10825:     if ($duplicates ne '') {
                   10826:         $output .= '<p><span class="LC_warning">'.
                   10827:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   10828:                    &start_data_table().
                   10829:                    &start_data_table_header_row().
                   10830:                    '<th>'.&mt('Overwrite?').'</th>'.
                   10831:                    '<th>'.&mt('Name').'</th>'.
                   10832:                    '<th>'.&mt('Type').'</th>'.
                   10833:                    '<th>'.&mt('Size').'</th>'.
                   10834:                    '<th>'.&mt('Last modified').'</th>'.
                   10835:                    &end_data_table_header_row().
                   10836:                    $duplicates.
                   10837:                    &end_data_table().
                   10838:                    '</p>';
                   10839:     }
1.1067    raeburn  10840:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  10841:     if (ref($hiddenelements) eq 'HASH') {
                   10842:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   10843:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   10844:         }
                   10845:     }
                   10846:     $output .= <<"END";
1.1067    raeburn  10847: <br />
1.1053    raeburn  10848: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   10849: </form>
                   10850: $noextract
                   10851: END
                   10852:     return $output;
                   10853: }
                   10854: 
1.1065    raeburn  10855: sub decompression_utility {
                   10856:     my ($program) = @_;
                   10857:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   10858:     my $location;
                   10859:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   10860:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   10861:                          '/usr/sbin/') {
                   10862:             if (-x $dir.$program) {
                   10863:                 $location = $dir.$program;
                   10864:                 last;
                   10865:             }
                   10866:         }
                   10867:     }
                   10868:     return $location;
                   10869: }
                   10870: 
                   10871: sub list_archive_contents {
                   10872:     my ($file,$pathsref) = @_;
                   10873:     my (@cmd,$output);
                   10874:     my $needsregexp;
                   10875:     if ($file =~ /\.zip$/) {
                   10876:         @cmd = (&decompression_utility('unzip'),"-l");
                   10877:         $needsregexp = 1;
                   10878:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   10879:              ($file =~ /\.tgz$/)) {
                   10880:         @cmd = (&decompression_utility('tar'),"-ztf");
                   10881:     } elsif ($file =~ /\.tar\.bz2$/) {
                   10882:         @cmd = (&decompression_utility('tar'),"-jtf");
                   10883:     } elsif ($file =~ m|\.tar$|) {
                   10884:         @cmd = (&decompression_utility('tar'),"-tf");
                   10885:     }
                   10886:     if (@cmd) {
                   10887:         undef($!);
                   10888:         undef($@);
                   10889:         if (open(my $fh,"-|", @cmd, $file)) {
                   10890:             while (my $line = <$fh>) {
                   10891:                 $output .= $line;
                   10892:                 chomp($line);
                   10893:                 my $item;
                   10894:                 if ($needsregexp) {
                   10895:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   10896:                 } else {
                   10897:                     $item = $line;
                   10898:                 }
                   10899:                 if ($item ne '') {
                   10900:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   10901:                         push(@{$pathsref},$item);
                   10902:                     } 
                   10903:                 }
                   10904:             }
                   10905:             close($fh);
                   10906:         }
                   10907:     }
                   10908:     return $output;
                   10909: }
                   10910: 
1.1053    raeburn  10911: sub decompress_uploaded_file {
                   10912:     my ($file,$dir) = @_;
                   10913:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   10914:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   10915:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   10916:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   10917:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   10918:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   10919:     my $decompressed = $env{'cgi.decompressed'};
                   10920:     &Apache::lonnet::delenv('cgi.file');
                   10921:     &Apache::lonnet::delenv('cgi.dir');
                   10922:     &Apache::lonnet::delenv('cgi.decompressed');
                   10923:     return ($decompressed,$result);
                   10924: }
                   10925: 
1.1055    raeburn  10926: sub process_decompression {
                   10927:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   10928:     my ($dir,$error,$warning,$output);
                   10929:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
1.1075.2.34  raeburn  10930:         $error = &mt('Filename not a supported archive file type.').
                   10931:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  10932:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   10933:     } else {
                   10934:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   10935:         if ($docuhome eq 'no_host') {
                   10936:             $error = &mt('Could not determine home server for course.');
                   10937:         } else {
                   10938:             my @ids=&Apache::lonnet::current_machine_ids();
                   10939:             my $currdir = "$dir_root/$destination";
                   10940:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   10941:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   10942:                        "$dir_root/$destination";
                   10943:             } else {
                   10944:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   10945:                        "$dir_root/$docudom/$docuname/$destination";
                   10946:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   10947:                     $error = &mt('Archive file not found.');
                   10948:                 }
                   10949:             }
1.1065    raeburn  10950:             my (@to_overwrite,@to_skip);
                   10951:             if ($env{'form.archive_overwrite_total'} > 0) {
                   10952:                 my $total = $env{'form.archive_overwrite_total'};
                   10953:                 for (my $i=0; $i<$total; $i++) {
                   10954:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   10955:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   10956:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   10957:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   10958:                     }
                   10959:                 }
                   10960:             }
                   10961:             my $numskip = scalar(@to_skip);
                   10962:             if (($numskip > 0) && 
                   10963:                 ($numskip == $env{'form.archive_itemcount'})) {
                   10964:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   10965:             } elsif ($dir eq '') {
1.1055    raeburn  10966:                 $error = &mt('Directory containing archive file unavailable.');
                   10967:             } elsif (!$error) {
1.1065    raeburn  10968:                 my ($decompressed,$display);
                   10969:                 if ($numskip > 0) {
                   10970:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   10971:                     mkdir("$dir/$tempdir",0755);
                   10972:                     system("mv $dir/$file $dir/$tempdir/$file");
                   10973:                     ($decompressed,$display) = 
                   10974:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   10975:                     foreach my $item (@to_skip) {
                   10976:                         if (($item ne '') && ($item !~ /\.\./)) {
                   10977:                             if (-f "$dir/$tempdir/$item") { 
                   10978:                                 unlink("$dir/$tempdir/$item");
                   10979:                             } elsif (-d "$dir/$tempdir/$item") {
                   10980:                                 system("rm -rf $dir/$tempdir/$item");
                   10981:                             }
                   10982:                         }
                   10983:                     }
                   10984:                     system("mv $dir/$tempdir/* $dir");
                   10985:                     rmdir("$dir/$tempdir");   
                   10986:                 } else {
                   10987:                     ($decompressed,$display) = 
                   10988:                         &decompress_uploaded_file($file,$dir);
                   10989:                 }
1.1055    raeburn  10990:                 if ($decompressed eq 'ok') {
1.1065    raeburn  10991:                     $output = '<p class="LC_info">'.
                   10992:                               &mt('Files extracted successfully from archive.').
                   10993:                               '</p>'."\n";
1.1055    raeburn  10994:                     my ($warning,$result,@contents);
                   10995:                     my ($newdirlistref,$newlisterror) =
                   10996:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   10997:                                                  $docuname,1);
                   10998:                     my (%is_dir,%changes,@newitems);
                   10999:                     my $dirptr = 16384;
1.1065    raeburn  11000:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11001:                         foreach my $dir_line (@{$newdirlistref}) {
                   11002:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11003:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11004:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11005:                                 push(@newitems,$item);
                   11006:                                 if ($dirptr&$testdir) {
                   11007:                                     $is_dir{$item} = 1;
                   11008:                                 }
                   11009:                                 $changes{$item} = 1;
                   11010:                             }
                   11011:                         }
                   11012:                     }
                   11013:                     if (keys(%changes) > 0) {
                   11014:                         foreach my $item (sort(@newitems)) {
                   11015:                             if ($changes{$item}) {
                   11016:                                 push(@contents,$item);
                   11017:                             }
                   11018:                         }
                   11019:                     }
                   11020:                     if (@contents > 0) {
1.1067    raeburn  11021:                         my $wantform;
                   11022:                         unless ($env{'form.autoextract_camtasia'}) {
                   11023:                             $wantform = 1;
                   11024:                         }
1.1056    raeburn  11025:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11026:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11027:                                                                 $currdir,\%is_dir,
                   11028:                                                                 \%children,\%parent,
1.1056    raeburn  11029:                                                                 \@contents,\%dirorder,
                   11030:                                                                 \%titles,$wantform);
1.1055    raeburn  11031:                         if ($datatable ne '') {
                   11032:                             $output .= &archive_options_form('decompressed',$datatable,
                   11033:                                                              $count,$hiddenelem);
1.1065    raeburn  11034:                             my $startcount = 6;
1.1055    raeburn  11035:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11036:                                                            \%titles,\%children);
1.1055    raeburn  11037:                         }
1.1067    raeburn  11038:                         if ($env{'form.autoextract_camtasia'}) {
                   11039:                             my %displayed;
                   11040:                             my $total = 1;
                   11041:                             $env{'form.archive_directory'} = [];
                   11042:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11043:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11044:                                 $path =~ s{/$}{};
                   11045:                                 my $item;
                   11046:                                 if ($path ne '') {
                   11047:                                     $item = "$path/$titles{$i}";
                   11048:                                 } else {
                   11049:                                     $item = $titles{$i};
                   11050:                                 }
                   11051:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11052:                                 if ($item eq $contents[0]) {
                   11053:                                     push(@{$env{'form.archive_directory'}},$i);
                   11054:                                     $env{'form.archive_'.$i} = 'display';
                   11055:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11056:                                     $displayed{'folder'} = $i;
                   11057:                                 } elsif ($item eq "$contents[0]/index.html") {
                   11058:                                     $env{'form.archive_'.$i} = 'display';
                   11059:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11060:                                     $displayed{'web'} = $i;
                   11061:                                 } else {
                   11062:                                     if ($item eq "$contents[0]/media") {
                   11063:                                         push(@{$env{'form.archive_directory'}},$i);
                   11064:                                     }
                   11065:                                     $env{'form.archive_'.$i} = 'dependency';
                   11066:                                 }
                   11067:                                 $total ++;
                   11068:                             }
                   11069:                             for (my $i=1; $i<$total; $i++) {
                   11070:                                 next if ($i == $displayed{'web'});
                   11071:                                 next if ($i == $displayed{'folder'});
                   11072:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11073:                             }
                   11074:                             $env{'form.phase'} = 'decompress_cleanup';
                   11075:                             $env{'form.archivedelete'} = 1;
                   11076:                             $env{'form.archive_count'} = $total-1;
                   11077:                             $output .=
                   11078:                                 &process_extracted_files('coursedocs',$docudom,
                   11079:                                                          $docuname,$destination,
                   11080:                                                          $dir_root,$hiddenelem);
                   11081:                         }
1.1055    raeburn  11082:                     } else {
                   11083:                         $warning = &mt('No new items extracted from archive file.');
                   11084:                     }
                   11085:                 } else {
                   11086:                     $output = $display;
                   11087:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11088:                 }
                   11089:             }
                   11090:         }
                   11091:     }
                   11092:     if ($error) {
                   11093:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11094:                    $error.'</p>'."\n";
                   11095:     }
                   11096:     if ($warning) {
                   11097:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11098:     }
                   11099:     return $output;
                   11100: }
                   11101: 
                   11102: sub get_extracted {
1.1056    raeburn  11103:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11104:         $titles,$wantform) = @_;
1.1055    raeburn  11105:     my $count = 0;
                   11106:     my $depth = 0;
                   11107:     my $datatable;
1.1056    raeburn  11108:     my @hierarchy;
1.1055    raeburn  11109:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11110:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11111:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11112:     foreach my $item (@{$contents}) {
                   11113:         $count ++;
1.1056    raeburn  11114:         @{$dirorder->{$count}} = @hierarchy;
                   11115:         $titles->{$count} = $item;
1.1055    raeburn  11116:         &archive_hierarchy($depth,$count,$parent,$children);
                   11117:         if ($wantform) {
                   11118:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11119:                                        $currdir,$depth,$count);
                   11120:         }
                   11121:         if ($is_dir->{$item}) {
                   11122:             $depth ++;
1.1056    raeburn  11123:             push(@hierarchy,$count);
                   11124:             $parent->{$depth} = $count;
1.1055    raeburn  11125:             $datatable .=
                   11126:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11127:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11128:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11129:             $depth --;
1.1056    raeburn  11130:             pop(@hierarchy);
1.1055    raeburn  11131:         }
                   11132:     }
                   11133:     return ($count,$datatable);
                   11134: }
                   11135: 
                   11136: sub recurse_extracted_archive {
1.1056    raeburn  11137:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11138:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11139:     my $result='';
1.1056    raeburn  11140:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11141:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11142:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11143:         return $result;
                   11144:     }
                   11145:     my $dirptr = 16384;
                   11146:     my ($newdirlistref,$newlisterror) =
                   11147:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11148:     if (ref($newdirlistref) eq 'ARRAY') {
                   11149:         foreach my $dir_line (@{$newdirlistref}) {
                   11150:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11151:             unless ($item =~ /^\.+$/) {
                   11152:                 $$count ++;
1.1056    raeburn  11153:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11154:                 $titles->{$$count} = $item;
1.1055    raeburn  11155:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11156: 
1.1055    raeburn  11157:                 my $is_dir;
                   11158:                 if ($dirptr&$testdir) {
                   11159:                     $is_dir = 1;
                   11160:                 }
                   11161:                 if ($wantform) {
                   11162:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11163:                 }
                   11164:                 if ($is_dir) {
                   11165:                     $$depth ++;
1.1056    raeburn  11166:                     push(@{$hierarchy},$$count);
                   11167:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11168:                     $result .=
                   11169:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11170:                                                    $docuname,$depth,$count,
1.1056    raeburn  11171:                                                    $hierarchy,$dirorder,$children,
                   11172:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11173:                     $$depth --;
1.1056    raeburn  11174:                     pop(@{$hierarchy});
1.1055    raeburn  11175:                 }
                   11176:             }
                   11177:         }
                   11178:     }
                   11179:     return $result;
                   11180: }
                   11181: 
                   11182: sub archive_hierarchy {
                   11183:     my ($depth,$count,$parent,$children) =@_;
                   11184:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11185:         if (exists($parent->{$depth})) {
                   11186:              $children->{$parent->{$depth}} .= $count.':';
                   11187:         }
                   11188:     }
                   11189:     return;
                   11190: }
                   11191: 
                   11192: sub archive_row {
                   11193:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11194:     my ($name) = ($item =~ m{([^/]+)$});
                   11195:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11196:                                        'display'    => 'Add as file',
1.1055    raeburn  11197:                                        'dependency' => 'Include as dependency',
                   11198:                                        'discard'    => 'Discard',
                   11199:                                       );
                   11200:     if ($is_dir) {
1.1059    raeburn  11201:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11202:     }
1.1056    raeburn  11203:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11204:     my $offset = 0;
1.1055    raeburn  11205:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11206:         $offset ++;
1.1065    raeburn  11207:         if ($action ne 'display') {
                   11208:             $offset ++;
                   11209:         }  
1.1055    raeburn  11210:         $output .= '<td><span class="LC_nobreak">'.
                   11211:                    '<label><input type="radio" name="archive_'.$count.
                   11212:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11213:         my $text = $choices{$action};
                   11214:         if ($is_dir) {
                   11215:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11216:             if ($action eq 'display') {
1.1059    raeburn  11217:                 $text = &mt('Add as folder');
1.1055    raeburn  11218:             }
1.1056    raeburn  11219:         } else {
                   11220:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11221: 
                   11222:         }
                   11223:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11224:         if ($action eq 'dependency') {
                   11225:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11226:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11227:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11228:                        '<option value=""></option>'."\n".
                   11229:                        '</select>'."\n".
                   11230:                        '</div>';
1.1059    raeburn  11231:         } elsif ($action eq 'display') {
                   11232:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11233:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11234:                        '</div>';
1.1055    raeburn  11235:         }
1.1056    raeburn  11236:         $output .= '</td>';
1.1055    raeburn  11237:     }
                   11238:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11239:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11240:     for (my $i=0; $i<$depth; $i++) {
                   11241:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11242:     }
                   11243:     if ($is_dir) {
                   11244:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11245:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11246:     } else {
                   11247:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11248:     }
                   11249:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11250:                &end_data_table_row();
                   11251:     return $output;
                   11252: }
                   11253: 
                   11254: sub archive_options_form {
1.1065    raeburn  11255:     my ($form,$display,$count,$hiddenelem) = @_;
                   11256:     my %lt = &Apache::lonlocal::texthash(
                   11257:                perm => 'Permanently remove archive file?',
                   11258:                hows => 'How should each extracted item be incorporated in the course?',
                   11259:                cont => 'Content actions for all',
                   11260:                addf => 'Add as folder/file',
                   11261:                incd => 'Include as dependency for a displayed file',
                   11262:                disc => 'Discard',
                   11263:                no   => 'No',
                   11264:                yes  => 'Yes',
                   11265:                save => 'Save',
                   11266:     );
                   11267:     my $output = <<"END";
                   11268: <form name="$form" method="post" action="">
                   11269: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11270: <label>
                   11271:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11272: </label>
                   11273: &nbsp;
                   11274: <label>
                   11275:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11276: </span>
                   11277: </p>
                   11278: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11279: <br />$lt{'hows'}
                   11280: <div class="LC_columnSection">
                   11281:   <fieldset>
                   11282:     <legend>$lt{'cont'}</legend>
                   11283:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11284:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11285:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11286:   </fieldset>
                   11287: </div>
                   11288: END
                   11289:     return $output.
1.1055    raeburn  11290:            &start_data_table()."\n".
1.1065    raeburn  11291:            $display."\n".
1.1055    raeburn  11292:            &end_data_table()."\n".
                   11293:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11294:            $hiddenelem.
1.1065    raeburn  11295:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11296:            '</form>';
                   11297: }
                   11298: 
                   11299: sub archive_javascript {
1.1056    raeburn  11300:     my ($startcount,$numitems,$titles,$children) = @_;
                   11301:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11302:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11303:     my $scripttag = <<START;
                   11304: <script type="text/javascript">
                   11305: // <![CDATA[
                   11306: 
                   11307: function checkAll(form,prefix) {
                   11308:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11309:     for (var i=0; i < form.elements.length; i++) {
                   11310:         var id = form.elements[i].id;
                   11311:         if ((id != '') && (id != undefined)) {
                   11312:             if (idstr.test(id)) {
                   11313:                 if (form.elements[i].type == 'radio') {
                   11314:                     form.elements[i].checked = true;
1.1056    raeburn  11315:                     var nostart = i-$startcount;
1.1059    raeburn  11316:                     var offset = nostart%7;
                   11317:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11318:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11319:                 }
                   11320:             }
                   11321:         }
                   11322:     }
                   11323: }
                   11324: 
                   11325: function propagateCheck(form,count) {
                   11326:     if (count > 0) {
1.1059    raeburn  11327:         var startelement = $startcount + ((count-1) * 7);
                   11328:         for (var j=1; j<6; j++) {
                   11329:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11330:                 var item = startelement + j; 
                   11331:                 if (form.elements[item].type == 'radio') {
                   11332:                     if (form.elements[item].checked) {
                   11333:                         containerCheck(form,count,j);
                   11334:                         break;
                   11335:                     }
1.1055    raeburn  11336:                 }
                   11337:             }
                   11338:         }
                   11339:     }
                   11340: }
                   11341: 
                   11342: numitems = $numitems
1.1056    raeburn  11343: var titles = new Array(numitems);
                   11344: var parents = new Array(numitems);
1.1055    raeburn  11345: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11346:     parents[i] = new Array;
1.1055    raeburn  11347: }
1.1059    raeburn  11348: var maintitle = '$maintitle';
1.1055    raeburn  11349: 
                   11350: START
                   11351: 
1.1056    raeburn  11352:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11353:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11354:         for (my $i=0; $i<@contents; $i ++) {
                   11355:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11356:         }
                   11357:     }
                   11358: 
1.1056    raeburn  11359:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11360:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11361:     }
                   11362: 
1.1055    raeburn  11363:     $scripttag .= <<END;
                   11364: 
                   11365: function containerCheck(form,count,offset) {
                   11366:     if (count > 0) {
1.1056    raeburn  11367:         dependencyCheck(form,count,offset);
1.1059    raeburn  11368:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11369:         form.elements[item].checked = true;
                   11370:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11371:             if (parents[count].length > 0) {
                   11372:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11373:                     containerCheck(form,parents[count][j],offset);
                   11374:                 }
                   11375:             }
                   11376:         }
                   11377:     }
                   11378: }
                   11379: 
                   11380: function dependencyCheck(form,count,offset) {
                   11381:     if (count > 0) {
1.1059    raeburn  11382:         var chosen = (offset+$startcount)+7*(count-1);
                   11383:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11384:         var currtype = form.elements[depitem].type;
                   11385:         if (form.elements[chosen].value == 'dependency') {
                   11386:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11387:             form.elements[depitem].options.length = 0;
                   11388:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  11389:             for (var i=1; i<=numitems; i++) {
                   11390:                 if (i == count) {
                   11391:                     continue;
                   11392:                 }
1.1059    raeburn  11393:                 var startelement = $startcount + (i-1) * 7;
                   11394:                 for (var j=1; j<6; j++) {
                   11395:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11396:                         var item = startelement + j;
                   11397:                         if (form.elements[item].type == 'radio') {
                   11398:                             if (form.elements[item].checked) {
                   11399:                                 if (form.elements[item].value == 'display') {
                   11400:                                     var n = form.elements[depitem].options.length;
                   11401:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11402:                                 }
                   11403:                             }
                   11404:                         }
                   11405:                     }
                   11406:                 }
                   11407:             }
                   11408:         } else {
                   11409:             document.getElementById('arc_depon_'+count).style.display='none';
                   11410:             form.elements[depitem].options.length = 0;
                   11411:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11412:         }
1.1059    raeburn  11413:         titleCheck(form,count,offset);
1.1056    raeburn  11414:     }
                   11415: }
                   11416: 
                   11417: function propagateSelect(form,count,offset) {
                   11418:     if (count > 0) {
1.1065    raeburn  11419:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11420:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11421:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11422:             if (parents[count].length > 0) {
                   11423:                 for (var j=0; j<parents[count].length; j++) {
                   11424:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11425:                 }
                   11426:             }
                   11427:         }
                   11428:     }
                   11429: }
1.1056    raeburn  11430: 
                   11431: function containerSelect(form,count,offset,picked) {
                   11432:     if (count > 0) {
1.1065    raeburn  11433:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11434:         if (form.elements[item].type == 'radio') {
                   11435:             if (form.elements[item].value == 'dependency') {
                   11436:                 if (form.elements[item+1].type == 'select-one') {
                   11437:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11438:                         if (form.elements[item+1].options[i].value == picked) {
                   11439:                             form.elements[item+1].selectedIndex = i;
                   11440:                             break;
                   11441:                         }
                   11442:                     }
                   11443:                 }
                   11444:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11445:                     if (parents[count].length > 0) {
                   11446:                         for (var j=0; j<parents[count].length; j++) {
                   11447:                             containerSelect(form,parents[count][j],offset,picked);
                   11448:                         }
                   11449:                     }
                   11450:                 }
                   11451:             }
                   11452:         }
                   11453:     }
                   11454: }
                   11455: 
1.1059    raeburn  11456: function titleCheck(form,count,offset) {
                   11457:     if (count > 0) {
                   11458:         var chosen = (offset+$startcount)+7*(count-1);
                   11459:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11460:         var currtype = form.elements[depitem].type;
                   11461:         if (form.elements[chosen].value == 'display') {
                   11462:             document.getElementById('arc_title_'+count).style.display='block';
                   11463:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11464:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11465:             }
                   11466:         } else {
                   11467:             document.getElementById('arc_title_'+count).style.display='none';
                   11468:             if (currtype == 'text') { 
                   11469:                 document.getElementById('archive_title_'+count).value='';
                   11470:             }
                   11471:         }
                   11472:     }
                   11473:     return;
                   11474: }
                   11475: 
1.1055    raeburn  11476: // ]]>
                   11477: </script>
                   11478: END
                   11479:     return $scripttag;
                   11480: }
                   11481: 
                   11482: sub process_extracted_files {
1.1067    raeburn  11483:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11484:     my $numitems = $env{'form.archive_count'};
                   11485:     return unless ($numitems);
                   11486:     my @ids=&Apache::lonnet::current_machine_ids();
                   11487:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11488:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11489:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11490:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11491:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11492:         $pathtocheck = "$dir_root/$destination";
                   11493:         $dir = $dir_root;
                   11494:         $ishome = 1;
                   11495:     } else {
                   11496:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11497:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11498:         $dir = "$dir_root/$docudom/$docuname";    
                   11499:     }
                   11500:     my $currdir = "$dir_root/$destination";
                   11501:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11502:     if ($env{'form.folderpath'}) {
                   11503:         my @items = split('&',$env{'form.folderpath'});
                   11504:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  11505:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11506:             $containers{'0'}='page';
                   11507:         } else {
                   11508:             $containers{'0'}='sequence';
                   11509:         }
1.1055    raeburn  11510:     }
                   11511:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11512:     if ($numitems) {
                   11513:         for (my $i=1; $i<=$numitems; $i++) {
                   11514:             my $path = $env{'form.archive_content_'.$i};
                   11515:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11516:                 my $item = $1;
                   11517:                 $toplevelitems{$item} = $i;
                   11518:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11519:                     $is_dir{$item} = 1;
                   11520:                 }
                   11521:             }
                   11522:         }
                   11523:     }
1.1067    raeburn  11524:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11525:     if (keys(%toplevelitems) > 0) {
                   11526:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11527:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11528:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11529:     }
1.1066    raeburn  11530:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11531:     if ($numitems) {
                   11532:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  11533:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11534:             my $path = $env{'form.archive_content_'.$i};
                   11535:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11536:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11537:                     if ($prefix ne '' && $path ne '') {
                   11538:                         if (-e $prefix.$path) {
1.1066    raeburn  11539:                             if ((@archdirs > 0) && 
                   11540:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11541:                                 $todeletedir{$prefix.$path} = 1;
                   11542:                             } else {
                   11543:                                 $todelete{$prefix.$path} = 1;
                   11544:                             }
1.1055    raeburn  11545:                         }
                   11546:                     }
                   11547:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11548:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11549:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11550:                     $docstitle = $env{'form.archive_title_'.$i};
                   11551:                     if ($docstitle eq '') {
                   11552:                         $docstitle = $title;
                   11553:                     }
1.1055    raeburn  11554:                     $outer = 0;
1.1056    raeburn  11555:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11556:                         if (@{$dirorder{$i}} > 0) {
                   11557:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11558:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11559:                                     $outer = $item;
                   11560:                                     last;
                   11561:                                 }
                   11562:                             }
                   11563:                         }
                   11564:                     }
                   11565:                     my ($errtext,$fatal) = 
                   11566:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11567:                                                '/'.$folders{$outer}.'.'.
                   11568:                                                $containers{$outer});
                   11569:                     next if ($fatal);
                   11570:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11571:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11572:                             $mapinner{$i} = time;
1.1055    raeburn  11573:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11574:                             $containers{$i} = 'sequence';
                   11575:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11576:                                       $folders{$i}.'.'.$containers{$i};
                   11577:                             my $newidx = &LONCAPA::map::getresidx();
                   11578:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11579:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11580:                             push(@LONCAPA::map::order,$newidx);
                   11581:                             my ($outtext,$errtext) =
                   11582:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11583:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  11584:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11585:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11586:                             unless ($errtext) {
                   11587:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11588:                             }
1.1055    raeburn  11589:                         }
                   11590:                     } else {
                   11591:                         if ($context eq 'coursedocs') {
                   11592:                             my $newidx=&LONCAPA::map::getresidx();
                   11593:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11594:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11595:                                       $title;
                   11596:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11597:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11598:                             }
                   11599:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11600:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11601:                             }
                   11602:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11603:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11604:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11605:                                 unless ($ishome) {
                   11606:                                     my $fetch = "$newdest{$i}/$title";
                   11607:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11608:                                     $prompttofetch{$fetch} = 1;
                   11609:                                 }
1.1055    raeburn  11610:                             }
                   11611:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11612:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11613:                             push(@LONCAPA::map::order, $newidx);
                   11614:                             my ($outtext,$errtext)=
                   11615:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11616:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  11617:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11618:                             unless ($errtext) {
                   11619:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11620:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11621:                                 }
                   11622:                             }
1.1055    raeburn  11623:                         }
                   11624:                     }
1.1075.2.11  raeburn  11625:                 }
                   11626:             } else {
                   11627:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   11628:             }
                   11629:         }
                   11630:         for (my $i=1; $i<=$numitems; $i++) {
                   11631:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11632:             my $path = $env{'form.archive_content_'.$i};
                   11633:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11634:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11635:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11636:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11637:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11638:                         my ($itemidx,$fullpath,$relpath);
                   11639:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11640:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11641:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  11642:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11643:                                     $itemidx = $j;
1.1056    raeburn  11644:                                 }
                   11645:                             }
1.1075.2.11  raeburn  11646:                         }
                   11647:                         if ($itemidx eq '') {
                   11648:                             $itemidx =  0;
                   11649:                         }
                   11650:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11651:                             if ($mapinner{$referrer{$i}}) {
                   11652:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11653:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11654:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11655:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11656:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11657:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11658:                                             if (!-e $fullpath) {
                   11659:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11660:                                             }
                   11661:                                         }
1.1075.2.11  raeburn  11662:                                     } else {
                   11663:                                         last;
1.1056    raeburn  11664:                                     }
1.1075.2.11  raeburn  11665:                                 }
                   11666:                             }
                   11667:                         } elsif ($newdest{$referrer{$i}}) {
                   11668:                             $fullpath = $newdest{$referrer{$i}};
                   11669:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11670:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11671:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11672:                                     last;
                   11673:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11674:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11675:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11676:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11677:                                         if (!-e $fullpath) {
                   11678:                                             mkdir($fullpath,0755);
1.1056    raeburn  11679:                                         }
                   11680:                                     }
1.1075.2.11  raeburn  11681:                                 } else {
                   11682:                                     last;
1.1056    raeburn  11683:                                 }
1.1075.2.11  raeburn  11684:                             }
                   11685:                         }
                   11686:                         if ($fullpath ne '') {
                   11687:                             if (-e "$prefix$path") {
                   11688:                                 system("mv $prefix$path $fullpath/$title");
                   11689:                             }
                   11690:                             if (-e "$fullpath/$title") {
                   11691:                                 my $showpath;
                   11692:                                 if ($relpath ne '') {
                   11693:                                     $showpath = "$relpath/$title";
                   11694:                                 } else {
                   11695:                                     $showpath = "/$title";
1.1056    raeburn  11696:                                 }
1.1075.2.11  raeburn  11697:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   11698:                             }
                   11699:                             unless ($ishome) {
                   11700:                                 my $fetch = "$fullpath/$title";
                   11701:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   11702:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  11703:                             }
                   11704:                         }
                   11705:                     }
1.1075.2.11  raeburn  11706:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   11707:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   11708:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  11709:                 }
                   11710:             } else {
1.1075.2.11  raeburn  11711:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  11712:             }
                   11713:         }
                   11714:         if (keys(%todelete)) {
                   11715:             foreach my $key (keys(%todelete)) {
                   11716:                 unlink($key);
1.1066    raeburn  11717:             }
                   11718:         }
                   11719:         if (keys(%todeletedir)) {
                   11720:             foreach my $key (keys(%todeletedir)) {
                   11721:                 rmdir($key);
                   11722:             }
                   11723:         }
                   11724:         foreach my $dir (sort(keys(%is_dir))) {
                   11725:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   11726:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  11727:             }
                   11728:         }
1.1067    raeburn  11729:         if ($result ne '') {
                   11730:             $output .= '<ul>'."\n".
                   11731:                        $result."\n".
                   11732:                        '</ul>';
                   11733:         }
                   11734:         unless ($ishome) {
                   11735:             my $replicationfail;
                   11736:             foreach my $item (keys(%prompttofetch)) {
                   11737:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   11738:                 unless ($fetchresult eq 'ok') {
                   11739:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   11740:                 }
                   11741:             }
                   11742:             if ($replicationfail) {
                   11743:                 $output .= '<p class="LC_error">'.
                   11744:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   11745:                            $replicationfail.
                   11746:                            '</ul></p>';
                   11747:             }
                   11748:         }
1.1055    raeburn  11749:     } else {
                   11750:         $warning = &mt('No items found in archive.');
                   11751:     }
                   11752:     if ($error) {
                   11753:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11754:                    $error.'</p>'."\n";
                   11755:     }
                   11756:     if ($warning) {
                   11757:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11758:     }
                   11759:     return $output;
                   11760: }
                   11761: 
1.1066    raeburn  11762: sub cleanup_empty_dirs {
                   11763:     my ($path) = @_;
                   11764:     if (($path ne '') && (-d $path)) {
                   11765:         if (opendir(my $dirh,$path)) {
                   11766:             my @dircontents = grep(!/^\./,readdir($dirh));
                   11767:             my $numitems = 0;
                   11768:             foreach my $item (@dircontents) {
                   11769:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  11770:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  11771:                     if (-e "$path/$item") {
                   11772:                         $numitems ++;
                   11773:                     }
                   11774:                 } else {
                   11775:                     $numitems ++;
                   11776:                 }
                   11777:             }
                   11778:             if ($numitems == 0) {
                   11779:                 rmdir($path);
                   11780:             }
                   11781:             closedir($dirh);
                   11782:         }
                   11783:     }
                   11784:     return;
                   11785: }
                   11786: 
1.41      ng       11787: =pod
1.45      matthew  11788: 
1.1068    raeburn  11789: =item &get_folder_hierarchy()
                   11790: 
                   11791: Provides hierarchy of names of folders/sub-folders containing the current
                   11792: item,
                   11793: 
                   11794: Inputs: 3
                   11795:      - $navmap - navmaps object
                   11796: 
                   11797:      - $map - url for map (either the trigger itself, or map containing
                   11798:                            the resource, which is the trigger).
                   11799: 
                   11800:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   11801: 
                   11802: Outputs: 1 @pathitems - array of folder/subfolder names.
                   11803: 
                   11804: =cut
                   11805: 
                   11806: sub get_folder_hierarchy {
                   11807:     my ($navmap,$map,$showitem) = @_;
                   11808:     my @pathitems;
                   11809:     if (ref($navmap)) {
                   11810:         my $mapres = $navmap->getResourceByUrl($map);
                   11811:         if (ref($mapres)) {
                   11812:             my $pcslist = $mapres->map_hierarchy();
                   11813:             if ($pcslist ne '') {
                   11814:                 my @pcs = split(/,/,$pcslist);
                   11815:                 foreach my $pc (@pcs) {
                   11816:                     if ($pc == 1) {
1.1075.2.38! raeburn  11817:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  11818:                     } else {
                   11819:                         my $res = $navmap->getByMapPc($pc);
                   11820:                         if (ref($res)) {
                   11821:                             my $title = $res->compTitle();
                   11822:                             $title =~ s/\W+/_/g;
                   11823:                             if ($title ne '') {
                   11824:                                 push(@pathitems,$title);
                   11825:                             }
                   11826:                         }
                   11827:                     }
                   11828:                 }
                   11829:             }
1.1071    raeburn  11830:             if ($showitem) {
                   11831:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38! raeburn  11832:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  11833:                 } else {
                   11834:                     my $maptitle = $mapres->compTitle();
                   11835:                     $maptitle =~ s/\W+/_/g;
                   11836:                     if ($maptitle ne '') {
                   11837:                         push(@pathitems,$maptitle);
                   11838:                     }
1.1068    raeburn  11839:                 }
                   11840:             }
                   11841:         }
                   11842:     }
                   11843:     return @pathitems;
                   11844: }
                   11845: 
                   11846: =pod
                   11847: 
1.1015    raeburn  11848: =item * &get_turnedin_filepath()
                   11849: 
                   11850: Determines path in a user's portfolio file for storage of files uploaded
                   11851: to a specific essayresponse or dropbox item.
                   11852: 
                   11853: Inputs: 3 required + 1 optional.
                   11854: $symb is symb for resource, $uname and $udom are for current user (required).
                   11855: $caller is optional (can be "submission", if routine is called when storing
                   11856: an upoaded file when "Submit Answer" button was pressed).
                   11857: 
                   11858: Returns array containing $path and $multiresp. 
                   11859: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   11860: than one file upload item.  Callers of routine should append partid as a 
                   11861: subdirectory to $path in cases where $multiresp is 1.
                   11862: 
                   11863: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   11864: 
                   11865: =cut
                   11866: 
                   11867: sub get_turnedin_filepath {
                   11868:     my ($symb,$uname,$udom,$caller) = @_;
                   11869:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   11870:     my $turnindir;
                   11871:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   11872:     $turnindir = $userhash{'turnindir'};
                   11873:     my ($path,$multiresp);
                   11874:     if ($turnindir eq '') {
                   11875:         if ($caller eq 'submission') {
                   11876:             $turnindir = &mt('turned in');
                   11877:             $turnindir =~ s/\W+/_/g;
                   11878:             my %newhash = (
                   11879:                             'turnindir' => $turnindir,
                   11880:                           );
                   11881:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   11882:         }
                   11883:     }
                   11884:     if ($turnindir ne '') {
                   11885:         $path = '/'.$turnindir.'/';
                   11886:         my ($multipart,$turnin,@pathitems);
                   11887:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11888:         if (defined($navmap)) {
                   11889:             my $mapres = $navmap->getResourceByUrl($map);
                   11890:             if (ref($mapres)) {
                   11891:                 my $pcslist = $mapres->map_hierarchy();
                   11892:                 if ($pcslist ne '') {
                   11893:                     foreach my $pc (split(/,/,$pcslist)) {
                   11894:                         my $res = $navmap->getByMapPc($pc);
                   11895:                         if (ref($res)) {
                   11896:                             my $title = $res->compTitle();
                   11897:                             $title =~ s/\W+/_/g;
                   11898:                             if ($title ne '') {
                   11899:                                 push(@pathitems,$title);
                   11900:                             }
                   11901:                         }
                   11902:                     }
                   11903:                 }
                   11904:                 my $maptitle = $mapres->compTitle();
                   11905:                 $maptitle =~ s/\W+/_/g;
                   11906:                 if ($maptitle ne '') {
                   11907:                     push(@pathitems,$maptitle);
                   11908:                 }
                   11909:                 unless ($env{'request.state'} eq 'construct') {
                   11910:                     my $res = $navmap->getBySymb($symb);
                   11911:                     if (ref($res)) {
                   11912:                         my $partlist = $res->parts();
                   11913:                         my $totaluploads = 0;
                   11914:                         if (ref($partlist) eq 'ARRAY') {
                   11915:                             foreach my $part (@{$partlist}) {
                   11916:                                 my @types = $res->responseType($part);
                   11917:                                 my @ids = $res->responseIds($part);
                   11918:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   11919:                                     if ($types[$i] eq 'essay') {
                   11920:                                         my $partid = $part.'_'.$ids[$i];
                   11921:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   11922:                                             $totaluploads ++;
                   11923:                                         }
                   11924:                                     }
                   11925:                                 }
                   11926:                             }
                   11927:                             if ($totaluploads > 1) {
                   11928:                                 $multiresp = 1;
                   11929:                             }
                   11930:                         }
                   11931:                     }
                   11932:                 }
                   11933:             } else {
                   11934:                 return;
                   11935:             }
                   11936:         } else {
                   11937:             return;
                   11938:         }
                   11939:         my $restitle=&Apache::lonnet::gettitle($symb);
                   11940:         $restitle =~ s/\W+/_/g;
                   11941:         if ($restitle eq '') {
                   11942:             $restitle = ($resurl =~ m{/[^/]+$});
                   11943:             if ($restitle eq '') {
                   11944:                 $restitle = time;
                   11945:             }
                   11946:         }
                   11947:         push(@pathitems,$restitle);
                   11948:         $path .= join('/',@pathitems);
                   11949:     }
                   11950:     return ($path,$multiresp);
                   11951: }
                   11952: 
                   11953: =pod
                   11954: 
1.464     albertel 11955: =back
1.41      ng       11956: 
1.112     bowersj2 11957: =head1 CSV Upload/Handling functions
1.38      albertel 11958: 
1.41      ng       11959: =over 4
                   11960: 
1.648     raeburn  11961: =item * &upfile_store($r)
1.41      ng       11962: 
                   11963: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 11964: needs $env{'form.upfile'}
1.41      ng       11965: returns $datatoken to be put into hidden field
                   11966: 
                   11967: =cut
1.31      albertel 11968: 
                   11969: sub upfile_store {
                   11970:     my $r=shift;
1.258     albertel 11971:     $env{'form.upfile'}=~s/\r/\n/gs;
                   11972:     $env{'form.upfile'}=~s/\f/\n/gs;
                   11973:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   11974:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 11975: 
1.258     albertel 11976:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   11977: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 11978:     {
1.158     raeburn  11979:         my $datafile = $r->dir_config('lonDaemons').
                   11980:                            '/tmp/'.$datatoken.'.tmp';
                   11981:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 11982:             print $fh $env{'form.upfile'};
1.158     raeburn  11983:             close($fh);
                   11984:         }
1.31      albertel 11985:     }
                   11986:     return $datatoken;
                   11987: }
                   11988: 
1.56      matthew  11989: =pod
                   11990: 
1.648     raeburn  11991: =item * &load_tmp_file($r)
1.41      ng       11992: 
                   11993: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 11994: needs $env{'form.datatoken'},
                   11995: sets $env{'form.upfile'} to the contents of the file
1.41      ng       11996: 
                   11997: =cut
1.31      albertel 11998: 
                   11999: sub load_tmp_file {
                   12000:     my $r=shift;
                   12001:     my @studentdata=();
                   12002:     {
1.158     raeburn  12003:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12004:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12005:         if ( open(my $fh,"<$studentfile") ) {
                   12006:             @studentdata=<$fh>;
                   12007:             close($fh);
                   12008:         }
1.31      albertel 12009:     }
1.258     albertel 12010:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12011: }
                   12012: 
1.56      matthew  12013: =pod
                   12014: 
1.648     raeburn  12015: =item * &upfile_record_sep()
1.41      ng       12016: 
                   12017: Separate uploaded file into records
                   12018: returns array of records,
1.258     albertel 12019: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12020: 
                   12021: =cut
1.31      albertel 12022: 
                   12023: sub upfile_record_sep {
1.258     albertel 12024:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12025:     } else {
1.248     albertel 12026: 	my @records;
1.258     albertel 12027: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12028: 	    if ($line=~/^\s*$/) { next; }
                   12029: 	    push(@records,$line);
                   12030: 	}
                   12031: 	return @records;
1.31      albertel 12032:     }
                   12033: }
                   12034: 
1.56      matthew  12035: =pod
                   12036: 
1.648     raeburn  12037: =item * &record_sep($record)
1.41      ng       12038: 
1.258     albertel 12039: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12040: 
                   12041: =cut
                   12042: 
1.263     www      12043: sub takeleft {
                   12044:     my $index=shift;
                   12045:     return substr('0000'.$index,-4,4);
                   12046: }
                   12047: 
1.31      albertel 12048: sub record_sep {
                   12049:     my $record=shift;
                   12050:     my %components=();
1.258     albertel 12051:     if ($env{'form.upfiletype'} eq 'xml') {
                   12052:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12053:         my $i=0;
1.356     albertel 12054:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12055:             $field=~s/^(\"|\')//;
                   12056:             $field=~s/(\"|\')$//;
1.263     www      12057:             $components{&takeleft($i)}=$field;
1.31      albertel 12058:             $i++;
                   12059:         }
1.258     albertel 12060:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12061:         my $i=0;
1.356     albertel 12062:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12063:             $field=~s/^(\"|\')//;
                   12064:             $field=~s/(\"|\')$//;
1.263     www      12065:             $components{&takeleft($i)}=$field;
1.31      albertel 12066:             $i++;
                   12067:         }
                   12068:     } else {
1.561     www      12069:         my $separator=',';
1.480     banghart 12070:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12071:             $separator=';';
1.480     banghart 12072:         }
1.31      albertel 12073:         my $i=0;
1.561     www      12074: # the character we are looking for to indicate the end of a quote or a record 
                   12075:         my $looking_for=$separator;
                   12076: # do not add the characters to the fields
                   12077:         my $ignore=0;
                   12078: # we just encountered a separator (or the beginning of the record)
                   12079:         my $just_found_separator=1;
                   12080: # store the field we are working on here
                   12081:         my $field='';
                   12082: # work our way through all characters in record
                   12083:         foreach my $character ($record=~/(.)/g) {
                   12084:             if ($character eq $looking_for) {
                   12085:                if ($character ne $separator) {
                   12086: # Found the end of a quote, again looking for separator
                   12087:                   $looking_for=$separator;
                   12088:                   $ignore=1;
                   12089:                } else {
                   12090: # Found a separator, store away what we got
                   12091:                   $components{&takeleft($i)}=$field;
                   12092: 	          $i++;
                   12093:                   $just_found_separator=1;
                   12094:                   $ignore=0;
                   12095:                   $field='';
                   12096:                }
                   12097:                next;
                   12098:             }
                   12099: # single or double quotation marks after a separator indicate beginning of a quote
                   12100: # we are now looking for the end of the quote and need to ignore separators
                   12101:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12102:                $looking_for=$character;
                   12103:                next;
                   12104:             }
                   12105: # ignore would be true after we reached the end of a quote
                   12106:             if ($ignore) { next; }
                   12107:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12108:             $field.=$character;
                   12109:             $just_found_separator=0; 
1.31      albertel 12110:         }
1.561     www      12111: # catch the very last entry, since we never encountered the separator
                   12112:         $components{&takeleft($i)}=$field;
1.31      albertel 12113:     }
                   12114:     return %components;
                   12115: }
                   12116: 
1.144     matthew  12117: ######################################################
                   12118: ######################################################
                   12119: 
1.56      matthew  12120: =pod
                   12121: 
1.648     raeburn  12122: =item * &upfile_select_html()
1.41      ng       12123: 
1.144     matthew  12124: Return HTML code to select a file from the users machine and specify 
                   12125: the file type.
1.41      ng       12126: 
                   12127: =cut
                   12128: 
1.144     matthew  12129: ######################################################
                   12130: ######################################################
1.31      albertel 12131: sub upfile_select_html {
1.144     matthew  12132:     my %Types = (
                   12133:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12134:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12135:                  space => &mt('Space separated'),
                   12136:                  tab   => &mt('Tabulator separated'),
                   12137: #                 xml   => &mt('HTML/XML'),
                   12138:                  );
                   12139:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12140:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12141:     foreach my $type (sort(keys(%Types))) {
                   12142:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12143:     }
                   12144:     $Str .= "</select>\n";
                   12145:     return $Str;
1.31      albertel 12146: }
                   12147: 
1.301     albertel 12148: sub get_samples {
                   12149:     my ($records,$toget) = @_;
                   12150:     my @samples=({});
                   12151:     my $got=0;
                   12152:     foreach my $rec (@$records) {
                   12153: 	my %temp = &record_sep($rec);
                   12154: 	if (! grep(/\S/, values(%temp))) { next; }
                   12155: 	if (%temp) {
                   12156: 	    $samples[$got]=\%temp;
                   12157: 	    $got++;
                   12158: 	    if ($got == $toget) { last; }
                   12159: 	}
                   12160:     }
                   12161:     return \@samples;
                   12162: }
                   12163: 
1.144     matthew  12164: ######################################################
                   12165: ######################################################
                   12166: 
1.56      matthew  12167: =pod
                   12168: 
1.648     raeburn  12169: =item * &csv_print_samples($r,$records)
1.41      ng       12170: 
                   12171: Prints a table of sample values from each column uploaded $r is an
                   12172: Apache Request ref, $records is an arrayref from
                   12173: &Apache::loncommon::upfile_record_sep
                   12174: 
                   12175: =cut
                   12176: 
1.144     matthew  12177: ######################################################
                   12178: ######################################################
1.31      albertel 12179: sub csv_print_samples {
                   12180:     my ($r,$records) = @_;
1.662     bisitz   12181:     my $samples = &get_samples($records,5);
1.301     albertel 12182: 
1.594     raeburn  12183:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12184:               &start_data_table_header_row());
1.356     albertel 12185:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12186:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12187:     $r->print(&end_data_table_header_row());
1.301     albertel 12188:     foreach my $hash (@$samples) {
1.594     raeburn  12189: 	$r->print(&start_data_table_row());
1.356     albertel 12190: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12191: 	    $r->print('<td>');
1.356     albertel 12192: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12193: 	    $r->print('</td>');
                   12194: 	}
1.594     raeburn  12195: 	$r->print(&end_data_table_row());
1.31      albertel 12196:     }
1.594     raeburn  12197:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12198: }
                   12199: 
1.144     matthew  12200: ######################################################
                   12201: ######################################################
                   12202: 
1.56      matthew  12203: =pod
                   12204: 
1.648     raeburn  12205: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12206: 
                   12207: Prints a table to create associations between values and table columns.
1.144     matthew  12208: 
1.41      ng       12209: $r is an Apache Request ref,
                   12210: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12211: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12212: 
                   12213: =cut
                   12214: 
1.144     matthew  12215: ######################################################
                   12216: ######################################################
1.31      albertel 12217: sub csv_print_select_table {
                   12218:     my ($r,$records,$d) = @_;
1.301     albertel 12219:     my $i=0;
                   12220:     my $samples = &get_samples($records,1);
1.144     matthew  12221:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12222: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12223:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12224:               '<th>'.&mt('Column').'</th>'.
                   12225:               &end_data_table_header_row()."\n");
1.356     albertel 12226:     foreach my $array_ref (@$d) {
                   12227: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12228: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12229: 
1.875     bisitz   12230: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12231: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12232: 	$r->print('<option value="none"></option>');
1.356     albertel 12233: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12234: 	    $r->print('<option value="'.$sample.'"'.
                   12235:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12236:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12237: 	}
1.594     raeburn  12238: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12239: 	$i++;
                   12240:     }
1.594     raeburn  12241:     $r->print(&end_data_table());
1.31      albertel 12242:     $i--;
                   12243:     return $i;
                   12244: }
1.56      matthew  12245: 
1.144     matthew  12246: ######################################################
                   12247: ######################################################
                   12248: 
1.56      matthew  12249: =pod
1.31      albertel 12250: 
1.648     raeburn  12251: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12252: 
                   12253: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12254: 
                   12255: $r is an Apache Request ref,
                   12256: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12257: $d is an array of 2 element arrays (internal name, displayed name)
                   12258: 
                   12259: =cut
                   12260: 
1.144     matthew  12261: ######################################################
                   12262: ######################################################
1.31      albertel 12263: sub csv_samples_select_table {
                   12264:     my ($r,$records,$d) = @_;
                   12265:     my $i=0;
1.144     matthew  12266:     #
1.662     bisitz   12267:     my $max_samples = 5;
                   12268:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12269:     $r->print(&start_data_table().
                   12270:               &start_data_table_header_row().'<th>'.
                   12271:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12272:               &end_data_table_header_row());
1.301     albertel 12273: 
                   12274:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12275: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12276: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12277: 	foreach my $option (@$d) {
                   12278: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12279: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12280:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12281:                       $display.'</option>');
1.31      albertel 12282: 	}
                   12283: 	$r->print('</select></td><td>');
1.662     bisitz   12284: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12285: 	    if (defined($samples->[$line]{$key})) { 
                   12286: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12287: 	    }
                   12288: 	}
1.594     raeburn  12289: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12290: 	$i++;
                   12291:     }
1.594     raeburn  12292:     $r->print(&end_data_table());
1.31      albertel 12293:     $i--;
                   12294:     return($i);
1.115     matthew  12295: }
                   12296: 
1.144     matthew  12297: ######################################################
                   12298: ######################################################
                   12299: 
1.115     matthew  12300: =pod
                   12301: 
1.648     raeburn  12302: =item * &clean_excel_name($name)
1.115     matthew  12303: 
                   12304: Returns a replacement for $name which does not contain any illegal characters.
                   12305: 
                   12306: =cut
                   12307: 
1.144     matthew  12308: ######################################################
                   12309: ######################################################
1.115     matthew  12310: sub clean_excel_name {
                   12311:     my ($name) = @_;
                   12312:     $name =~ s/[:\*\?\/\\]//g;
                   12313:     if (length($name) > 31) {
                   12314:         $name = substr($name,0,31);
                   12315:     }
                   12316:     return $name;
1.25      albertel 12317: }
1.84      albertel 12318: 
1.85      albertel 12319: =pod
                   12320: 
1.648     raeburn  12321: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12322: 
                   12323: Returns either 1 or undef
                   12324: 
                   12325: 1 if the part is to be hidden, undef if it is to be shown
                   12326: 
                   12327: Arguments are:
                   12328: 
                   12329: $id the id of the part to be checked
                   12330: $symb, optional the symb of the resource to check
                   12331: $udom, optional the domain of the user to check for
                   12332: $uname, optional the username of the user to check for
                   12333: 
                   12334: =cut
1.84      albertel 12335: 
                   12336: sub check_if_partid_hidden {
                   12337:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12338:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12339: 					 $symb,$udom,$uname);
1.141     albertel 12340:     my $truth=1;
                   12341:     #if the string starts with !, then the list is the list to show not hide
                   12342:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12343:     my @hiddenlist=split(/,/,$hiddenparts);
                   12344:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12345: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12346:     }
1.141     albertel 12347:     return !$truth;
1.84      albertel 12348: }
1.127     matthew  12349: 
1.138     matthew  12350: 
                   12351: ############################################################
                   12352: ############################################################
                   12353: 
                   12354: =pod
                   12355: 
1.157     matthew  12356: =back 
                   12357: 
1.138     matthew  12358: =head1 cgi-bin script and graphing routines
                   12359: 
1.157     matthew  12360: =over 4
                   12361: 
1.648     raeburn  12362: =item * &get_cgi_id()
1.138     matthew  12363: 
                   12364: Inputs: none
                   12365: 
                   12366: Returns an id which can be used to pass environment variables
                   12367: to various cgi-bin scripts.  These environment variables will
                   12368: be removed from the users environment after a given time by
                   12369: the routine &Apache::lonnet::transfer_profile_to_env.
                   12370: 
                   12371: =cut
                   12372: 
                   12373: ############################################################
                   12374: ############################################################
1.152     albertel 12375: my $uniq=0;
1.136     matthew  12376: sub get_cgi_id {
1.154     albertel 12377:     $uniq=($uniq+1)%100000;
1.280     albertel 12378:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12379: }
                   12380: 
1.127     matthew  12381: ############################################################
                   12382: ############################################################
                   12383: 
                   12384: =pod
                   12385: 
1.648     raeburn  12386: =item * &DrawBarGraph()
1.127     matthew  12387: 
1.138     matthew  12388: Facilitates the plotting of data in a (stacked) bar graph.
                   12389: Puts plot definition data into the users environment in order for 
                   12390: graph.png to plot it.  Returns an <img> tag for the plot.
                   12391: The bars on the plot are labeled '1','2',...,'n'.
                   12392: 
                   12393: Inputs:
                   12394: 
                   12395: =over 4
                   12396: 
                   12397: =item $Title: string, the title of the plot
                   12398: 
                   12399: =item $xlabel: string, text describing the X-axis of the plot
                   12400: 
                   12401: =item $ylabel: string, text describing the Y-axis of the plot
                   12402: 
                   12403: =item $Max: scalar, the maximum Y value to use in the plot
                   12404: If $Max is < any data point, the graph will not be rendered.
                   12405: 
1.140     matthew  12406: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12407: they are plotted.  If undefined, default values will be used.
                   12408: 
1.178     matthew  12409: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12410: 
1.138     matthew  12411: =item @Values: An array of array references.  Each array reference holds data
                   12412: to be plotted in a stacked bar chart.
                   12413: 
1.239     matthew  12414: =item If the final element of @Values is a hash reference the key/value
                   12415: pairs will be added to the graph definition.
                   12416: 
1.138     matthew  12417: =back
                   12418: 
                   12419: Returns:
                   12420: 
                   12421: An <img> tag which references graph.png and the appropriate identifying
                   12422: information for the plot.
                   12423: 
1.127     matthew  12424: =cut
                   12425: 
                   12426: ############################################################
                   12427: ############################################################
1.134     matthew  12428: sub DrawBarGraph {
1.178     matthew  12429:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12430:     #
                   12431:     if (! defined($colors)) {
                   12432:         $colors = ['#33ff00', 
                   12433:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12434:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12435:                   ]; 
                   12436:     }
1.228     matthew  12437:     my $extra_settings = {};
                   12438:     if (ref($Values[-1]) eq 'HASH') {
                   12439:         $extra_settings = pop(@Values);
                   12440:     }
1.127     matthew  12441:     #
1.136     matthew  12442:     my $identifier = &get_cgi_id();
                   12443:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12444:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12445:         return '';
                   12446:     }
1.225     matthew  12447:     #
                   12448:     my @Labels;
                   12449:     if (defined($labels)) {
                   12450:         @Labels = @$labels;
                   12451:     } else {
                   12452:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12453:             push (@Labels,$i+1);
                   12454:         }
                   12455:     }
                   12456:     #
1.129     matthew  12457:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12458:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12459:     my %ValuesHash;
                   12460:     my $NumSets=1;
                   12461:     foreach my $array (@Values) {
                   12462:         next if (! ref($array));
1.136     matthew  12463:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12464:             join(',',@$array);
1.129     matthew  12465:     }
1.127     matthew  12466:     #
1.136     matthew  12467:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12468:     if ($NumBars < 3) {
                   12469:         $width = 120+$NumBars*32;
1.220     matthew  12470:         $xskip = 1;
1.225     matthew  12471:         $bar_width = 30;
                   12472:     } elsif ($NumBars < 5) {
                   12473:         $width = 120+$NumBars*20;
                   12474:         $xskip = 1;
                   12475:         $bar_width = 20;
1.220     matthew  12476:     } elsif ($NumBars < 10) {
1.136     matthew  12477:         $width = 120+$NumBars*15;
                   12478:         $xskip = 1;
                   12479:         $bar_width = 15;
                   12480:     } elsif ($NumBars <= 25) {
                   12481:         $width = 120+$NumBars*11;
                   12482:         $xskip = 5;
                   12483:         $bar_width = 8;
                   12484:     } elsif ($NumBars <= 50) {
                   12485:         $width = 120+$NumBars*8;
                   12486:         $xskip = 5;
                   12487:         $bar_width = 4;
                   12488:     } else {
                   12489:         $width = 120+$NumBars*8;
                   12490:         $xskip = 5;
                   12491:         $bar_width = 4;
                   12492:     }
                   12493:     #
1.137     matthew  12494:     $Max = 1 if ($Max < 1);
                   12495:     if ( int($Max) < $Max ) {
                   12496:         $Max++;
                   12497:         $Max = int($Max);
                   12498:     }
1.127     matthew  12499:     $Title  = '' if (! defined($Title));
                   12500:     $xlabel = '' if (! defined($xlabel));
                   12501:     $ylabel = '' if (! defined($ylabel));
1.369     www      12502:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12503:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12504:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12505:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12506:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12507:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12508:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12509:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12510:     $ValuesHash{$id.'.height'}   = $height;
                   12511:     $ValuesHash{$id.'.width'}    = $width;
                   12512:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12513:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12514:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12515:     #
1.228     matthew  12516:     # Deal with other parameters
                   12517:     while (my ($key,$value) = each(%$extra_settings)) {
                   12518:         $ValuesHash{$id.'.'.$key} = $value;
                   12519:     }
                   12520:     #
1.646     raeburn  12521:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12522:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12523: }
                   12524: 
                   12525: ############################################################
                   12526: ############################################################
                   12527: 
                   12528: =pod
                   12529: 
1.648     raeburn  12530: =item * &DrawXYGraph()
1.137     matthew  12531: 
1.138     matthew  12532: Facilitates the plotting of data in an XY graph.
                   12533: Puts plot definition data into the users environment in order for 
                   12534: graph.png to plot it.  Returns an <img> tag for the plot.
                   12535: 
                   12536: Inputs:
                   12537: 
                   12538: =over 4
                   12539: 
                   12540: =item $Title: string, the title of the plot
                   12541: 
                   12542: =item $xlabel: string, text describing the X-axis of the plot
                   12543: 
                   12544: =item $ylabel: string, text describing the Y-axis of the plot
                   12545: 
                   12546: =item $Max: scalar, the maximum Y value to use in the plot
                   12547: If $Max is < any data point, the graph will not be rendered.
                   12548: 
                   12549: =item $colors: Array ref containing the hex color codes for the data to be 
                   12550: plotted in.  If undefined, default values will be used.
                   12551: 
                   12552: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12553: 
                   12554: =item $Ydata: Array ref containing Array refs.  
1.185     www      12555: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12556: 
                   12557: =item %Values: hash indicating or overriding any default values which are 
                   12558: passed to graph.png.  
                   12559: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12560: 
                   12561: =back
                   12562: 
                   12563: Returns:
                   12564: 
                   12565: An <img> tag which references graph.png and the appropriate identifying
                   12566: information for the plot.
                   12567: 
1.137     matthew  12568: =cut
                   12569: 
                   12570: ############################################################
                   12571: ############################################################
                   12572: sub DrawXYGraph {
                   12573:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12574:     #
                   12575:     # Create the identifier for the graph
                   12576:     my $identifier = &get_cgi_id();
                   12577:     my $id = 'cgi.'.$identifier;
                   12578:     #
                   12579:     $Title  = '' if (! defined($Title));
                   12580:     $xlabel = '' if (! defined($xlabel));
                   12581:     $ylabel = '' if (! defined($ylabel));
                   12582:     my %ValuesHash = 
                   12583:         (
1.369     www      12584:          $id.'.title'  => &escape($Title),
                   12585:          $id.'.xlabel' => &escape($xlabel),
                   12586:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12587:          $id.'.y_max_value'=> $Max,
                   12588:          $id.'.labels'     => join(',',@$Xlabels),
                   12589:          $id.'.PlotType'   => 'XY',
                   12590:          );
                   12591:     #
                   12592:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12593:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12594:     }
                   12595:     #
                   12596:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12597:         return '';
                   12598:     }
                   12599:     my $NumSets=1;
1.138     matthew  12600:     foreach my $array (@{$Ydata}){
1.137     matthew  12601:         next if (! ref($array));
                   12602:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12603:     }
1.138     matthew  12604:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12605:     #
                   12606:     # Deal with other parameters
                   12607:     while (my ($key,$value) = each(%Values)) {
                   12608:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12609:     }
                   12610:     #
1.646     raeburn  12611:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12612:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12613: }
                   12614: 
                   12615: ############################################################
                   12616: ############################################################
                   12617: 
                   12618: =pod
                   12619: 
1.648     raeburn  12620: =item * &DrawXYYGraph()
1.138     matthew  12621: 
                   12622: Facilitates the plotting of data in an XY graph with two Y axes.
                   12623: Puts plot definition data into the users environment in order for 
                   12624: graph.png to plot it.  Returns an <img> tag for the plot.
                   12625: 
                   12626: Inputs:
                   12627: 
                   12628: =over 4
                   12629: 
                   12630: =item $Title: string, the title of the plot
                   12631: 
                   12632: =item $xlabel: string, text describing the X-axis of the plot
                   12633: 
                   12634: =item $ylabel: string, text describing the Y-axis of the plot
                   12635: 
                   12636: =item $colors: Array ref containing the hex color codes for the data to be 
                   12637: plotted in.  If undefined, default values will be used.
                   12638: 
                   12639: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12640: 
                   12641: =item $Ydata1: The first data set
                   12642: 
                   12643: =item $Min1: The minimum value of the left Y-axis
                   12644: 
                   12645: =item $Max1: The maximum value of the left Y-axis
                   12646: 
                   12647: =item $Ydata2: The second data set
                   12648: 
                   12649: =item $Min2: The minimum value of the right Y-axis
                   12650: 
                   12651: =item $Max2: The maximum value of the left Y-axis
                   12652: 
                   12653: =item %Values: hash indicating or overriding any default values which are 
                   12654: passed to graph.png.  
                   12655: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12656: 
                   12657: =back
                   12658: 
                   12659: Returns:
                   12660: 
                   12661: An <img> tag which references graph.png and the appropriate identifying
                   12662: information for the plot.
1.136     matthew  12663: 
                   12664: =cut
                   12665: 
                   12666: ############################################################
                   12667: ############################################################
1.137     matthew  12668: sub DrawXYYGraph {
                   12669:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12670:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12671:     #
                   12672:     # Create the identifier for the graph
                   12673:     my $identifier = &get_cgi_id();
                   12674:     my $id = 'cgi.'.$identifier;
                   12675:     #
                   12676:     $Title  = '' if (! defined($Title));
                   12677:     $xlabel = '' if (! defined($xlabel));
                   12678:     $ylabel = '' if (! defined($ylabel));
                   12679:     my %ValuesHash = 
                   12680:         (
1.369     www      12681:          $id.'.title'  => &escape($Title),
                   12682:          $id.'.xlabel' => &escape($xlabel),
                   12683:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  12684:          $id.'.labels' => join(',',@$Xlabels),
                   12685:          $id.'.PlotType' => 'XY',
                   12686:          $id.'.NumSets' => 2,
1.137     matthew  12687:          $id.'.two_axes' => 1,
                   12688:          $id.'.y1_max_value' => $Max1,
                   12689:          $id.'.y1_min_value' => $Min1,
                   12690:          $id.'.y2_max_value' => $Max2,
                   12691:          $id.'.y2_min_value' => $Min2,
1.136     matthew  12692:          );
                   12693:     #
1.137     matthew  12694:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12695:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12696:     }
                   12697:     #
                   12698:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   12699:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  12700:         return '';
                   12701:     }
                   12702:     my $NumSets=1;
1.137     matthew  12703:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  12704:         next if (! ref($array));
                   12705:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  12706:     }
                   12707:     #
                   12708:     # Deal with other parameters
                   12709:     while (my ($key,$value) = each(%Values)) {
                   12710:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  12711:     }
                   12712:     #
1.646     raeburn  12713:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 12714:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  12715: }
                   12716: 
                   12717: ############################################################
                   12718: ############################################################
                   12719: 
                   12720: =pod
                   12721: 
1.157     matthew  12722: =back 
                   12723: 
1.139     matthew  12724: =head1 Statistics helper routines?  
                   12725: 
                   12726: Bad place for them but what the hell.
                   12727: 
1.157     matthew  12728: =over 4
                   12729: 
1.648     raeburn  12730: =item * &chartlink()
1.139     matthew  12731: 
                   12732: Returns a link to the chart for a specific student.  
                   12733: 
                   12734: Inputs:
                   12735: 
                   12736: =over 4
                   12737: 
                   12738: =item $linktext: The text of the link
                   12739: 
                   12740: =item $sname: The students username
                   12741: 
                   12742: =item $sdomain: The students domain
                   12743: 
                   12744: =back
                   12745: 
1.157     matthew  12746: =back
                   12747: 
1.139     matthew  12748: =cut
                   12749: 
                   12750: ############################################################
                   12751: ############################################################
                   12752: sub chartlink {
                   12753:     my ($linktext, $sname, $sdomain) = @_;
                   12754:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      12755:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 12756:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  12757:        '">'.$linktext.'</a>';
1.153     matthew  12758: }
                   12759: 
                   12760: #######################################################
                   12761: #######################################################
                   12762: 
                   12763: =pod
                   12764: 
                   12765: =head1 Course Environment Routines
1.157     matthew  12766: 
                   12767: =over 4
1.153     matthew  12768: 
1.648     raeburn  12769: =item * &restore_course_settings()
1.153     matthew  12770: 
1.648     raeburn  12771: =item * &store_course_settings()
1.153     matthew  12772: 
                   12773: Restores/Store indicated form parameters from the course environment.
                   12774: Will not overwrite existing values of the form parameters.
                   12775: 
                   12776: Inputs: 
                   12777: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   12778: 
                   12779: a hash ref describing the data to be stored.  For example:
                   12780:    
                   12781: %Save_Parameters = ('Status' => 'scalar',
                   12782:     'chartoutputmode' => 'scalar',
                   12783:     'chartoutputdata' => 'scalar',
                   12784:     'Section' => 'array',
1.373     raeburn  12785:     'Group' => 'array',
1.153     matthew  12786:     'StudentData' => 'array',
                   12787:     'Maps' => 'array');
                   12788: 
                   12789: Returns: both routines return nothing
                   12790: 
1.631     raeburn  12791: =back
                   12792: 
1.153     matthew  12793: =cut
                   12794: 
                   12795: #######################################################
                   12796: #######################################################
                   12797: sub store_course_settings {
1.496     albertel 12798:     return &store_settings($env{'request.course.id'},@_);
                   12799: }
                   12800: 
                   12801: sub store_settings {
1.153     matthew  12802:     # save to the environment
                   12803:     # appenv the same items, just to be safe
1.300     albertel 12804:     my $udom  = $env{'user.domain'};
                   12805:     my $uname = $env{'user.name'};
1.496     albertel 12806:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12807:     my %SaveHash;
                   12808:     my %AppHash;
                   12809:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 12810:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 12811:         my $envname = 'environment.'.$basename;
1.258     albertel 12812:         if (exists($env{'form.'.$setting})) {
1.153     matthew  12813:             # Save this value away
                   12814:             if ($type eq 'scalar' &&
1.258     albertel 12815:                 (! exists($env{$envname}) || 
                   12816:                  $env{$envname} ne $env{'form.'.$setting})) {
                   12817:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   12818:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  12819:             } elsif ($type eq 'array') {
                   12820:                 my $stored_form;
1.258     albertel 12821:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  12822:                     $stored_form = join(',',
                   12823:                                         map {
1.369     www      12824:                                             &escape($_);
1.258     albertel 12825:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  12826:                 } else {
                   12827:                     $stored_form = 
1.369     www      12828:                         &escape($env{'form.'.$setting});
1.153     matthew  12829:                 }
                   12830:                 # Determine if the array contents are the same.
1.258     albertel 12831:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  12832:                     $SaveHash{$basename} = $stored_form;
                   12833:                     $AppHash{$envname}   = $stored_form;
                   12834:                 }
                   12835:             }
                   12836:         }
                   12837:     }
                   12838:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 12839:                                           $udom,$uname);
1.153     matthew  12840:     if ($put_result !~ /^(ok|delayed)/) {
                   12841:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   12842:                                  'got error:'.$put_result);
                   12843:     }
                   12844:     # Make sure these settings stick around in this session, too
1.646     raeburn  12845:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  12846:     return;
                   12847: }
                   12848: 
                   12849: sub restore_course_settings {
1.499     albertel 12850:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 12851: }
                   12852: 
                   12853: sub restore_settings {
                   12854:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12855:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 12856:         next if (exists($env{'form.'.$setting}));
1.496     albertel 12857:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  12858:             '.'.$setting;
1.258     albertel 12859:         if (exists($env{$envname})) {
1.153     matthew  12860:             if ($type eq 'scalar') {
1.258     albertel 12861:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  12862:             } elsif ($type eq 'array') {
1.258     albertel 12863:                 $env{'form.'.$setting} = [ 
1.153     matthew  12864:                                            map { 
1.369     www      12865:                                                &unescape($_); 
1.258     albertel 12866:                                            } split(',',$env{$envname})
1.153     matthew  12867:                                            ];
                   12868:             }
                   12869:         }
                   12870:     }
1.127     matthew  12871: }
                   12872: 
1.618     raeburn  12873: #######################################################
                   12874: #######################################################
                   12875: 
                   12876: =pod
                   12877: 
                   12878: =head1 Domain E-mail Routines  
                   12879: 
                   12880: =over 4
                   12881: 
1.648     raeburn  12882: =item * &build_recipient_list()
1.618     raeburn  12883: 
1.884     raeburn  12884: Build recipient lists for five types of e-mail:
1.766     raeburn  12885: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.884     raeburn  12886: (d) Help requests, (e) Course requests needing approval,  generated by
                   12887: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
                   12888: loncoursequeueadmin.pm respectively.
1.618     raeburn  12889: 
                   12890: Inputs:
1.619     raeburn  12891: defmail (scalar - email address of default recipient), 
1.618     raeburn  12892: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  12893: defdom (domain for which to retrieve configuration settings),
                   12894: origmail (scalar - email address of recipient from loncapa.conf, 
                   12895: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  12896: 
1.655     raeburn  12897: Returns: comma separated list of addresses to which to send e-mail.
                   12898: 
                   12899: =back
1.618     raeburn  12900: 
                   12901: =cut
                   12902: 
                   12903: ############################################################
                   12904: ############################################################
                   12905: sub build_recipient_list {
1.619     raeburn  12906:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  12907:     my @recipients;
                   12908:     my $otheremails;
                   12909:     my %domconfig =
                   12910:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   12911:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  12912:         if (exists($domconfig{'contacts'}{$mailing})) {
                   12913:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   12914:                 my @contacts = ('adminemail','supportemail');
                   12915:                 foreach my $item (@contacts) {
                   12916:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   12917:                         my $addr = $domconfig{'contacts'}{$item}; 
                   12918:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12919:                             push(@recipients,$addr);
                   12920:                         }
1.619     raeburn  12921:                     }
1.766     raeburn  12922:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  12923:                 }
                   12924:             }
1.766     raeburn  12925:         } elsif ($origmail ne '') {
                   12926:             push(@recipients,$origmail);
1.618     raeburn  12927:         }
1.619     raeburn  12928:     } elsif ($origmail ne '') {
                   12929:         push(@recipients,$origmail);
1.618     raeburn  12930:     }
1.688     raeburn  12931:     if (defined($defmail)) {
                   12932:         if ($defmail ne '') {
                   12933:             push(@recipients,$defmail);
                   12934:         }
1.618     raeburn  12935:     }
                   12936:     if ($otheremails) {
1.619     raeburn  12937:         my @others;
                   12938:         if ($otheremails =~ /,/) {
                   12939:             @others = split(/,/,$otheremails);
1.618     raeburn  12940:         } else {
1.619     raeburn  12941:             push(@others,$otheremails);
                   12942:         }
                   12943:         foreach my $addr (@others) {
                   12944:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12945:                 push(@recipients,$addr);
                   12946:             }
1.618     raeburn  12947:         }
                   12948:     }
1.619     raeburn  12949:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  12950:     return $recipientlist;
                   12951: }
                   12952: 
1.127     matthew  12953: ############################################################
                   12954: ############################################################
1.154     albertel 12955: 
1.655     raeburn  12956: =pod
                   12957: 
                   12958: =head1 Course Catalog Routines
                   12959: 
                   12960: =over 4
                   12961: 
                   12962: =item * &gather_categories()
                   12963: 
                   12964: Converts category definitions - keys of categories hash stored in  
                   12965: coursecategories in configuration.db on the primary library server in a 
                   12966: domain - to an array.  Also generates javascript and idx hash used to 
                   12967: generate Domain Coordinator interface for editing Course Categories.
                   12968: 
                   12969: Inputs:
1.663     raeburn  12970: 
1.655     raeburn  12971: categories (reference to hash of category definitions).
1.663     raeburn  12972: 
1.655     raeburn  12973: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12974:       categories and subcategories).
1.663     raeburn  12975: 
1.655     raeburn  12976: idx (reference to hash of counters used in Domain Coordinator interface for 
                   12977:       editing Course Categories).
1.663     raeburn  12978: 
1.655     raeburn  12979: jsarray (reference to array of categories used to create Javascript arrays for
                   12980:          Domain Coordinator interface for editing Course Categories).
                   12981: 
                   12982: Returns: nothing
                   12983: 
                   12984: Side effects: populates cats, idx and jsarray. 
                   12985: 
                   12986: =cut
                   12987: 
                   12988: sub gather_categories {
                   12989:     my ($categories,$cats,$idx,$jsarray) = @_;
                   12990:     my %counters;
                   12991:     my $num = 0;
                   12992:     foreach my $item (keys(%{$categories})) {
                   12993:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   12994:         if ($container eq '' && $depth == 0) {
                   12995:             $cats->[$depth][$categories->{$item}] = $cat;
                   12996:         } else {
                   12997:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   12998:         }
                   12999:         my ($escitem,$tail) = split(/:/,$item,2);
                   13000:         if ($counters{$tail} eq '') {
                   13001:             $counters{$tail} = $num;
                   13002:             $num ++;
                   13003:         }
                   13004:         if (ref($idx) eq 'HASH') {
                   13005:             $idx->{$item} = $counters{$tail};
                   13006:         }
                   13007:         if (ref($jsarray) eq 'ARRAY') {
                   13008:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13009:         }
                   13010:     }
                   13011:     return;
                   13012: }
                   13013: 
                   13014: =pod
                   13015: 
                   13016: =item * &extract_categories()
                   13017: 
                   13018: Used to generate breadcrumb trails for course categories.
                   13019: 
                   13020: Inputs:
1.663     raeburn  13021: 
1.655     raeburn  13022: categories (reference to hash of category definitions).
1.663     raeburn  13023: 
1.655     raeburn  13024: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13025:       categories and subcategories).
1.663     raeburn  13026: 
1.655     raeburn  13027: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13028: 
1.655     raeburn  13029: allitems (reference to hash - key is category key 
                   13030:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13031: 
1.655     raeburn  13032: idx (reference to hash of counters used in Domain Coordinator interface for
                   13033:       editing Course Categories).
1.663     raeburn  13034: 
1.655     raeburn  13035: jsarray (reference to array of categories used to create Javascript arrays for
                   13036:          Domain Coordinator interface for editing Course Categories).
                   13037: 
1.665     raeburn  13038: subcats (reference to hash of arrays containing all subcategories within each 
                   13039:          category, -recursive)
                   13040: 
1.655     raeburn  13041: Returns: nothing
                   13042: 
                   13043: Side effects: populates trails and allitems hash references.
                   13044: 
                   13045: =cut
                   13046: 
                   13047: sub extract_categories {
1.665     raeburn  13048:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13049:     if (ref($categories) eq 'HASH') {
                   13050:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13051:         if (ref($cats->[0]) eq 'ARRAY') {
                   13052:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13053:                 my $name = $cats->[0][$i];
                   13054:                 my $item = &escape($name).'::0';
                   13055:                 my $trailstr;
                   13056:                 if ($name eq 'instcode') {
                   13057:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13058:                 } elsif ($name eq 'communities') {
                   13059:                     $trailstr = &mt('Communities');
1.655     raeburn  13060:                 } else {
                   13061:                     $trailstr = $name;
                   13062:                 }
                   13063:                 if ($allitems->{$item} eq '') {
                   13064:                     push(@{$trails},$trailstr);
                   13065:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13066:                 }
                   13067:                 my @parents = ($name);
                   13068:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13069:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13070:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13071:                         if (ref($subcats) eq 'HASH') {
                   13072:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13073:                         }
                   13074:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13075:                     }
                   13076:                 } else {
                   13077:                     if (ref($subcats) eq 'HASH') {
                   13078:                         $subcats->{$item} = [];
1.655     raeburn  13079:                     }
                   13080:                 }
                   13081:             }
                   13082:         }
                   13083:     }
                   13084:     return;
                   13085: }
                   13086: 
                   13087: =pod
                   13088: 
                   13089: =item *&recurse_categories()
                   13090: 
                   13091: Recursively used to generate breadcrumb trails for course categories.
                   13092: 
                   13093: Inputs:
1.663     raeburn  13094: 
1.655     raeburn  13095: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13096:       categories and subcategories).
1.663     raeburn  13097: 
1.655     raeburn  13098: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13099: 
                   13100: category (current course category, for which breadcrumb trail is being generated).
                   13101: 
                   13102: trails (reference to array of breadcrumb trails for each category).
                   13103: 
1.655     raeburn  13104: allitems (reference to hash - key is category key
                   13105:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13106: 
1.655     raeburn  13107: parents (array containing containers directories for current category, 
                   13108:          back to top level). 
                   13109: 
                   13110: Returns: nothing
                   13111: 
                   13112: Side effects: populates trails and allitems hash references
                   13113: 
                   13114: =cut
                   13115: 
                   13116: sub recurse_categories {
1.665     raeburn  13117:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13118:     my $shallower = $depth - 1;
                   13119:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13120:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13121:             my $name = $cats->[$depth]{$category}[$k];
                   13122:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13123:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13124:             if ($allitems->{$item} eq '') {
                   13125:                 push(@{$trails},$trailstr);
                   13126:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13127:             }
                   13128:             my $deeper = $depth+1;
                   13129:             push(@{$parents},$category);
1.665     raeburn  13130:             if (ref($subcats) eq 'HASH') {
                   13131:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13132:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13133:                     my $higher;
                   13134:                     if ($j > 0) {
                   13135:                         $higher = &escape($parents->[$j]).':'.
                   13136:                                   &escape($parents->[$j-1]).':'.$j;
                   13137:                     } else {
                   13138:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13139:                     }
                   13140:                     push(@{$subcats->{$higher}},$subcat);
                   13141:                 }
                   13142:             }
                   13143:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13144:                                 $subcats);
1.655     raeburn  13145:             pop(@{$parents});
                   13146:         }
                   13147:     } else {
                   13148:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13149:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13150:         if ($allitems->{$item} eq '') {
                   13151:             push(@{$trails},$trailstr);
                   13152:             $allitems->{$item} = scalar(@{$trails})-1;
                   13153:         }
                   13154:     }
                   13155:     return;
                   13156: }
                   13157: 
1.663     raeburn  13158: =pod
                   13159: 
                   13160: =item *&assign_categories_table()
                   13161: 
                   13162: Create a datatable for display of hierarchical categories in a domain,
                   13163: with checkboxes to allow a course to be categorized. 
                   13164: 
                   13165: Inputs:
                   13166: 
                   13167: cathash - reference to hash of categories defined for the domain (from
                   13168:           configuration.db)
                   13169: 
                   13170: currcat - scalar with an & separated list of categories assigned to a course. 
                   13171: 
1.919     raeburn  13172: type    - scalar contains course type (Course or Community).
                   13173: 
1.663     raeburn  13174: Returns: $output (markup to be displayed) 
                   13175: 
                   13176: =cut
                   13177: 
                   13178: sub assign_categories_table {
1.919     raeburn  13179:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13180:     my $output;
                   13181:     if (ref($cathash) eq 'HASH') {
                   13182:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13183:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13184:         $maxdepth = scalar(@cats);
                   13185:         if (@cats > 0) {
                   13186:             my $itemcount = 0;
                   13187:             if (ref($cats[0]) eq 'ARRAY') {
                   13188:                 my @currcategories;
                   13189:                 if ($currcat ne '') {
                   13190:                     @currcategories = split('&',$currcat);
                   13191:                 }
1.919     raeburn  13192:                 my $table;
1.663     raeburn  13193:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13194:                     my $parent = $cats[0][$i];
1.919     raeburn  13195:                     next if ($parent eq 'instcode');
                   13196:                     if ($type eq 'Community') {
                   13197:                         next unless ($parent eq 'communities');
                   13198:                     } else {
                   13199:                         next if ($parent eq 'communities');
                   13200:                     }
1.663     raeburn  13201:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13202:                     my $item = &escape($parent).'::0';
                   13203:                     my $checked = '';
                   13204:                     if (@currcategories > 0) {
                   13205:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13206:                             $checked = ' checked="checked"';
1.663     raeburn  13207:                         }
                   13208:                     }
1.919     raeburn  13209:                     my $parent_title = $parent;
                   13210:                     if ($parent eq 'communities') {
                   13211:                         $parent_title = &mt('Communities');
                   13212:                     }
                   13213:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13214:                               '<input type="checkbox" name="usecategory" value="'.
                   13215:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13216:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13217:                     my $depth = 1;
                   13218:                     push(@path,$parent);
1.919     raeburn  13219:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13220:                     pop(@path);
1.919     raeburn  13221:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13222:                     $itemcount ++;
                   13223:                 }
1.919     raeburn  13224:                 if ($itemcount) {
                   13225:                     $output = &Apache::loncommon::start_data_table().
                   13226:                               $table.
                   13227:                               &Apache::loncommon::end_data_table();
                   13228:                 }
1.663     raeburn  13229:             }
                   13230:         }
                   13231:     }
                   13232:     return $output;
                   13233: }
                   13234: 
                   13235: =pod
                   13236: 
                   13237: =item *&assign_category_rows()
                   13238: 
                   13239: Create a datatable row for display of nested categories in a domain,
                   13240: with checkboxes to allow a course to be categorized,called recursively.
                   13241: 
                   13242: Inputs:
                   13243: 
                   13244: itemcount - track row number for alternating colors
                   13245: 
                   13246: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13247:       categories and subcategories.
                   13248: 
                   13249: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13250: 
                   13251: parent - parent of current category item
                   13252: 
                   13253: path - Array containing all categories back up through the hierarchy from the
                   13254:        current category to the top level.
                   13255: 
                   13256: currcategories - reference to array of current categories assigned to the course
                   13257: 
                   13258: Returns: $output (markup to be displayed).
                   13259: 
                   13260: =cut
                   13261: 
                   13262: sub assign_category_rows {
                   13263:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13264:     my ($text,$name,$item,$chgstr);
                   13265:     if (ref($cats) eq 'ARRAY') {
                   13266:         my $maxdepth = scalar(@{$cats});
                   13267:         if (ref($cats->[$depth]) eq 'HASH') {
                   13268:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13269:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13270:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13271:                 $text .= '<td><table class="LC_datatable">';
                   13272:                 for (my $j=0; $j<$numchildren; $j++) {
                   13273:                     $name = $cats->[$depth]{$parent}[$j];
                   13274:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13275:                     my $deeper = $depth+1;
                   13276:                     my $checked = '';
                   13277:                     if (ref($currcategories) eq 'ARRAY') {
                   13278:                         if (@{$currcategories} > 0) {
                   13279:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13280:                                 $checked = ' checked="checked"';
1.663     raeburn  13281:                             }
                   13282:                         }
                   13283:                     }
1.664     raeburn  13284:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13285:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13286:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13287:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13288:                              '</td><td>';
1.663     raeburn  13289:                     if (ref($path) eq 'ARRAY') {
                   13290:                         push(@{$path},$name);
                   13291:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13292:                         pop(@{$path});
                   13293:                     }
                   13294:                     $text .= '</td></tr>';
                   13295:                 }
                   13296:                 $text .= '</table></td>';
                   13297:             }
                   13298:         }
                   13299:     }
                   13300:     return $text;
                   13301: }
                   13302: 
1.655     raeburn  13303: ############################################################
                   13304: ############################################################
                   13305: 
                   13306: 
1.443     albertel 13307: sub commit_customrole {
1.664     raeburn  13308:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13309:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13310:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13311:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13312:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13313:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13314:                  '</b><br />';
                   13315:     return $output;
                   13316: }
                   13317: 
                   13318: sub commit_standardrole {
1.1075.2.31  raeburn  13319:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13320:     my ($output,$logmsg,$linefeed);
                   13321:     if ($context eq 'auto') {
                   13322:         $linefeed = "\n";
                   13323:     } else {
                   13324:         $linefeed = "<br />\n";
                   13325:     }  
1.443     albertel 13326:     if ($three eq 'st') {
1.541     raeburn  13327:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  13328:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13329:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13330:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13331:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13332:         } else {
1.541     raeburn  13333:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13334:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13335:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13336:             if ($context eq 'auto') {
                   13337:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13338:             } else {
                   13339:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13340:                &mt('Add to classlist').': <b>ok</b>';
                   13341:             }
                   13342:             $output .= $linefeed;
1.443     albertel 13343:         }
                   13344:     } else {
                   13345:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13346:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13347:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13348:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13349:         if ($context eq 'auto') {
                   13350:             $output .= $result.$linefeed;
                   13351:         } else {
                   13352:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13353:         }
1.443     albertel 13354:     }
                   13355:     return $output;
                   13356: }
                   13357: 
                   13358: sub commit_studentrole {
1.1075.2.31  raeburn  13359:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13360:         $credits) = @_;
1.626     raeburn  13361:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13362:     if ($context eq 'auto') {
                   13363:         $linefeed = "\n";
                   13364:     } else {
                   13365:         $linefeed = '<br />'."\n";
                   13366:     }
1.443     albertel 13367:     if (defined($one) && defined($two)) {
                   13368:         my $cid=$one.'_'.$two;
                   13369:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13370:         my $secchange = 0;
                   13371:         my $expire_role_result;
                   13372:         my $modify_section_result;
1.628     raeburn  13373:         if ($oldsec ne '-1') { 
                   13374:             if ($oldsec ne $sec) {
1.443     albertel 13375:                 $secchange = 1;
1.628     raeburn  13376:                 my $now = time;
1.443     albertel 13377:                 my $uurl='/'.$cid;
                   13378:                 $uurl=~s/\_/\//g;
                   13379:                 if ($oldsec) {
                   13380:                     $uurl.='/'.$oldsec;
                   13381:                 }
1.626     raeburn  13382:                 $oldsecurl = $uurl;
1.628     raeburn  13383:                 $expire_role_result = 
1.652     raeburn  13384:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13385:                 if ($env{'request.course.sec'} ne '') { 
                   13386:                     if ($expire_role_result eq 'refused') {
                   13387:                         my @roles = ('st');
                   13388:                         my @statuses = ('previous');
                   13389:                         my @roledoms = ($one);
                   13390:                         my $withsec = 1;
                   13391:                         my %roleshash = 
                   13392:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13393:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13394:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13395:                             my ($oldstart,$oldend) = 
                   13396:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13397:                             if ($oldend > 0 && $oldend <= $now) {
                   13398:                                 $expire_role_result = 'ok';
                   13399:                             }
                   13400:                         }
                   13401:                     }
                   13402:                 }
1.443     albertel 13403:                 $result = $expire_role_result;
                   13404:             }
                   13405:         }
                   13406:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  13407:             $modify_section_result = 
                   13408:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13409:                                                            undef,undef,undef,$sec,
                   13410:                                                            $end,$start,'','',$cid,
                   13411:                                                            '',$context,$credits);
1.443     albertel 13412:             if ($modify_section_result =~ /^ok/) {
                   13413:                 if ($secchange == 1) {
1.628     raeburn  13414:                     if ($sec eq '') {
                   13415:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13416:                     } else {
                   13417:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13418:                     }
1.443     albertel 13419:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13420:                     if ($sec eq '') {
                   13421:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13422:                     } else {
                   13423:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13424:                     }
1.443     albertel 13425:                 } else {
1.628     raeburn  13426:                     if ($sec eq '') {
                   13427:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13428:                     } else {
                   13429:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13430:                     }
1.443     albertel 13431:                 }
                   13432:             } else {
1.628     raeburn  13433:                 if ($secchange) {       
                   13434:                     $$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;
                   13435:                 } else {
                   13436:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13437:                 }
1.443     albertel 13438:             }
                   13439:             $result = $modify_section_result;
                   13440:         } elsif ($secchange == 1) {
1.628     raeburn  13441:             if ($oldsec eq '') {
1.1075.2.20  raeburn  13442:                 $$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  13443:             } else {
                   13444:                 $$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;
                   13445:             }
1.626     raeburn  13446:             if ($expire_role_result eq 'refused') {
                   13447:                 my $newsecurl = '/'.$cid;
                   13448:                 $newsecurl =~ s/\_/\//g;
                   13449:                 if ($sec ne '') {
                   13450:                     $newsecurl.='/'.$sec;
                   13451:                 }
                   13452:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13453:                     if ($sec eq '') {
                   13454:                         $$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;
                   13455:                     } else {
                   13456:                         $$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;
                   13457:                     }
                   13458:                 }
                   13459:             }
1.443     albertel 13460:         }
                   13461:     } else {
1.626     raeburn  13462:         $$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 13463:         $result = "error: incomplete course id\n";
                   13464:     }
                   13465:     return $result;
                   13466: }
                   13467: 
1.1075.2.25  raeburn  13468: sub show_role_extent {
                   13469:     my ($scope,$context,$role) = @_;
                   13470:     $scope =~ s{^/}{};
                   13471:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   13472:     push(@courseroles,'co');
                   13473:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   13474:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   13475:         $scope =~ s{/}{_};
                   13476:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   13477:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   13478:         my ($audom,$auname) = split(/\//,$scope);
                   13479:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   13480:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   13481:     } else {
                   13482:         $scope =~ s{/$}{};
                   13483:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   13484:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   13485:     }
                   13486: }
                   13487: 
1.443     albertel 13488: ############################################################
                   13489: ############################################################
                   13490: 
1.566     albertel 13491: sub check_clone {
1.578     raeburn  13492:     my ($args,$linefeed) = @_;
1.566     albertel 13493:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13494:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13495:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13496:     my $clonemsg;
                   13497:     my $can_clone = 0;
1.944     raeburn  13498:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13499:     if ($lctype ne 'community') {
                   13500:         $lctype = 'course';
                   13501:     }
1.566     albertel 13502:     if ($clonehome eq 'no_host') {
1.944     raeburn  13503:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13504:             $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'});
                   13505:         } else {
                   13506:             $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'});
                   13507:         }     
1.566     albertel 13508:     } else {
                   13509: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13510:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13511:             if ($clonedesc{'type'} ne 'Community') {
                   13512:                  $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'});
                   13513:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13514:             }
                   13515:         }
1.882     raeburn  13516: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13517:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13518: 	    $can_clone = 1;
                   13519: 	} else {
                   13520: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13521: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13522: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13523:             if (grep(/^\*$/,@cloners)) {
                   13524:                 $can_clone = 1;
                   13525:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13526:                 $can_clone = 1;
                   13527:             } else {
1.908     raeburn  13528:                 my $ccrole = 'cc';
1.944     raeburn  13529:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13530:                     $ccrole = 'co';
                   13531:                 }
1.578     raeburn  13532: 	        my %roleshash =
                   13533: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13534: 					 $args->{'ccdomain'},
1.908     raeburn  13535:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13536: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13537: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13538:                     $can_clone = 1;
                   13539:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13540:                     $can_clone = 1;
                   13541:                 } else {
1.944     raeburn  13542:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13543:                         $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'});
                   13544:                     } else {
                   13545:                         $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'});
                   13546:                     }
1.578     raeburn  13547: 	        }
1.566     albertel 13548: 	    }
1.578     raeburn  13549:         }
1.566     albertel 13550:     }
                   13551:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13552: }
                   13553: 
1.444     albertel 13554: sub construct_course {
1.885     raeburn  13555:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 13556:     my $outcome;
1.541     raeburn  13557:     my $linefeed =  '<br />'."\n";
                   13558:     if ($context eq 'auto') {
                   13559:         $linefeed = "\n";
                   13560:     }
1.566     albertel 13561: 
                   13562: #
                   13563: # Are we cloning?
                   13564: #
                   13565:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13566:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13567: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13568: 	if ($context ne 'auto') {
1.578     raeburn  13569:             if ($clonemsg ne '') {
                   13570: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13571:             }
1.566     albertel 13572: 	}
                   13573: 	$outcome .= $clonemsg.$linefeed;
                   13574: 
                   13575:         if (!$can_clone) {
                   13576: 	    return (0,$outcome);
                   13577: 	}
                   13578:     }
                   13579: 
1.444     albertel 13580: #
                   13581: # Open course
                   13582: #
                   13583:     my $crstype = lc($args->{'crstype'});
                   13584:     my %cenv=();
                   13585:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13586:                                              $args->{'cdescr'},
                   13587:                                              $args->{'curl'},
                   13588:                                              $args->{'course_home'},
                   13589:                                              $args->{'nonstandard'},
                   13590:                                              $args->{'crscode'},
                   13591:                                              $args->{'ccuname'}.':'.
                   13592:                                              $args->{'ccdomain'},
1.882     raeburn  13593:                                              $args->{'crstype'},
1.885     raeburn  13594:                                              $cnum,$context,$category);
1.444     albertel 13595: 
                   13596:     # Note: The testing routines depend on this being output; see 
                   13597:     # Utils::Course. This needs to at least be output as a comment
                   13598:     # if anyone ever decides to not show this, and Utils::Course::new
                   13599:     # will need to be suitably modified.
1.541     raeburn  13600:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13601:     if ($$courseid =~ /^error:/) {
                   13602:         return (0,$outcome);
                   13603:     }
                   13604: 
1.444     albertel 13605: #
                   13606: # Check if created correctly
                   13607: #
1.479     albertel 13608:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13609:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13610:     if ($crsuhome eq 'no_host') {
                   13611:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13612:         return (0,$outcome);
                   13613:     }
1.541     raeburn  13614:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13615: 
1.444     albertel 13616: #
1.566     albertel 13617: # Do the cloning
                   13618: #   
                   13619:     if ($can_clone && $cloneid) {
                   13620: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13621: 	if ($context ne 'auto') {
                   13622: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13623: 	}
                   13624: 	$outcome .= $clonemsg.$linefeed;
                   13625: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13626: # Copy all files
1.637     www      13627: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13628: # Restore URL
1.566     albertel 13629: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13630: # Restore title
1.566     albertel 13631: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13632: # Restore creation date, creator and creation context.
                   13633:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13634:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13635:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13636: # Mark as cloned
1.566     albertel 13637: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13638: # Need to clone grading mode
                   13639:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13640:         $cenv{'grading'}=$newenv{'grading'};
                   13641: # Do not clone these environment entries
                   13642:         &Apache::lonnet::del('environment',
                   13643:                   ['default_enrollment_start_date',
                   13644:                    'default_enrollment_end_date',
                   13645:                    'question.email',
                   13646:                    'policy.email',
                   13647:                    'comment.email',
                   13648:                    'pch.users.denied',
1.725     raeburn  13649:                    'plc.users.denied',
                   13650:                    'hidefromcat',
1.1075.2.36  raeburn  13651:                    'checkforpriv',
1.725     raeburn  13652:                    'categories'],
1.638     www      13653:                    $$crsudom,$$crsunum);
1.444     albertel 13654:     }
1.566     albertel 13655: 
1.444     albertel 13656: #
                   13657: # Set environment (will override cloned, if existing)
                   13658: #
                   13659:     my @sections = ();
                   13660:     my @xlists = ();
                   13661:     if ($args->{'crstype'}) {
                   13662:         $cenv{'type'}=$args->{'crstype'};
                   13663:     }
                   13664:     if ($args->{'crsid'}) {
                   13665:         $cenv{'courseid'}=$args->{'crsid'};
                   13666:     }
                   13667:     if ($args->{'crscode'}) {
                   13668:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   13669:     }
                   13670:     if ($args->{'crsquota'} ne '') {
                   13671:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   13672:     } else {
                   13673:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   13674:     }
                   13675:     if ($args->{'ccuname'}) {
                   13676:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   13677:                                         ':'.$args->{'ccdomain'};
                   13678:     } else {
                   13679:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   13680:     }
1.1075.2.31  raeburn  13681:     if ($args->{'defaultcredits'}) {
                   13682:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   13683:     }
1.444     albertel 13684:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   13685:     if ($args->{'crssections'}) {
                   13686:         $cenv{'internal.sectionnums'} = '';
                   13687:         if ($args->{'crssections'} =~ m/,/) {
                   13688:             @sections = split/,/,$args->{'crssections'};
                   13689:         } else {
                   13690:             $sections[0] = $args->{'crssections'};
                   13691:         }
                   13692:         if (@sections > 0) {
                   13693:             foreach my $item (@sections) {
                   13694:                 my ($sec,$gp) = split/:/,$item;
                   13695:                 my $class = $args->{'crscode'}.$sec;
                   13696:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   13697:                 $cenv{'internal.sectionnums'} .= $item.',';
                   13698:                 unless ($addcheck eq 'ok') {
                   13699:                     push @badclasses, $class;
                   13700:                 }
                   13701:             }
                   13702:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   13703:         }
                   13704:     }
                   13705: # do not hide course coordinator from staff listing, 
                   13706: # even if privileged
                   13707:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  13708: # add course coordinator's domain to domains to check for privileged users
                   13709: # if different to course domain
                   13710:     if ($$crsudom ne $args->{'ccdomain'}) {
                   13711:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   13712:     }
1.444     albertel 13713: # add crosslistings
                   13714:     if ($args->{'crsxlist'}) {
                   13715:         $cenv{'internal.crosslistings'}='';
                   13716:         if ($args->{'crsxlist'} =~ m/,/) {
                   13717:             @xlists = split/,/,$args->{'crsxlist'};
                   13718:         } else {
                   13719:             $xlists[0] = $args->{'crsxlist'};
                   13720:         }
                   13721:         if (@xlists > 0) {
                   13722:             foreach my $item (@xlists) {
                   13723:                 my ($xl,$gp) = split/:/,$item;
                   13724:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   13725:                 $cenv{'internal.crosslistings'} .= $item.',';
                   13726:                 unless ($addcheck eq 'ok') {
                   13727:                     push @badclasses, $xl;
                   13728:                 }
                   13729:             }
                   13730:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   13731:         }
                   13732:     }
                   13733:     if ($args->{'autoadds'}) {
                   13734:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   13735:     }
                   13736:     if ($args->{'autodrops'}) {
                   13737:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   13738:     }
                   13739: # check for notification of enrollment changes
                   13740:     my @notified = ();
                   13741:     if ($args->{'notify_owner'}) {
                   13742:         if ($args->{'ccuname'} ne '') {
                   13743:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   13744:         }
                   13745:     }
                   13746:     if ($args->{'notify_dc'}) {
                   13747:         if ($uname ne '') { 
1.630     raeburn  13748:             push(@notified,$uname.':'.$udom);
1.444     albertel 13749:         }
                   13750:     }
                   13751:     if (@notified > 0) {
                   13752:         my $notifylist;
                   13753:         if (@notified > 1) {
                   13754:             $notifylist = join(',',@notified);
                   13755:         } else {
                   13756:             $notifylist = $notified[0];
                   13757:         }
                   13758:         $cenv{'internal.notifylist'} = $notifylist;
                   13759:     }
                   13760:     if (@badclasses > 0) {
                   13761:         my %lt=&Apache::lonlocal::texthash(
                   13762:                 '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',
                   13763:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   13764:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   13765:         );
1.541     raeburn  13766:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   13767:                            ' ('.$lt{'adby'}.')';
                   13768:         if ($context eq 'auto') {
                   13769:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 13770:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  13771:             foreach my $item (@badclasses) {
                   13772:                 if ($context eq 'auto') {
                   13773:                     $outcome .= " - $item\n";
                   13774:                 } else {
                   13775:                     $outcome .= "<li>$item</li>\n";
                   13776:                 }
                   13777:             }
                   13778:             if ($context eq 'auto') {
                   13779:                 $outcome .= $linefeed;
                   13780:             } else {
1.566     albertel 13781:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  13782:             }
                   13783:         } 
1.444     albertel 13784:     }
                   13785:     if ($args->{'no_end_date'}) {
                   13786:         $args->{'endaccess'} = 0;
                   13787:     }
                   13788:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   13789:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   13790:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   13791:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   13792:     if ($args->{'showphotos'}) {
                   13793:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   13794:     }
                   13795:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   13796:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   13797:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   13798:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  13799:             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'); 
                   13800:             if ($context eq 'auto') {
                   13801:                 $outcome .= $krb_msg;
                   13802:             } else {
1.566     albertel 13803:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  13804:             }
                   13805:             $outcome .= $linefeed;
1.444     albertel 13806:         }
                   13807:     }
                   13808:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   13809:        if ($args->{'setpolicy'}) {
                   13810:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13811:        }
                   13812:        if ($args->{'setcontent'}) {
                   13813:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13814:        }
                   13815:     }
                   13816:     if ($args->{'reshome'}) {
                   13817: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   13818: 	$cenv{'reshome'}=~s/\/+$/\//;
                   13819:     }
                   13820: #
                   13821: # course has keyed access
                   13822: #
                   13823:     if ($args->{'setkeys'}) {
                   13824:        $cenv{'keyaccess'}='yes';
                   13825:     }
                   13826: # if specified, key authority is not course, but user
                   13827: # only active if keyaccess is yes
                   13828:     if ($args->{'keyauth'}) {
1.487     albertel 13829: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   13830: 	$user = &LONCAPA::clean_username($user);
                   13831: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     13832: 	if ($user ne '' && $domain ne '') {
1.487     albertel 13833: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 13834: 	}
                   13835:     }
                   13836: 
                   13837:     if ($args->{'disresdis'}) {
                   13838:         $cenv{'pch.roles.denied'}='st';
                   13839:     }
                   13840:     if ($args->{'disablechat'}) {
                   13841:         $cenv{'plc.roles.denied'}='st';
                   13842:     }
                   13843: 
                   13844:     # Record we've not yet viewed the Course Initialization Helper for this 
                   13845:     # course
                   13846:     $cenv{'course.helper.not.run'} = 1;
                   13847:     #
                   13848:     # Use new Randomseed
                   13849:     #
                   13850:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   13851:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   13852:     #
                   13853:     # The encryption code and receipt prefix for this course
                   13854:     #
                   13855:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   13856:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   13857:     #
                   13858:     # By default, use standard grading
                   13859:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   13860: 
1.541     raeburn  13861:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   13862:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13863: #
                   13864: # Open all assignments
                   13865: #
                   13866:     if ($args->{'openall'}) {
                   13867:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   13868:        my %storecontent = ($storeunder         => time,
                   13869:                            $storeunder.'.type' => 'date_start');
                   13870:        
                   13871:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  13872:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13873:    }
                   13874: #
                   13875: # Set first page
                   13876: #
                   13877:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   13878: 	    || ($cloneid)) {
1.445     albertel 13879: 	use LONCAPA::map;
1.444     albertel 13880: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 13881: 
                   13882: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   13883:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   13884: 
1.444     albertel 13885:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   13886:         my $title; my $url;
                   13887:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   13888: 	    $title=&mt('Syllabus');
1.444     albertel 13889:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   13890:         } else {
1.963     raeburn  13891:             $title=&mt('Table of Contents');
1.444     albertel 13892:             $url='/adm/navmaps';
                   13893:         }
1.445     albertel 13894: 
                   13895:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   13896: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   13897: 
                   13898: 	if ($errtext) { $fatal=2; }
1.541     raeburn  13899:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 13900:     }
1.566     albertel 13901: 
                   13902:     return (1,$outcome);
1.444     albertel 13903: }
                   13904: 
                   13905: ############################################################
                   13906: ############################################################
                   13907: 
1.953     droeschl 13908: #SD
                   13909: # only Community and Course, or anything else?
1.378     raeburn  13910: sub course_type {
                   13911:     my ($cid) = @_;
                   13912:     if (!defined($cid)) {
                   13913:         $cid = $env{'request.course.id'};
                   13914:     }
1.404     albertel 13915:     if (defined($env{'course.'.$cid.'.type'})) {
                   13916:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  13917:     } else {
                   13918:         return 'Course';
1.377     raeburn  13919:     }
                   13920: }
1.156     albertel 13921: 
1.406     raeburn  13922: sub group_term {
                   13923:     my $crstype = &course_type();
                   13924:     my %names = (
                   13925:                   'Course' => 'group',
1.865     raeburn  13926:                   'Community' => 'group',
1.406     raeburn  13927:                 );
                   13928:     return $names{$crstype};
                   13929: }
                   13930: 
1.902     raeburn  13931: sub course_types {
                   13932:     my @types = ('official','unofficial','community');
                   13933:     my %typename = (
                   13934:                          official   => 'Official course',
                   13935:                          unofficial => 'Unofficial course',
                   13936:                          community  => 'Community',
                   13937:                    );
                   13938:     return (\@types,\%typename);
                   13939: }
                   13940: 
1.156     albertel 13941: sub icon {
                   13942:     my ($file)=@_;
1.505     albertel 13943:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 13944:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 13945:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 13946:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   13947: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   13948: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13949: 	            $curfext.".gif") {
                   13950: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13951: 		$curfext.".gif";
                   13952: 	}
                   13953:     }
1.249     albertel 13954:     return &lonhttpdurl($iconname);
1.154     albertel 13955: } 
1.84      albertel 13956: 
1.575     albertel 13957: sub lonhttpdurl {
1.692     www      13958: #
                   13959: # Had been used for "small fry" static images on separate port 8080.
                   13960: # Modify here if lightweight http functionality desired again.
                   13961: # Currently eliminated due to increasing firewall issues.
                   13962: #
1.575     albertel 13963:     my ($url)=@_;
1.692     www      13964:     return $url;
1.215     albertel 13965: }
                   13966: 
1.213     albertel 13967: sub connection_aborted {
                   13968:     my ($r)=@_;
                   13969:     $r->print(" ");$r->rflush();
                   13970:     my $c = $r->connection;
                   13971:     return $c->aborted();
                   13972: }
                   13973: 
1.221     foxr     13974: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     13975: #    strings as 'strings'.
                   13976: sub escape_single {
1.221     foxr     13977:     my ($input) = @_;
1.223     albertel 13978:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     13979:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   13980:     return $input;
                   13981: }
1.223     albertel 13982: 
1.222     foxr     13983: #  Same as escape_single, but escape's "'s  This 
                   13984: #  can be used for  "strings"
                   13985: sub escape_double {
                   13986:     my ($input) = @_;
                   13987:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   13988:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   13989:     return $input;
                   13990: }
1.223     albertel 13991:  
1.222     foxr     13992: #   Escapes the last element of a full URL.
                   13993: sub escape_url {
                   13994:     my ($url)   = @_;
1.238     raeburn  13995:     my @urlslices = split(/\//, $url,-1);
1.369     www      13996:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 13997:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     13998: }
1.462     albertel 13999: 
1.820     raeburn  14000: sub compare_arrays {
                   14001:     my ($arrayref1,$arrayref2) = @_;
                   14002:     my (@difference,%count);
                   14003:     @difference = ();
                   14004:     %count = ();
                   14005:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14006:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14007:         foreach my $element (keys(%count)) {
                   14008:             if ($count{$element} == 1) {
                   14009:                 push(@difference,$element);
                   14010:             }
                   14011:         }
                   14012:     }
                   14013:     return @difference;
                   14014: }
                   14015: 
1.817     bisitz   14016: # -------------------------------------------------------- Initialize user login
1.462     albertel 14017: sub init_user_environment {
1.463     albertel 14018:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14019:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14020: 
                   14021:     my $public=($username eq 'public' && $domain eq 'public');
                   14022: 
                   14023: # See if old ID present, if so, remove
                   14024: 
1.1062    raeburn  14025:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14026:     my $now=time;
                   14027: 
                   14028:     if ($public) {
                   14029: 	my $max_public=100;
                   14030: 	my $oldest;
                   14031: 	my $oldest_time=0;
                   14032: 	for(my $next=1;$next<=$max_public;$next++) {
                   14033: 	    if (-e $lonids."/publicuser_$next.id") {
                   14034: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14035: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14036: 		    $oldest_time=$mtime;
                   14037: 		    $oldest=$next;
                   14038: 		}
                   14039: 	    } else {
                   14040: 		$cookie="publicuser_$next";
                   14041: 		last;
                   14042: 	    }
                   14043: 	}
                   14044: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14045:     } else {
1.463     albertel 14046: 	# if this isn't a robot, kill any existing non-robot sessions
                   14047: 	if (!$args->{'robot'}) {
                   14048: 	    opendir(DIR,$lonids);
                   14049: 	    while ($filename=readdir(DIR)) {
                   14050: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14051: 		    unlink($lonids.'/'.$filename);
                   14052: 		}
1.462     albertel 14053: 	    }
1.463     albertel 14054: 	    closedir(DIR);
1.462     albertel 14055: 	}
                   14056: # Give them a new cookie
1.463     albertel 14057: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14058: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14059: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14060:     
                   14061: # Initialize roles
                   14062: 
1.1062    raeburn  14063: 	($userroles,$firstaccenv,$timerintenv) = 
                   14064:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14065:     }
                   14066: # ------------------------------------ Check browser type and MathML capability
                   14067: 
                   14068:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   14069:         $clientunicode,$clientos) = &decode_user_agent($r);
                   14070: 
                   14071: # ------------------------------------------------------------- Get environment
                   14072: 
                   14073:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14074:     my ($tmp) = keys(%userenv);
                   14075:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14076:     } else {
                   14077: 	undef(%userenv);
                   14078:     }
                   14079:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14080: 	$form->{'interface'}=$userenv{'interface'};
                   14081:     }
                   14082:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14083: 
                   14084: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14085:     foreach my $option ('interface','localpath','localres') {
                   14086:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14087:     }
                   14088: # --------------------------------------------------------- Write first profile
                   14089: 
                   14090:     {
                   14091: 	my %initial_env = 
                   14092: 	    ("user.name"          => $username,
                   14093: 	     "user.domain"        => $domain,
                   14094: 	     "user.home"          => $authhost,
                   14095: 	     "browser.type"       => $clientbrowser,
                   14096: 	     "browser.version"    => $clientversion,
                   14097: 	     "browser.mathml"     => $clientmathml,
                   14098: 	     "browser.unicode"    => $clientunicode,
                   14099: 	     "browser.os"         => $clientos,
                   14100: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14101: 	     "request.course.fn"  => '',
                   14102: 	     "request.course.uri" => '',
                   14103: 	     "request.course.sec" => '',
                   14104: 	     "request.role"       => 'cm',
                   14105: 	     "request.role.adv"   => $env{'user.adv'},
                   14106: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14107: 
                   14108:         if ($form->{'localpath'}) {
                   14109: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14110: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14111:         }
                   14112: 	
                   14113: 	if ($form->{'interface'}) {
                   14114: 	    $form->{'interface'}=~s/\W//gs;
                   14115: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14116: 	    $env{'browser.interface'}=$form->{'interface'};
                   14117: 	}
                   14118: 
1.981     raeburn  14119:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14120:         my %domdef;
                   14121:         unless ($domain eq 'public') {
                   14122:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14123:         }
1.980     raeburn  14124: 
1.1075.2.7  raeburn  14125:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14126:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14127:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14128:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14129:         }
                   14130: 
1.864     raeburn  14131:         foreach my $crstype ('official','unofficial','community') {
1.765     raeburn  14132:             $userenv{'canrequest.'.$crstype} =
                   14133:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14134:                                                   'reload','requestcourses',
                   14135:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14136:         }
                   14137: 
1.1075.2.14  raeburn  14138:         $userenv{'canrequest.author'} =
                   14139:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14140:                                         'reload','requestauthor',
                   14141:                                         \%userenv,\%domdef,\%is_adv);
                   14142:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14143:                                              $domain,$username);
                   14144:         my $reqstatus = $reqauthor{'author_status'};
                   14145:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   14146:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14147:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14148:                                                   $reqauthor{'author'}{'timestamp'};
                   14149:             }
                   14150:         }
                   14151: 
1.462     albertel 14152: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14153: 
1.462     albertel 14154: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14155: 		 &GDBM_WRCREAT(),0640)) {
                   14156: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14157: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14158: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14159:             if (ref($firstaccenv) eq 'HASH') {
                   14160:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14161:             }
                   14162:             if (ref($timerintenv) eq 'HASH') {
                   14163:                 &_add_to_env(\%disk_env,$timerintenv);
                   14164:             }
1.463     albertel 14165: 	    if (ref($args->{'extra_env'})) {
                   14166: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14167: 	    }
1.462     albertel 14168: 	    untie(%disk_env);
                   14169: 	} else {
1.705     tempelho 14170: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14171: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14172: 	    return 'error: '.$!;
                   14173: 	}
                   14174:     }
                   14175:     $env{'request.role'}='cm';
                   14176:     $env{'request.role.adv'}=$env{'user.adv'};
                   14177:     $env{'browser.type'}=$clientbrowser;
                   14178: 
                   14179:     return $cookie;
                   14180: 
                   14181: }
                   14182: 
                   14183: sub _add_to_env {
                   14184:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14185:     if (ref($env_data) eq 'HASH') {
                   14186:         while (my ($key,$value) = each(%$env_data)) {
                   14187: 	    $idf->{$prefix.$key} = $value;
                   14188: 	    $env{$prefix.$key}   = $value;
                   14189:         }
1.462     albertel 14190:     }
                   14191: }
                   14192: 
1.685     tempelho 14193: # --- Get the symbolic name of a problem and the url
                   14194: sub get_symb {
                   14195:     my ($request,$silent) = @_;
1.726     raeburn  14196:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14197:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14198:     if ($symb eq '') {
                   14199:         if (!$silent) {
1.1071    raeburn  14200:             if (ref($request)) { 
                   14201:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14202:             }
1.685     tempelho 14203:             return ();
                   14204:         }
                   14205:     }
                   14206:     &Apache::lonenc::check_decrypt(\$symb);
                   14207:     return ($symb);
                   14208: }
                   14209: 
                   14210: # --------------------------------------------------------------Get annotation
                   14211: 
                   14212: sub get_annotation {
                   14213:     my ($symb,$enc) = @_;
                   14214: 
                   14215:     my $key = $symb;
                   14216:     if (!$enc) {
                   14217:         $key =
                   14218:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14219:     }
                   14220:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14221:     return $annotation{$key};
                   14222: }
                   14223: 
                   14224: sub clean_symb {
1.731     raeburn  14225:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14226: 
                   14227:     &Apache::lonenc::check_decrypt(\$symb);
                   14228:     my $enc = $env{'request.enc'};
1.731     raeburn  14229:     if ($delete_enc) {
1.730     raeburn  14230:         delete($env{'request.enc'});
                   14231:     }
1.685     tempelho 14232: 
                   14233:     return ($symb,$enc);
                   14234: }
1.462     albertel 14235: 
1.990     raeburn  14236: sub build_release_hashes {
                   14237:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14238:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14239:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14240:                   (ref($randomizetry) eq 'HASH'));
                   14241:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14242:         my ($item,$name,$value) = split(/:/,$key);
                   14243:         if ($item eq 'parameter') {
                   14244:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14245:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14246:                     push(@{$checkparms->{$name}},$value);
                   14247:                 }
                   14248:             } else {
                   14249:                 push(@{$checkparms->{$name}},$value);
                   14250:             }
                   14251:         } elsif ($item eq 'resourcetag') {
                   14252:             if ($name eq 'responsetype') {
                   14253:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14254:             }
                   14255:         } elsif ($item eq 'course') {
                   14256:             if ($name eq 'crstype') {
                   14257:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14258:             }
                   14259:         }
                   14260:     }
                   14261:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14262:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14263:     return;
                   14264: }
                   14265: 
1.1075.2.11  raeburn  14266: sub update_content_constraints {
                   14267:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14268:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14269:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14270:     my %checkresponsetypes;
                   14271:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14272:         my ($item,$name,$value) = split(/:/,$key);
                   14273:         if ($item eq 'resourcetag') {
                   14274:             if ($name eq 'responsetype') {
                   14275:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14276:             }
                   14277:         }
                   14278:     }
                   14279:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14280:     if (defined($navmap)) {
                   14281:         my %allresponses;
                   14282:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14283:             my %responses = $res->responseTypes();
                   14284:             foreach my $key (keys(%responses)) {
                   14285:                 next unless(exists($checkresponsetypes{$key}));
                   14286:                 $allresponses{$key} += $responses{$key};
                   14287:             }
                   14288:         }
                   14289:         foreach my $key (keys(%allresponses)) {
                   14290:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14291:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14292:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14293:             }
                   14294:         }
                   14295:         undef($navmap);
                   14296:     }
                   14297:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14298:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14299:     }
                   14300:     return;
                   14301: }
                   14302: 
1.1075.2.27  raeburn  14303: sub allmaps_incourse {
                   14304:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14305:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   14306:         $cid = $env{'request.course.id'};
                   14307:         $cdom = $env{'course.'.$cid.'.domain'};
                   14308:         $cnum = $env{'course.'.$cid.'.num'};
                   14309:         $chome = $env{'course.'.$cid.'.home'};
                   14310:     }
                   14311:     my %allmaps = ();
                   14312:     my $lastchange =
                   14313:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   14314:     if ($lastchange > $env{'request.course.tied'}) {
                   14315:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   14316:         unless ($ferr) {
                   14317:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   14318:         }
                   14319:     }
                   14320:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14321:     if (defined($navmap)) {
                   14322:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   14323:             $allmaps{$res->src()} = 1;
                   14324:         }
                   14325:     }
                   14326:     return \%allmaps;
                   14327: }
                   14328: 
1.1075.2.11  raeburn  14329: sub parse_supplemental_title {
                   14330:     my ($title) = @_;
                   14331: 
                   14332:     my ($foldertitle,$renametitle);
                   14333:     if ($title =~ /&amp;&amp;&amp;/) {
                   14334:         $title = &HTML::Entites::decode($title);
                   14335:     }
                   14336:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14337:         $renametitle=$4;
                   14338:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14339:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14340:         my $name =  &plainname($uname,$udom);
                   14341:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14342:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14343:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14344:             $name.': <br />'.$foldertitle;
                   14345:     }
                   14346:     if (wantarray) {
                   14347:         return ($title,$foldertitle,$renametitle);
                   14348:     }
                   14349:     return $title;
                   14350: }
                   14351: 
1.1075.2.18  raeburn  14352: sub symb_to_docspath {
                   14353:     my ($symb) = @_;
                   14354:     return unless ($symb);
                   14355:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14356:     if ($resurl=~/\.(sequence|page)$/) {
                   14357:         $mapurl=$resurl;
                   14358:     } elsif ($resurl eq 'adm/navmaps') {
                   14359:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14360:     }
                   14361:     my $mapresobj;
                   14362:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14363:     if (ref($navmap)) {
                   14364:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14365:     }
                   14366:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14367:     my $type=$2;
                   14368:     my $path;
                   14369:     if (ref($mapresobj)) {
                   14370:         my $pcslist = $mapresobj->map_hierarchy();
                   14371:         if ($pcslist ne '') {
                   14372:             foreach my $pc (split(/,/,$pcslist)) {
                   14373:                 next if ($pc <= 1);
                   14374:                 my $res = $navmap->getByMapPc($pc);
                   14375:                 if (ref($res)) {
                   14376:                     my $thisurl = $res->src();
                   14377:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14378:                     my $thistitle = $res->title();
                   14379:                     $path .= '&'.
                   14380:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   14381:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
                   14382:                              ':'.$res->randompick().
                   14383:                              ':'.$res->randomout().
                   14384:                              ':'.$res->encrypted().
                   14385:                              ':'.$res->randomorder().
                   14386:                              ':'.$res->is_page();
                   14387:                 }
                   14388:             }
                   14389:         }
                   14390:         $path =~ s/^\&//;
                   14391:         my $maptitle = $mapresobj->title();
                   14392:         if ($mapurl eq 'default') {
1.1075.2.38! raeburn  14393:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  14394:         }
                   14395:         $path .= (($path ne '')? '&' : '').
                   14396:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14397:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
                   14398:                  ':'.$mapresobj->randompick().
                   14399:                  ':'.$mapresobj->randomout().
                   14400:                  ':'.$mapresobj->encrypted().
                   14401:                  ':'.$mapresobj->randomorder().
                   14402:                  ':'.$mapresobj->is_page();
                   14403:     } else {
                   14404:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14405:         my $ispage = (($type eq 'page')? 1 : '');
                   14406:         if ($mapurl eq 'default') {
1.1075.2.38! raeburn  14407:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  14408:         }
                   14409:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14410:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   14411:     }
                   14412:     unless ($mapurl eq 'default') {
                   14413:         $path = 'default&'.
1.1075.2.38! raeburn  14414:                 &Apache::lonhtmlcommon::entity_encode('Main Content').
1.1075.2.18  raeburn  14415:                 ':::::&'.$path;
                   14416:     }
                   14417:     return $path;
                   14418: }
                   14419: 
1.1075.2.14  raeburn  14420: sub captcha_display {
                   14421:     my ($context,$lonhost) = @_;
                   14422:     my ($output,$error);
                   14423:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   14424:     if ($captcha eq 'original') {
                   14425:         $output = &create_captcha();
                   14426:         unless ($output) {
                   14427:             $error = 'captcha';
                   14428:         }
                   14429:     } elsif ($captcha eq 'recaptcha') {
                   14430:         $output = &create_recaptcha($pubkey);
                   14431:         unless ($output) {
                   14432:             $error = 'recaptcha';
                   14433:         }
                   14434:     }
                   14435:     return ($output,$error);
                   14436: }
                   14437: 
                   14438: sub captcha_response {
                   14439:     my ($context,$lonhost) = @_;
                   14440:     my ($captcha_chk,$captcha_error);
                   14441:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   14442:     if ($captcha eq 'original') {
                   14443:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14444:     } elsif ($captcha eq 'recaptcha') {
                   14445:         $captcha_chk = &check_recaptcha($privkey);
                   14446:     } else {
                   14447:         $captcha_chk = 1;
                   14448:     }
                   14449:     return ($captcha_chk,$captcha_error);
                   14450: }
                   14451: 
                   14452: sub get_captcha_config {
                   14453:     my ($context,$lonhost) = @_;
                   14454:     my ($captcha,$pubkey,$privkey,$hashtocheck);
                   14455:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14456:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14457:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   14458:     if ($context eq 'usercreation') {
                   14459:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14460:         if (ref($domconfig{$context}) eq 'HASH') {
                   14461:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14462:             if (ref($hashtocheck) eq 'HASH') {
                   14463:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14464:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14465:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14466:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14467:                     }
                   14468:                     if ($privkey && $pubkey) {
                   14469:                         $captcha = 'recaptcha';
                   14470:                     } else {
                   14471:                         $captcha = 'original';
                   14472:                     }
                   14473:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14474:                     $captcha = 'original';
                   14475:                 }
                   14476:             }
                   14477:         } else {
                   14478:             $captcha = 'captcha';
                   14479:         }
                   14480:     } elsif ($context eq 'login') {
                   14481:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14482:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14483:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14484:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   14485:             if ($privkey && $pubkey) {
                   14486:                 $captcha = 'recaptcha';
                   14487:             } else {
                   14488:                 $captcha = 'original';
                   14489:             }
                   14490:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14491:             $captcha = 'original';
                   14492:         }
                   14493:     }
                   14494:     return ($captcha,$pubkey,$privkey);
                   14495: }
                   14496: 
                   14497: sub create_captcha {
                   14498:     my %captcha_params = &captcha_settings();
                   14499:     my ($output,$maxtries,$tries) = ('',10,0);
                   14500:     while ($tries < $maxtries) {
                   14501:         $tries ++;
                   14502:         my $captcha = Authen::Captcha->new (
                   14503:                                            output_folder => $captcha_params{'output_dir'},
                   14504:                                            data_folder   => $captcha_params{'db_dir'},
                   14505:                                           );
                   14506:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14507: 
                   14508:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14509:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14510:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14511:                      '<input type="text" size="5" name="code" value="" /><br />'.
                   14512:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
                   14513:             last;
                   14514:         }
                   14515:     }
                   14516:     return $output;
                   14517: }
                   14518: 
                   14519: sub captcha_settings {
                   14520:     my %captcha_params = (
                   14521:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14522:                            www_output_dir => "/captchaspool",
                   14523:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14524:                            numchars       => '5',
                   14525:                          );
                   14526:     return %captcha_params;
                   14527: }
                   14528: 
                   14529: sub check_captcha {
                   14530:     my ($captcha_chk,$captcha_error);
                   14531:     my $code = $env{'form.code'};
                   14532:     my $md5sum = $env{'form.crypt'};
                   14533:     my %captcha_params = &captcha_settings();
                   14534:     my $captcha = Authen::Captcha->new(
                   14535:                       output_folder => $captcha_params{'output_dir'},
                   14536:                       data_folder   => $captcha_params{'db_dir'},
                   14537:                   );
1.1075.2.26  raeburn  14538:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  14539:     my %captcha_hash = (
                   14540:                         0       => 'Code not checked (file error)',
                   14541:                        -1      => 'Failed: code expired',
                   14542:                        -2      => 'Failed: invalid code (not in database)',
                   14543:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   14544:     );
                   14545:     if ($captcha_chk != 1) {
                   14546:         $captcha_error = $captcha_hash{$captcha_chk}
                   14547:     }
                   14548:     return ($captcha_chk,$captcha_error);
                   14549: }
                   14550: 
                   14551: sub create_recaptcha {
                   14552:     my ($pubkey) = @_;
                   14553:     my $captcha = Captcha::reCAPTCHA->new;
                   14554:     return $captcha->get_options_setter({theme => 'white'})."\n".
                   14555:            $captcha->get_html($pubkey).
                   14556:            &mt('If either word is hard to read, [_1] will replace them.',
                   14557:                '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   14558:            '<br /><br />';
                   14559: }
                   14560: 
                   14561: sub check_recaptcha {
                   14562:     my ($privkey) = @_;
                   14563:     my $captcha_chk;
                   14564:     my $captcha = Captcha::reCAPTCHA->new;
                   14565:     my $captcha_result =
                   14566:         $captcha->check_answer(
                   14567:                                 $privkey,
                   14568:                                 $ENV{'REMOTE_ADDR'},
                   14569:                                 $env{'form.recaptcha_challenge_field'},
                   14570:                                 $env{'form.recaptcha_response_field'},
                   14571:                               );
                   14572:     if ($captcha_result->{is_valid}) {
                   14573:         $captcha_chk = 1;
                   14574:     }
                   14575:     return $captcha_chk;
                   14576: }
                   14577: 
1.41      ng       14578: =pod
                   14579: 
                   14580: =back
                   14581: 
1.112     bowersj2 14582: =cut
1.41      ng       14583: 
1.112     bowersj2 14584: 1;
                   14585: __END__;
1.41      ng       14586: 

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