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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1107  ! raeburn     4: # $Id: loncommon.pm,v 1.1106 2012/12/22 15:37:02 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.479     albertel   70: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    71: use DateTime::TimeZone;
1.687     raeburn    72: use DateTime::Locale::Catalog;
1.1091    foxr       73: use Text::Aspell;
1.1094    raeburn    74: use Authen::Captcha;
                     75: use Captcha::reCAPTCHA;
1.117     www        76: 
1.517     raeburn    77: # ---------------------------------------------- Designs
                     78: use vars qw(%defaultdesign);
                     79: 
1.22      www        80: my $readit;
                     81: 
1.517     raeburn    82: 
1.157     matthew    83: ##
                     84: ## Global Variables
                     85: ##
1.46      matthew    86: 
1.643     foxr       87: 
                     88: # ----------------------------------------------- SSI with retries:
                     89: #
                     90: 
                     91: =pod
                     92: 
1.648     raeburn    93: =head1 Server Side include with retries:
1.643     foxr       94: 
                     95: =over 4
                     96: 
1.648     raeburn    97: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       98: 
                     99: Performs an ssi with some number of retries.  Retries continue either
                    100: until the result is ok or until the retry count supplied by the
                    101: caller is exhausted.  
                    102: 
                    103: Inputs:
1.648     raeburn   104: 
                    105: =over 4
                    106: 
1.643     foxr      107: resource   - Identifies the resource to insert.
1.648     raeburn   108: 
1.643     foxr      109: retries    - Count of the number of retries allowed.
1.648     raeburn   110: 
1.643     foxr      111: form       - Hash that identifies the rendering options.
                    112: 
1.648     raeburn   113: =back
                    114: 
                    115: Returns:
                    116: 
                    117: =over 4
                    118: 
1.643     foxr      119: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   120: 
1.643     foxr      121: response   - The response from the last attempt (which may or may not have been successful.
                    122: 
1.648     raeburn   123: =back
                    124: 
                    125: =back
                    126: 
1.643     foxr      127: =cut
                    128: 
                    129: sub ssi_with_retries {
                    130:     my ($resource, $retries, %form) = @_;
                    131: 
                    132: 
                    133:     my $ok = 0;			# True if we got a good response.
                    134:     my $content;
                    135:     my $response;
                    136: 
                    137:     # Try to get the ssi done. within the retries count:
                    138: 
                    139:     do {
                    140: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    141: 	$ok      = $response->is_success;
1.650     www       142:         if (!$ok) {
                    143:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    144:         }
1.643     foxr      145: 	$retries--;
                    146:     } while (!$ok && ($retries > 0));
                    147: 
                    148:     if (!$ok) {
                    149: 	$content = '';		# On error return an empty content.
                    150:     }
                    151:     return ($content, $response);
                    152: 
                    153: }
                    154: 
                    155: 
                    156: 
1.20      www       157: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  158: my %language;
1.124     www       159: my %supported_language;
1.1088    foxr      160: my %supported_codes;
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.1088    foxr      195:                 my ($key,$code,$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;
1.1088    foxr      199: 		    $supported_codes{$key}   = $code;
1.158     raeburn   200:                 }
1.1048    foxr      201: 		if ($latex) {
                    202: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      203: 		    $latex_language{$code} = $latex;
1.1048    foxr      204: 		}
1.158     raeburn   205:             }
                    206:             close($fh);
                    207:         }
1.12      harris41  208:     }
                    209: # ------------------------------------------------------------------ copyrights
                    210:     {
1.158     raeburn   211:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    212:                                   '/copyright.tab';
                    213:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  214:             while (my $line = <$fh>) {
                    215:                 next if ($line=~/^\#/);
                    216:                 chomp($line);
                    217:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   218:                 $cprtag{$key}=$val;
                    219:             }
                    220:             close($fh);
                    221:         }
1.12      harris41  222:     }
1.351     www       223: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  224:     {
                    225:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    226:                                   '/source_copyright.tab';
                    227:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  228:             while (my $line = <$fh>) {
                    229:                 next if ($line =~ /^\#/);
                    230:                 chomp($line);
                    231:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  232:                 $scprtag{$key}=$val;
                    233:             }
                    234:             close($fh);
                    235:         }
                    236:     }
1.63      www       237: 
1.517     raeburn   238: # -------------------------------------------------------------- default domain designs
1.63      www       239:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   240:     my $designfile = $designdir.'/default.tab';
                    241:     if ( open (my $fh,"<$designfile") ) {
                    242:         while (my $line = <$fh>) {
                    243:             next if ($line =~ /^\#/);
                    244:             chomp($line);
                    245:             my ($key,$val)=(split(/\=/,$line));
                    246:             if ($val) { $defaultdesign{$key}=$val; }
                    247:         }
                    248:         close($fh);
1.63      www       249:     }
                    250: 
1.15      harris41  251: # ------------------------------------------------------------- file categories
                    252:     {
1.158     raeburn   253:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    254:                                   '/filecategories.tab';
                    255:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  256: 	    while (my $line = <$fh>) {
                    257: 		next if ($line =~ /^\#/);
                    258: 		chomp($line);
                    259:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   260:                 push @{$category_extensions{lc($category)}},$extension;
                    261:             }
                    262:             close($fh);
                    263:         }
                    264: 
1.15      harris41  265:     }
1.12      harris41  266: # ------------------------------------------------------------------ file types
                    267:     {
1.158     raeburn   268:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    269:                '/filetypes.tab';
                    270:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  271:             while (my $line = <$fh>) {
                    272: 		next if ($line =~ /^\#/);
                    273: 		chomp($line);
                    274:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   275:                 if ($descr ne '') {
                    276:                     $fe{$ending}=lc($emb);
                    277:                     $fd{$ending}=$descr;
1.351     www       278:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   279:                 }
                    280:             }
                    281:             close($fh);
                    282:         }
1.12      harris41  283:     }
1.22      www       284:     &Apache::lonnet::logthis(
1.705     tempelho  285:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       286:     $readit=1;
1.46      matthew   287:     }  # end of unless($readit) 
1.32      matthew   288:     
                    289: }
1.112     bowersj2  290: 
1.42      matthew   291: ###############################################################
                    292: ##           HTML and Javascript Helper Functions            ##
                    293: ###############################################################
                    294: 
                    295: =pod 
                    296: 
1.112     bowersj2  297: =head1 HTML and Javascript Functions
1.42      matthew   298: 
1.112     bowersj2  299: =over 4
                    300: 
1.648     raeburn   301: =item * &browser_and_searcher_javascript()
1.112     bowersj2  302: 
                    303: X<browsing, javascript>X<searching, javascript>Returns a string
                    304: containing javascript with two functions, C<openbrowser> and
                    305: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    306: tags.
1.42      matthew   307: 
1.648     raeburn   308: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   309: 
                    310: inputs: formname, elementname, only, omit
                    311: 
                    312: formname and elementname indicate the name of the html form and name of
                    313: the element that the results of the browsing selection are to be placed in. 
                    314: 
                    315: Specifying 'only' will restrict the browser to displaying only files
1.185     www       316: with the given extension.  Can be a comma separated list.
1.42      matthew   317: 
                    318: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       319: with the given extension.  Can be a comma separated list.
1.42      matthew   320: 
1.648     raeburn   321: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   322: 
                    323: Inputs: formname, elementname
                    324: 
                    325: formname and elementname specify the name of the html form and the name
                    326: of the element the selection from the search results will be placed in.
1.542     raeburn   327: 
1.42      matthew   328: =cut
                    329: 
                    330: sub browser_and_searcher_javascript {
1.199     albertel  331:     my ($mode)=@_;
                    332:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  333:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   334:     return <<END;
1.219     albertel  335: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   336:     var editbrowser = null;
1.135     albertel  337:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       338:         var url = '$resurl/?';
1.42      matthew   339:         if (editbrowser == null) {
                    340:             url += 'launch=1&';
                    341:         }
                    342:         url += 'catalogmode=interactive&';
1.199     albertel  343:         url += 'mode=$mode&';
1.611     albertel  344:         url += 'inhibitmenu=yes&';
1.42      matthew   345:         url += 'form=' + formname + '&';
                    346:         if (only != null) {
                    347:             url += 'only=' + only + '&';
1.217     albertel  348:         } else {
                    349:             url += 'only=&';
                    350: 	}
1.42      matthew   351:         if (omit != null) {
                    352:             url += 'omit=' + omit + '&';
1.217     albertel  353:         } else {
                    354:             url += 'omit=&';
                    355: 	}
1.135     albertel  356:         if (titleelement != null) {
                    357:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  358:         } else {
                    359: 	    url += 'titleelement=&';
                    360: 	}
1.42      matthew   361:         url += 'element=' + elementname + '';
                    362:         var title = 'Browser';
1.435     albertel  363:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   364:         options += ',width=700,height=600';
                    365:         editbrowser = open(url,title,options,'1');
                    366:         editbrowser.focus();
                    367:     }
                    368:     var editsearcher;
1.135     albertel  369:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   370:         var url = '/adm/searchcat?';
                    371:         if (editsearcher == null) {
                    372:             url += 'launch=1&';
                    373:         }
                    374:         url += 'catalogmode=interactive&';
1.199     albertel  375:         url += 'mode=$mode&';
1.42      matthew   376:         url += 'form=' + formname + '&';
1.135     albertel  377:         if (titleelement != null) {
                    378:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  379:         } else {
                    380: 	    url += 'titleelement=&';
                    381: 	}
1.42      matthew   382:         url += 'element=' + elementname + '';
                    383:         var title = 'Search';
1.435     albertel  384:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   385:         options += ',width=700,height=600';
                    386:         editsearcher = open(url,title,options,'1');
                    387:         editsearcher.focus();
                    388:     }
1.219     albertel  389: // END LON-CAPA Internal -->
1.42      matthew   390: END
1.170     www       391: }
                    392: 
                    393: sub lastresurl {
1.258     albertel  394:     if ($env{'environment.lastresurl'}) {
                    395: 	return $env{'environment.lastresurl'}
1.170     www       396:     } else {
                    397: 	return '/res';
                    398:     }
                    399: }
                    400: 
                    401: sub storeresurl {
                    402:     my $resurl=&Apache::lonnet::clutter(shift);
                    403:     unless ($resurl=~/^\/res/) { return 0; }
                    404:     $resurl=~s/\/$//;
                    405:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   406:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       407:     return 1;
1.42      matthew   408: }
                    409: 
1.74      www       410: sub studentbrowser_javascript {
1.111     www       411:    unless (
1.258     albertel  412:             (($env{'request.course.id'}) && 
1.302     albertel  413:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    414: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    415: 					  '/'.$env{'request.course.sec'})
                    416: 	      ))
1.258     albertel  417:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       418:           ) { return ''; }  
1.74      www       419:    return (<<'ENDSTDBRW');
1.776     bisitz    420: <script type="text/javascript" language="Javascript">
1.824     bisitz    421: // <![CDATA[
1.74      www       422:     var stdeditbrowser;
1.999     www       423:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       424:         var url = '/adm/pickstudent?';
                    425:         var filter;
1.558     albertel  426: 	if (!ignorefilter) {
                    427: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    428: 	}
1.74      www       429:         if (filter != null) {
                    430:            if (filter != '') {
                    431:                url += 'filter='+filter+'&';
                    432: 	   }
                    433:         }
                    434:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       435:                                     '&udomelement='+udom+
                    436:                                     '&clicker='+clicker;
1.111     www       437: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   438:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       439:         var title = 'Student_Browser';
1.74      www       440:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    441:         options += ',width=700,height=600';
                    442:         stdeditbrowser = open(url,title,options,'1');
                    443:         stdeditbrowser.focus();
                    444:     }
1.824     bisitz    445: // ]]>
1.74      www       446: </script>
                    447: ENDSTDBRW
                    448: }
1.42      matthew   449: 
1.1003    www       450: sub resourcebrowser_javascript {
                    451:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       452:    return (<<'ENDRESBRW');
1.1003    www       453: <script type="text/javascript" language="Javascript">
                    454: // <![CDATA[
                    455:     var reseditbrowser;
1.1004    www       456:     function openresbrowser(formname,reslink) {
1.1005    www       457:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       458:         var title = 'Resource_Browser';
                    459:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       460:         options += ',width=700,height=500';
1.1004    www       461:         reseditbrowser = open(url,title,options,'1');
                    462:         reseditbrowser.focus();
1.1003    www       463:     }
                    464: // ]]>
                    465: </script>
1.1004    www       466: ENDRESBRW
1.1003    www       467: }
                    468: 
1.74      www       469: sub selectstudent_link {
1.999     www       470:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    471:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    472:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    473:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  474:    if ($env{'request.course.id'}) {  
1.302     albertel  475:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    476: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    477: 					'/'.$env{'request.course.sec'})) {
1.111     www       478: 	   return '';
                    479:        }
1.999     www       480:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   481:        if ($courseadvonly)  {
                    482:            $callargs .= ",'',1,1";
                    483:        }
                    484:        return '<span class="LC_nobreak">'.
                    485:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    486:               &mt('Select User').'</a></span>';
1.74      www       487:    }
1.258     albertel  488:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       489:        $callargs .= ",'',1"; 
1.793     raeburn   490:        return '<span class="LC_nobreak">'.
                    491:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    492:               &mt('Select User').'</a></span>';
1.111     www       493:    }
                    494:    return '';
1.91      www       495: }
                    496: 
1.1004    www       497: sub selectresource_link {
                    498:    my ($form,$reslink,$arg)=@_;
                    499:    
                    500:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    501:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    502:    unless ($env{'request.course.id'}) { return $arg; }
                    503:    return '<span class="LC_nobreak">'.
                    504:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    505:               $arg.'</a></span>';
                    506: }
                    507: 
                    508: 
                    509: 
1.653     raeburn   510: sub authorbrowser_javascript {
                    511:     return <<"ENDAUTHORBRW";
1.776     bisitz    512: <script type="text/javascript" language="JavaScript">
1.824     bisitz    513: // <![CDATA[
1.653     raeburn   514: var stdeditbrowser;
                    515: 
                    516: function openauthorbrowser(formname,udom) {
                    517:     var url = '/adm/pickauthor?';
                    518:     url += 'form='+formname+'&roledom='+udom;
                    519:     var title = 'Author_Browser';
                    520:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    521:     options += ',width=700,height=600';
                    522:     stdeditbrowser = open(url,title,options,'1');
                    523:     stdeditbrowser.focus();
                    524: }
                    525: 
1.824     bisitz    526: // ]]>
1.653     raeburn   527: </script>
                    528: ENDAUTHORBRW
                    529: }
                    530: 
1.91      www       531: sub coursebrowser_javascript {
1.909     raeburn   532:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
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.905     raeburn   595:     if (($sec_element ne '') || ($role_element ne '')) {
                    596:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
1.876     raeburn   597:     }
                    598:     $output .= '
                    599: // ]]>
                    600: </script>';
                    601:     return $output;
                    602: }
                    603: 
                    604: sub javascript_index_functions {
                    605:     return <<"ENDJS";
                    606: 
                    607: function getFormIdByName(formname) {
                    608:     for (var i=0;i<document.forms.length;i++) {
                    609:         if (document.forms[i].name == formname) {
                    610:             return i;
                    611:         }
                    612:     }
                    613:     return -1;
                    614: }
                    615: 
                    616: function getIndexByName(formid,item) {
                    617:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    618:         if (document.forms[formid].elements[i].name == item) {
                    619:             return i;
                    620:         }
                    621:     }
                    622:     return -1;
                    623: }
1.468     raeburn   624: 
1.876     raeburn   625: function getDomainFromSelectbox(formname,udom) {
                    626:     var userdom;
                    627:     var formid = getFormIdByName(formname);
                    628:     if (formid > -1) {
                    629:         var domid = getIndexByName(formid,udom);
                    630:         if (domid > -1) {
                    631:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    632:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    633:             }
                    634:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    635:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   636:             }
                    637:         }
                    638:     }
1.876     raeburn   639:     return userdom;
                    640: }
                    641: 
                    642: ENDJS
1.468     raeburn   643: 
1.876     raeburn   644: }
                    645: 
1.1017    raeburn   646: sub javascript_array_indexof {
1.1018    raeburn   647:     return <<ENDJS;
1.1017    raeburn   648: <script type="text/javascript" language="JavaScript">
                    649: // <![CDATA[
                    650: 
                    651: if (!Array.prototype.indexOf) {
                    652:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    653:         "use strict";
                    654:         if (this === void 0 || this === null) {
                    655:             throw new TypeError();
                    656:         }
                    657:         var t = Object(this);
                    658:         var len = t.length >>> 0;
                    659:         if (len === 0) {
                    660:             return -1;
                    661:         }
                    662:         var n = 0;
                    663:         if (arguments.length > 0) {
                    664:             n = Number(arguments[1]);
1.1088    foxr      665:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   666:                 n = 0;
                    667:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    668:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    669:             }
                    670:         }
                    671:         if (n >= len) {
                    672:             return -1;
                    673:         }
                    674:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    675:         for (; k < len; k++) {
                    676:             if (k in t && t[k] === searchElement) {
                    677:                 return k;
                    678:             }
                    679:         }
                    680:         return -1;
                    681:     }
                    682: }
                    683: 
                    684: // ]]>
                    685: </script>
                    686: 
                    687: ENDJS
                    688: 
                    689: }
                    690: 
1.876     raeburn   691: sub userbrowser_javascript {
                    692:     my $id_functions = &javascript_index_functions();
                    693:     return <<"ENDUSERBRW";
                    694: 
1.888     raeburn   695: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   696:     var url = '/adm/pickuser?';
                    697:     var userdom = getDomainFromSelectbox(formname,udom);
                    698:     if (userdom != null) {
                    699:        if (userdom != '') {
                    700:            url += 'srchdom='+userdom+'&';
                    701:        }
                    702:     }
                    703:     url += 'form=' + formname + '&unameelement='+uname+
                    704:                                 '&udomelement='+udom+
                    705:                                 '&ulastelement='+ulast+
                    706:                                 '&ufirstelement='+ufirst+
                    707:                                 '&uemailelement='+uemail+
1.881     raeburn   708:                                 '&hideudomelement='+hideudom+
                    709:                                 '&coursedom='+crsdom;
1.888     raeburn   710:     if ((caller != null) && (caller != undefined)) {
                    711:         url += '&caller='+caller;
                    712:     }
1.876     raeburn   713:     var title = 'User_Browser';
                    714:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    715:     options += ',width=700,height=600';
                    716:     var stdeditbrowser = open(url,title,options,'1');
                    717:     stdeditbrowser.focus();
                    718: }
                    719: 
1.888     raeburn   720: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   721:     var formid = getFormIdByName(formname);
                    722:     if (formid > -1) {
1.888     raeburn   723:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   724:         var domid = getIndexByName(formid,udom);
                    725:         var hidedomid = getIndexByName(formid,origdom);
                    726:         if (hidedomid > -1) {
                    727:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   728:             var unameval = document.forms[formid].elements[unameid].value;
                    729:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    730:                 if (domid > -1) {
                    731:                     var slct = document.forms[formid].elements[domid];
                    732:                     if (slct.type == 'select-one') {
                    733:                         var i;
                    734:                         for (i=0;i<slct.length;i++) {
                    735:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    736:                         }
                    737:                     }
                    738:                     if (slct.type == 'hidden') {
                    739:                         slct.value = fixeddom;
1.876     raeburn   740:                     }
                    741:                 }
1.468     raeburn   742:             }
                    743:         }
                    744:     }
1.876     raeburn   745:     return;
                    746: }
                    747: 
                    748: $id_functions
                    749: ENDUSERBRW
1.468     raeburn   750: }
                    751: 
                    752: sub setsec_javascript {
1.905     raeburn   753:     my ($sec_element,$formname,$role_element) = @_;
                    754:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    755:         $communityrolestr);
                    756:     if ($role_element ne '') {
                    757:         my @allroles = ('st','ta','ep','in','ad');
                    758:         foreach my $crstype ('Course','Community') {
                    759:             if ($crstype eq 'Community') {
                    760:                 foreach my $role (@allroles) {
                    761:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    762:                 }
                    763:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    764:             } else {
                    765:                 foreach my $role (@allroles) {
                    766:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    767:                 }
                    768:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    769:             }
                    770:         }
                    771:         $rolestr = '"'.join('","',@allroles).'"';
                    772:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    773:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    774:     }
1.468     raeburn   775:     my $setsections = qq|
                    776: function setSect(sectionlist) {
1.629     raeburn   777:     var sectionsArray = new Array();
                    778:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    779:         sectionsArray = sectionlist.split(",");
                    780:     }
1.468     raeburn   781:     var numSections = sectionsArray.length;
                    782:     document.$formname.$sec_element.length = 0;
                    783:     if (numSections == 0) {
                    784:         document.$formname.$sec_element.multiple=false;
                    785:         document.$formname.$sec_element.size=1;
                    786:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    787:     } else {
                    788:         if (numSections == 1) {
                    789:             document.$formname.$sec_element.multiple=false;
                    790:             document.$formname.$sec_element.size=1;
                    791:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    792:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    793:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    794:         } else {
                    795:             for (var i=0; i<numSections; i++) {
                    796:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    797:             }
                    798:             document.$formname.$sec_element.multiple=true
                    799:             if (numSections < 3) {
                    800:                 document.$formname.$sec_element.size=numSections;
                    801:             } else {
                    802:                 document.$formname.$sec_element.size=3;
                    803:             }
                    804:             document.$formname.$sec_element.options[0].selected = false
                    805:         }
                    806:     }
1.91      www       807: }
1.905     raeburn   808: 
                    809: function setRole(crstype) {
1.468     raeburn   810: |;
1.905     raeburn   811:     if ($role_element eq '') {
                    812:         $setsections .= '    return;
                    813: }
                    814: ';
                    815:     } else {
                    816:         $setsections .= qq|
                    817:     var elementLength = document.$formname.$role_element.length;
                    818:     var allroles = Array($rolestr);
                    819:     var courserolenames = Array($courserolestr);
                    820:     var communityrolenames = Array($communityrolestr);
                    821:     if (elementLength != undefined) {
                    822:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    823:             if (crstype == 'Course') {
                    824:                 return;
                    825:             } else {
                    826:                 allroles[5] = 'co';
                    827:                 for (var i=0; i<6; i++) {
                    828:                     document.$formname.$role_element.options[i].value = allroles[i];
                    829:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    830:                 }
                    831:             }
                    832:         } else {
                    833:             if (crstype == 'Community') {
                    834:                 return;
                    835:             } else {
                    836:                 allroles[5] = 'cc';
                    837:                 for (var i=0; i<6; i++) {
                    838:                     document.$formname.$role_element.options[i].value = allroles[i];
                    839:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    840:                 }
                    841:             }
                    842:         }
                    843:     }
                    844:     return;
                    845: }
                    846: |;
                    847:     }
1.468     raeburn   848:     return $setsections;
                    849: }
                    850: 
1.91      www       851: sub selectcourse_link {
1.909     raeburn   852:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    853:        $typeelement) = @_;
                    854:    my $type = $selecttype;
1.871     raeburn   855:    my $linktext = &mt('Select Course');
                    856:    if ($selecttype eq 'Community') {
1.909     raeburn   857:        $linktext = &mt('Select Community');
1.906     raeburn   858:    } elsif ($selecttype eq 'Course/Community') {
                    859:        $linktext = &mt('Select Course/Community');
1.909     raeburn   860:        $type = '';
1.1019    raeburn   861:    } elsif ($selecttype eq 'Select') {
                    862:        $linktext = &mt('Select');
                    863:        $type = '';
1.871     raeburn   864:    }
1.787     bisitz    865:    return '<span class="LC_nobreak">'
                    866:          ."<a href='"
                    867:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    868:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   869:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   870:          ."'>".$linktext.'</a>'
1.787     bisitz    871:          .'</span>';
1.74      www       872: }
1.42      matthew   873: 
1.653     raeburn   874: sub selectauthor_link {
                    875:    my ($form,$udom)=@_;
                    876:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    877:           &mt('Select Author').'</a>';
                    878: }
                    879: 
1.876     raeburn   880: sub selectuser_link {
1.881     raeburn   881:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   882:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   883:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   884:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   885:            ');">'.$linktext.'</a>';
1.876     raeburn   886: }
                    887: 
1.273     raeburn   888: sub check_uncheck_jscript {
                    889:     my $jscript = <<"ENDSCRT";
                    890: function checkAll(field) {
                    891:     if (field.length > 0) {
                    892:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   893:             if (!field[i].disabled) { 
                    894:                 field[i].checked = true;
                    895:             }
1.273     raeburn   896:         }
                    897:     } else {
1.1093    raeburn   898:         if (!field.disabled) { 
                    899:             field.checked = true;
                    900:         }
1.273     raeburn   901:     }
                    902: }
                    903:  
                    904: function uncheckAll(field) {
                    905:     if (field.length > 0) {
                    906:         for (i = 0; i < field.length; i++) {
                    907:             field[i].checked = false ;
1.543     albertel  908:         }
                    909:     } else {
1.273     raeburn   910:         field.checked = false ;
                    911:     }
                    912: }
                    913: ENDSCRT
                    914:     return $jscript;
                    915: }
                    916: 
1.656     www       917: sub select_timezone {
1.659     raeburn   918:    my ($name,$selected,$onchange,$includeempty)=@_;
                    919:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    920:    if ($includeempty) {
                    921:        $output .= '<option value=""';
                    922:        if (($selected eq '') || ($selected eq 'local')) {
                    923:            $output .= ' selected="selected" ';
                    924:        }
                    925:        $output .= '> </option>';
                    926:    }
1.657     raeburn   927:    my @timezones = DateTime::TimeZone->all_names;
                    928:    foreach my $tzone (@timezones) {
                    929:        $output.= '<option value="'.$tzone.'"';
                    930:        if ($tzone eq $selected) {
                    931:            $output.=' selected="selected"';
                    932:        }
                    933:        $output.=">$tzone</option>\n";
1.656     www       934:    }
                    935:    $output.="</select>";
                    936:    return $output;
                    937: }
1.273     raeburn   938: 
1.687     raeburn   939: sub select_datelocale {
                    940:     my ($name,$selected,$onchange,$includeempty)=@_;
                    941:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    942:     if ($includeempty) {
                    943:         $output .= '<option value=""';
                    944:         if ($selected eq '') {
                    945:             $output .= ' selected="selected" ';
                    946:         }
                    947:         $output .= '> </option>';
                    948:     }
                    949:     my (@possibles,%locale_names);
                    950:     my @locales = DateTime::Locale::Catalog::Locales;
                    951:     foreach my $locale (@locales) {
                    952:         if (ref($locale) eq 'HASH') {
                    953:             my $id = $locale->{'id'};
                    954:             if ($id ne '') {
                    955:                 my $en_terr = $locale->{'en_territory'};
                    956:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   957:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   958:                 if (grep(/^en$/,@languages) || !@languages) {
                    959:                     if ($en_terr ne '') {
                    960:                         $locale_names{$id} = '('.$en_terr.')';
                    961:                     } elsif ($native_terr ne '') {
                    962:                         $locale_names{$id} = $native_terr;
                    963:                     }
                    964:                 } else {
                    965:                     if ($native_terr ne '') {
                    966:                         $locale_names{$id} = $native_terr.' ';
                    967:                     } elsif ($en_terr ne '') {
                    968:                         $locale_names{$id} = '('.$en_terr.')';
                    969:                     }
                    970:                 }
                    971:                 push (@possibles,$id);
                    972:             }
                    973:         }
                    974:     }
                    975:     foreach my $item (sort(@possibles)) {
                    976:         $output.= '<option value="'.$item.'"';
                    977:         if ($item eq $selected) {
                    978:             $output.=' selected="selected"';
                    979:         }
                    980:         $output.=">$item";
                    981:         if ($locale_names{$item} ne '') {
                    982:             $output.="  $locale_names{$item}</option>\n";
                    983:         }
                    984:         $output.="</option>\n";
                    985:     }
                    986:     $output.="</select>";
                    987:     return $output;
                    988: }
                    989: 
1.792     raeburn   990: sub select_language {
                    991:     my ($name,$selected,$includeempty) = @_;
                    992:     my %langchoices;
                    993:     if ($includeempty) {
                    994:         %langchoices = ('' => 'No language preference');
                    995:     }
                    996:     foreach my $id (&languageids()) {
                    997:         my $code = &supportedlanguagecode($id);
                    998:         if ($code) {
                    999:             $langchoices{$code} = &plainlanguagedescription($id);
                   1000:         }
                   1001:     }
1.970     raeburn  1002:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1003: }
                   1004: 
1.42      matthew  1005: =pod
1.36      matthew  1006: 
1.1088    foxr     1007: 
                   1008: =item * &list_languages()
                   1009: 
                   1010: Returns an array reference that is suitable for use in language prompters.
                   1011: Each array element is itself a two element array.  The first element
                   1012: is the language code.  The second element a descsriptiuon of the 
                   1013: language itself.  This is suitable for use in e.g.
                   1014: &Apache::edit::select_arg (once dereferenced that is).
                   1015: 
                   1016: =cut 
                   1017: 
                   1018: sub list_languages {
                   1019:     my @lang_choices;
                   1020: 
                   1021:     foreach my $id (&languageids()) {
                   1022: 	my $code = &supportedlanguagecode($id);
                   1023: 	if ($code) {
                   1024: 	    my $selector    = $supported_codes{$id};
                   1025: 	    my $description = &plainlanguagedescription($id);
                   1026: 	    push (@lang_choices, [$selector, $description]);
                   1027: 	}
                   1028:     }
                   1029:     return \@lang_choices;
                   1030: }
                   1031: 
                   1032: =pod
                   1033: 
1.648     raeburn  1034: =item * &linked_select_forms(...)
1.36      matthew  1035: 
                   1036: linked_select_forms returns a string containing a <script></script> block
                   1037: and html for two <select> menus.  The select menus will be linked in that
                   1038: changing the value of the first menu will result in new values being placed
                   1039: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1040: order unless a defined order is provided.
1.36      matthew  1041: 
                   1042: linked_select_forms takes the following ordered inputs:
                   1043: 
                   1044: =over 4
                   1045: 
1.112     bowersj2 1046: =item * $formname, the name of the <form> tag
1.36      matthew  1047: 
1.112     bowersj2 1048: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1049: 
1.112     bowersj2 1050: =item * $firstdefault, the default value for the first menu
1.36      matthew  1051: 
1.112     bowersj2 1052: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1053: 
1.112     bowersj2 1054: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1055: 
1.112     bowersj2 1056: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1057: 
1.609     raeburn  1058: =item * $menuorder, the order of values in the first menu
                   1059: 
1.41      ng       1060: =back 
                   1061: 
1.36      matthew  1062: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1063: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1064: values for the first select menu.  The text that coincides with the 
1.41      ng       1065: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1066: and text for the second menu are given in the hash pointed to by 
                   1067: $menu{$choice1}->{'select2'}.  
                   1068: 
1.112     bowersj2 1069:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1070:                        default => "B3",
                   1071:                        select2 => { 
                   1072:                            B1 => "Choice B1",
                   1073:                            B2 => "Choice B2",
                   1074:                            B3 => "Choice B3",
                   1075:                            B4 => "Choice B4"
1.609     raeburn  1076:                            },
                   1077:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1078:                    },
                   1079:                A2 => { text =>"Choice A2" ,
                   1080:                        default => "C2",
                   1081:                        select2 => { 
                   1082:                            C1 => "Choice C1",
                   1083:                            C2 => "Choice C2",
                   1084:                            C3 => "Choice C3"
1.609     raeburn  1085:                            },
                   1086:                        order => ['C2','C1','C3'],
1.112     bowersj2 1087:                    },
                   1088:                A3 => { text =>"Choice A3" ,
                   1089:                        default => "D6",
                   1090:                        select2 => { 
                   1091:                            D1 => "Choice D1",
                   1092:                            D2 => "Choice D2",
                   1093:                            D3 => "Choice D3",
                   1094:                            D4 => "Choice D4",
                   1095:                            D5 => "Choice D5",
                   1096:                            D6 => "Choice D6",
                   1097:                            D7 => "Choice D7"
1.609     raeburn  1098:                            },
                   1099:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1100:                    }
                   1101:                );
1.36      matthew  1102: 
                   1103: =cut
                   1104: 
                   1105: sub linked_select_forms {
                   1106:     my ($formname,
                   1107:         $middletext,
                   1108:         $firstdefault,
                   1109:         $firstselectname,
                   1110:         $secondselectname, 
1.609     raeburn  1111:         $hashref,
                   1112:         $menuorder,
1.36      matthew  1113:         ) = @_;
                   1114:     my $second = "document.$formname.$secondselectname";
                   1115:     my $first = "document.$formname.$firstselectname";
                   1116:     # output the javascript to do the changing
                   1117:     my $result = '';
1.776     bisitz   1118:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1119:     $result.="// <![CDATA[\n";
1.36      matthew  1120:     $result.="var select2data = new Object();\n";
                   1121:     $" = '","';
                   1122:     my $debug = '';
                   1123:     foreach my $s1 (sort(keys(%$hashref))) {
                   1124:         $result.="select2data.d_$s1 = new Object();\n";        
                   1125:         $result.="select2data.d_$s1.def = new String('".
                   1126:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1127:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1128:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1129:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1130:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1131:         }
1.36      matthew  1132:         $result.="\"@s2values\");\n";
                   1133:         $result.="select2data.d_$s1.texts = new Array(";        
                   1134:         my @s2texts;
                   1135:         foreach my $value (@s2values) {
                   1136:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1137:         }
                   1138:         $result.="\"@s2texts\");\n";
                   1139:     }
                   1140:     $"=' ';
                   1141:     $result.= <<"END";
                   1142: 
                   1143: function select1_changed() {
                   1144:     // Determine new choice
                   1145:     var newvalue = "d_" + $first.value;
                   1146:     // update select2
                   1147:     var values     = select2data[newvalue].values;
                   1148:     var texts      = select2data[newvalue].texts;
                   1149:     var select2def = select2data[newvalue].def;
                   1150:     var i;
                   1151:     // out with the old
                   1152:     for (i = 0; i < $second.options.length; i++) {
                   1153:         $second.options[i] = null;
                   1154:     }
                   1155:     // in with the nuclear
                   1156:     for (i=0;i<values.length; i++) {
                   1157:         $second.options[i] = new Option(values[i]);
1.143     matthew  1158:         $second.options[i].value = values[i];
1.36      matthew  1159:         $second.options[i].text = texts[i];
                   1160:         if (values[i] == select2def) {
                   1161:             $second.options[i].selected = true;
                   1162:         }
                   1163:     }
                   1164: }
1.824     bisitz   1165: // ]]>
1.36      matthew  1166: </script>
                   1167: END
                   1168:     # output the initial values for the selection lists
                   1169:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1.609     raeburn  1170:     my @order = sort(keys(%{$hashref}));
                   1171:     if (ref($menuorder) eq 'ARRAY') {
                   1172:         @order = @{$menuorder};
                   1173:     }
                   1174:     foreach my $value (@order) {
1.36      matthew  1175:         $result.="    <option value=\"$value\" ";
1.253     albertel 1176:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1177:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1178:     }
                   1179:     $result .= "</select>\n";
                   1180:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1181:     $result .= $middletext;
                   1182:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                   1183:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1184:     
                   1185:     my @secondorder = sort(keys(%select2));
                   1186:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1187:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1188:     }
                   1189:     foreach my $value (@secondorder) {
1.36      matthew  1190:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1191:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1192:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1193:     }
                   1194:     $result .= "</select>\n";
                   1195:     #    return $debug;
                   1196:     return $result;
                   1197: }   #  end of sub linked_select_forms {
                   1198: 
1.45      matthew  1199: =pod
1.44      bowersj2 1200: 
1.973     raeburn  1201: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1202: 
1.112     bowersj2 1203: Returns a string corresponding to an HTML link to the given help
                   1204: $topic, where $topic corresponds to the name of a .tex file in
                   1205: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1206: spaces. 
                   1207: 
                   1208: $text will optionally be linked to the same topic, allowing you to
                   1209: link text in addition to the graphic. If you do not want to link
                   1210: text, but wish to specify one of the later parameters, pass an
                   1211: empty string. 
                   1212: 
                   1213: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1214: the link will not open a new window. If false, the link will open
                   1215: a new window using Javascript. (Default is false.) 
                   1216: 
                   1217: $width and $height are optional numerical parameters that will
                   1218: override the width and height of the popped up window, which may
1.973     raeburn  1219: be useful for certain help topics with big pictures included.
                   1220: 
                   1221: $imgid is the id of the img tag used for the help icon. This may be
                   1222: used in a javascript call to switch the image src.  See 
                   1223: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1224: 
                   1225: =cut
                   1226: 
                   1227: sub help_open_topic {
1.973     raeburn  1228:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1229:     $text = "" if (not defined $text);
1.44      bowersj2 1230:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1231:     $width = 500 if (not defined $width);
1.44      bowersj2 1232:     $height = 400 if (not defined $height);
                   1233:     my $filename = $topic;
                   1234:     $filename =~ s/ /_/g;
                   1235: 
1.48      bowersj2 1236:     my $template = "";
                   1237:     my $link;
1.572     banghart 1238:     
1.159     www      1239:     $topic=~s/\W/\_/g;
1.44      bowersj2 1240: 
1.572     banghart 1241:     if (!$stayOnPage) {
1.1033    www      1242: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1243:     } elsif ($stayOnPage eq 'popup') {
                   1244:         $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 1245:     } else {
1.48      bowersj2 1246: 	$link = "/adm/help/${filename}.hlp";
                   1247:     }
                   1248: 
                   1249:     # Add the text
1.755     neumanie 1250:     if ($text ne "") {	
1.763     bisitz   1251: 	$template.='<span class="LC_help_open_topic">'
                   1252:                   .'<a target="_top" href="'.$link.'">'
                   1253:                   .$text.'</a>';
1.48      bowersj2 1254:     }
                   1255: 
1.763     bisitz   1256:     # (Always) Add the graphic
1.179     matthew  1257:     my $title = &mt('Online Help');
1.667     raeburn  1258:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1259:     if ($imgid ne '') {
                   1260:         $imgid = ' id="'.$imgid.'"';
                   1261:     }
1.763     bisitz   1262:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1263:               .'<img src="'.$helpicon.'" border="0"'
                   1264:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1265:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1266:               .' /></a>';
                   1267:     if ($text ne "") {	
                   1268:         $template.='</span>';
                   1269:     }
1.44      bowersj2 1270:     return $template;
                   1271: 
1.106     bowersj2 1272: }
                   1273: 
                   1274: # This is a quicky function for Latex cheatsheet editing, since it 
                   1275: # appears in at least four places
                   1276: sub helpLatexCheatsheet {
1.1037    www      1277:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1278:     my $out;
1.106     bowersj2 1279:     my $addOther = '';
1.732     raeburn  1280:     if ($topic) {
1.1037    www      1281: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1282:     }
                   1283:     $out = '<span>' # Start cheatsheet
                   1284: 	  .$addOther
                   1285:           .'<span>'
1.1037    www      1286: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1287: 	  .'</span> <span>'
1.1037    www      1288: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1289: 	  .'</span>';
1.732     raeburn  1290:     unless ($not_author) {
1.763     bisitz   1291:         $out .= ' <span>'
1.1037    www      1292: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1293: 	       .'</span>';
1.732     raeburn  1294:     }
1.763     bisitz   1295:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1296:     return $out;
1.172     www      1297: }
                   1298: 
1.430     albertel 1299: sub general_help {
                   1300:     my $helptopic='Student_Intro';
                   1301:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1302: 	$helptopic='Authoring_Intro';
1.907     raeburn  1303:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1304: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1305:     } elsif ($env{'request.role'}=~/^dc/) {
                   1306:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1307:     }
                   1308:     return $helptopic;
                   1309: }
                   1310: 
                   1311: sub update_help_link {
                   1312:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1313:     my $origurl = $ENV{'REQUEST_URI'};
                   1314:     $origurl=~s|^/~|/priv/|;
                   1315:     my $timestamp = time;
                   1316:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1317:         $$datum = &escape($$datum);
                   1318:     }
                   1319: 
                   1320:     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";
                   1321:     my $output .= <<"ENDOUTPUT";
                   1322: <script type="text/javascript">
1.824     bisitz   1323: // <![CDATA[
1.430     albertel 1324: banner_link = '$banner_link';
1.824     bisitz   1325: // ]]>
1.430     albertel 1326: </script>
                   1327: ENDOUTPUT
                   1328:     return $output;
                   1329: }
                   1330: 
                   1331: # now just updates the help link and generates a blue icon
1.193     raeburn  1332: sub help_open_menu {
1.430     albertel 1333:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1334: 	= @_;    
1.949     droeschl 1335:     $stayOnPage = 1;
1.430     albertel 1336:     my $output;
                   1337:     if ($component_help) {
                   1338: 	if (!$text) {
                   1339: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1340: 				       $width,$height);
                   1341: 	} else {
                   1342: 	    my $help_text;
                   1343: 	    $help_text=&unescape($topic);
                   1344: 	    $output='<table><tr><td>'.
                   1345: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1346: 				 $width,$height).'</td></tr></table>';
                   1347: 	}
                   1348:     }
                   1349:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1350:     return $output.$banner_link;
                   1351: }
                   1352: 
                   1353: sub top_nav_help {
                   1354:     my ($text) = @_;
1.436     albertel 1355:     $text = &mt($text);
1.949     droeschl 1356:     my $stay_on_page = 1;
                   1357: 
1.572     banghart 1358:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1359: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1360:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1361: 
1.201     raeburn  1362:     my $title = &mt('Get help');
1.436     albertel 1363: 
                   1364:     return <<"END";
                   1365: $banner_link
                   1366:  <a href="$link" title="$title">$text</a>
                   1367: END
                   1368: }
                   1369: 
                   1370: sub help_menu_js {
                   1371:     my ($text) = @_;
1.949     droeschl 1372:     my $stayOnPage = 1;
1.436     albertel 1373:     my $width = 620;
                   1374:     my $height = 600;
1.430     albertel 1375:     my $helptopic=&general_help();
                   1376:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1377:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1378:     my $start_page =
                   1379:         &Apache::loncommon::start_page('Help Menu', undef,
                   1380: 				       {'frameset'    => 1,
                   1381: 					'js_ready'    => 1,
                   1382: 					'add_entries' => {
                   1383: 					    'border' => '0',
1.579     raeburn  1384: 					    'rows'   => "110,*",},});
1.331     albertel 1385:     my $end_page =
                   1386:         &Apache::loncommon::end_page({'frameset' => 1,
                   1387: 				      'js_ready' => 1,});
                   1388: 
1.436     albertel 1389:     my $template .= <<"ENDTEMPLATE";
                   1390: <script type="text/javascript">
1.877     bisitz   1391: // <![CDATA[
1.253     albertel 1392: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1393: var banner_link = '';
1.243     raeburn  1394: function helpMenu(target) {
                   1395:     var caller = this;
                   1396:     if (target == 'open') {
                   1397:         var newWindow = null;
                   1398:         try {
1.262     albertel 1399:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1400:         }
                   1401:         catch(error) {
                   1402:             writeHelp(caller);
                   1403:             return;
                   1404:         }
                   1405:         if (newWindow) {
                   1406:             caller = newWindow;
                   1407:         }
1.193     raeburn  1408:     }
1.243     raeburn  1409:     writeHelp(caller);
                   1410:     return;
                   1411: }
                   1412: function writeHelp(caller) {
1.1072    raeburn  1413:     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  1414:     caller.document.close()
                   1415:     caller.focus()
1.193     raeburn  1416: }
1.877     bisitz   1417: // END LON-CAPA Internal -->
1.253     albertel 1418: // ]]>
1.436     albertel 1419: </script>
1.193     raeburn  1420: ENDTEMPLATE
                   1421:     return $template;
                   1422: }
                   1423: 
1.172     www      1424: sub help_open_bug {
                   1425:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1426:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1427:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1428:     $text = "" if (not defined $text);
                   1429: 	$stayOnPage=1;
1.184     albertel 1430:     $width = 600 if (not defined $width);
                   1431:     $height = 600 if (not defined $height);
1.172     www      1432: 
                   1433:     $topic=~s/\W+/\+/g;
                   1434:     my $link='';
                   1435:     my $template='';
1.379     albertel 1436:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1437: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1438:     if (!$stayOnPage)
                   1439:     {
                   1440: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1441:     }
                   1442:     else
                   1443:     {
                   1444: 	$link = $url;
                   1445:     }
                   1446:     # Add the text
                   1447:     if ($text ne "")
                   1448:     {
                   1449: 	$template .= 
                   1450:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1451:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1452:     }
                   1453: 
                   1454:     # Add the graphic
1.179     matthew  1455:     my $title = &mt('Report a Bug');
1.215     albertel 1456:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1457:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1458:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1459: ENDTEMPLATE
                   1460:     if ($text ne '') { $template.='</td></tr></table>' };
                   1461:     return $template;
                   1462: 
                   1463: }
                   1464: 
                   1465: sub help_open_faq {
                   1466:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1467:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1468:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1469:     $text = "" if (not defined $text);
                   1470: 	$stayOnPage=1;
                   1471:     $width = 350 if (not defined $width);
                   1472:     $height = 400 if (not defined $height);
                   1473: 
                   1474:     $topic=~s/\W+/\+/g;
                   1475:     my $link='';
                   1476:     my $template='';
                   1477:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1478:     if (!$stayOnPage)
                   1479:     {
                   1480: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1481:     }
                   1482:     else
                   1483:     {
                   1484: 	$link = $url;
                   1485:     }
                   1486: 
                   1487:     # Add the text
                   1488:     if ($text ne "")
                   1489:     {
                   1490: 	$template .= 
1.173     www      1491:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1492:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1493:     }
                   1494: 
                   1495:     # Add the graphic
1.179     matthew  1496:     my $title = &mt('View the FAQ');
1.215     albertel 1497:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1498:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1499:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1500: ENDTEMPLATE
                   1501:     if ($text ne '') { $template.='</td></tr></table>' };
                   1502:     return $template;
                   1503: 
1.44      bowersj2 1504: }
1.37      matthew  1505: 
1.180     matthew  1506: ###############################################################
                   1507: ###############################################################
                   1508: 
1.45      matthew  1509: =pod
                   1510: 
1.648     raeburn  1511: =item * &change_content_javascript():
1.256     matthew  1512: 
                   1513: This and the next function allow you to create small sections of an
                   1514: otherwise static HTML page that you can update on the fly with
                   1515: Javascript, even in Netscape 4.
                   1516: 
                   1517: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1518: must be written to the HTML page once. It will prove the Javascript
                   1519: function "change(name, content)". Calling the change function with the
                   1520: name of the section 
                   1521: you want to update, matching the name passed to C<changable_area>, and
                   1522: the new content you want to put in there, will put the content into
                   1523: that area.
                   1524: 
                   1525: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1526: to contain room for the original contents. You need to "make space"
                   1527: for whatever changes you wish to make, and be B<sure> to check your
                   1528: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1529: it's adequate for updating a one-line status display, but little more.
                   1530: This script will set the space to 100% width, so you only need to
                   1531: worry about height in Netscape 4.
                   1532: 
                   1533: Modern browsers are much less limiting, and if you can commit to the
                   1534: user not using Netscape 4, this feature may be used freely with
                   1535: pretty much any HTML.
                   1536: 
                   1537: =cut
                   1538: 
                   1539: sub change_content_javascript {
                   1540:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1541:     if ($env{'browser.type'} eq 'netscape' &&
                   1542: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1543: 	return (<<NETSCAPE4);
                   1544: 	function change(name, content) {
                   1545: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1546: 	    doc.open();
                   1547: 	    doc.write(content);
                   1548: 	    doc.close();
                   1549: 	}
                   1550: NETSCAPE4
                   1551:     } else {
                   1552: 	# Otherwise, we need to use semi-standards-compliant code
                   1553: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1554: 	# is really scary, and every useful browser supports it
                   1555: 	return (<<DOMBASED);
                   1556: 	function change(name, content) {
                   1557: 	    element = document.getElementById(name);
                   1558: 	    element.innerHTML = content;
                   1559: 	}
                   1560: DOMBASED
                   1561:     }
                   1562: }
                   1563: 
                   1564: =pod
                   1565: 
1.648     raeburn  1566: =item * &changable_area($name,$origContent):
1.256     matthew  1567: 
                   1568: This provides a "changable area" that can be modified on the fly via
                   1569: the Javascript code provided in C<change_content_javascript>. $name is
                   1570: the name you will use to reference the area later; do not repeat the
                   1571: same name on a given HTML page more then once. $origContent is what
                   1572: the area will originally contain, which can be left blank.
                   1573: 
                   1574: =cut
                   1575: 
                   1576: sub changable_area {
                   1577:     my ($name, $origContent) = @_;
                   1578: 
1.258     albertel 1579:     if ($env{'browser.type'} eq 'netscape' &&
                   1580: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1581: 	# If this is netscape 4, we need to use the Layer tag
                   1582: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1583:     } else {
                   1584: 	return "<span id='$name'>$origContent</span>";
                   1585:     }
                   1586: }
                   1587: 
                   1588: =pod
                   1589: 
1.648     raeburn  1590: =item * &viewport_geometry_js 
1.590     raeburn  1591: 
                   1592: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1593: 
                   1594: =cut
                   1595: 
                   1596: 
                   1597: sub viewport_geometry_js { 
                   1598:     return <<"GEOMETRY";
                   1599: var Geometry = {};
                   1600: function init_geometry() {
                   1601:     if (Geometry.init) { return };
                   1602:     Geometry.init=1;
                   1603:     if (window.innerHeight) {
                   1604:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1605:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1606:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1607:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1608:     }
                   1609:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1610:         Geometry.getViewportHeight =
                   1611:             function() { return document.documentElement.clientHeight; };
                   1612:         Geometry.getViewportWidth =
                   1613:             function() { return document.documentElement.clientWidth; };
                   1614: 
                   1615:         Geometry.getHorizontalScroll =
                   1616:             function() { return document.documentElement.scrollLeft; };
                   1617:         Geometry.getVerticalScroll =
                   1618:             function() { return document.documentElement.scrollTop; };
                   1619:     }
                   1620:     else if (document.body.clientHeight) {
                   1621:         Geometry.getViewportHeight =
                   1622:             function() { return document.body.clientHeight; };
                   1623:         Geometry.getViewportWidth =
                   1624:             function() { return document.body.clientWidth; };
                   1625:         Geometry.getHorizontalScroll =
                   1626:             function() { return document.body.scrollLeft; };
                   1627:         Geometry.getVerticalScroll =
                   1628:             function() { return document.body.scrollTop; };
                   1629:     }
                   1630: }
                   1631: 
                   1632: GEOMETRY
                   1633: }
                   1634: 
                   1635: =pod
                   1636: 
1.648     raeburn  1637: =item * &viewport_size_js()
1.590     raeburn  1638: 
                   1639: 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. 
                   1640: 
                   1641: =cut
                   1642: 
                   1643: sub viewport_size_js {
                   1644:     my $geometry = &viewport_geometry_js();
                   1645:     return <<"DIMS";
                   1646: 
                   1647: $geometry
                   1648: 
                   1649: function getViewportDims(width,height) {
                   1650:     init_geometry();
                   1651:     width.value = Geometry.getViewportWidth();
                   1652:     height.value = Geometry.getViewportHeight();
                   1653:     return;
                   1654: }
                   1655: 
                   1656: DIMS
                   1657: }
                   1658: 
                   1659: =pod
                   1660: 
1.648     raeburn  1661: =item * &resize_textarea_js()
1.565     albertel 1662: 
                   1663: emits the needed javascript to resize a textarea to be as big as possible
                   1664: 
                   1665: creates a function resize_textrea that takes two IDs first should be
                   1666: the id of the element to resize, second should be the id of a div that
                   1667: surrounds everything that comes after the textarea, this routine needs
                   1668: to be attached to the <body> for the onload and onresize events.
                   1669: 
1.648     raeburn  1670: =back
1.565     albertel 1671: 
                   1672: =cut
                   1673: 
                   1674: sub resize_textarea_js {
1.590     raeburn  1675:     my $geometry = &viewport_geometry_js();
1.565     albertel 1676:     return <<"RESIZE";
                   1677:     <script type="text/javascript">
1.824     bisitz   1678: // <![CDATA[
1.590     raeburn  1679: $geometry
1.565     albertel 1680: 
1.588     albertel 1681: function getX(element) {
                   1682:     var x = 0;
                   1683:     while (element) {
                   1684: 	x += element.offsetLeft;
                   1685: 	element = element.offsetParent;
                   1686:     }
                   1687:     return x;
                   1688: }
                   1689: function getY(element) {
                   1690:     var y = 0;
                   1691:     while (element) {
                   1692: 	y += element.offsetTop;
                   1693: 	element = element.offsetParent;
                   1694:     }
                   1695:     return y;
                   1696: }
                   1697: 
                   1698: 
1.565     albertel 1699: function resize_textarea(textarea_id,bottom_id) {
                   1700:     init_geometry();
                   1701:     var textarea        = document.getElementById(textarea_id);
                   1702:     //alert(textarea);
                   1703: 
1.588     albertel 1704:     var textarea_top    = getY(textarea);
1.565     albertel 1705:     var textarea_height = textarea.offsetHeight;
                   1706:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1707:     var bottom_top      = getY(bottom);
1.565     albertel 1708:     var bottom_height   = bottom.offsetHeight;
                   1709:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1710:     var fudge           = 23;
1.565     albertel 1711:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1712:     if (new_height < 300) {
                   1713: 	new_height = 300;
                   1714:     }
                   1715:     textarea.style.height=new_height+'px';
                   1716: }
1.824     bisitz   1717: // ]]>
1.565     albertel 1718: </script>
                   1719: RESIZE
                   1720: 
                   1721: }
                   1722: 
                   1723: =pod
                   1724: 
1.256     matthew  1725: =head1 Excel and CSV file utility routines
                   1726: 
                   1727: =over 4
                   1728: 
                   1729: =cut
                   1730: 
                   1731: ###############################################################
                   1732: ###############################################################
                   1733: 
                   1734: =pod
                   1735: 
1.648     raeburn  1736: =item * &csv_translate($text) 
1.37      matthew  1737: 
1.185     www      1738: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1739: format.
                   1740: 
                   1741: =cut
                   1742: 
1.180     matthew  1743: ###############################################################
                   1744: ###############################################################
1.37      matthew  1745: sub csv_translate {
                   1746:     my $text = shift;
                   1747:     $text =~ s/\"/\"\"/g;
1.209     albertel 1748:     $text =~ s/\n/ /g;
1.37      matthew  1749:     return $text;
                   1750: }
1.180     matthew  1751: 
                   1752: ###############################################################
                   1753: ###############################################################
                   1754: 
                   1755: =pod
                   1756: 
1.648     raeburn  1757: =item * &define_excel_formats()
1.180     matthew  1758: 
                   1759: Define some commonly used Excel cell formats.
                   1760: 
                   1761: Currently supported formats:
                   1762: 
                   1763: =over 4
                   1764: 
                   1765: =item header
                   1766: 
                   1767: =item bold
                   1768: 
                   1769: =item h1
                   1770: 
                   1771: =item h2
                   1772: 
                   1773: =item h3
                   1774: 
1.256     matthew  1775: =item h4
                   1776: 
                   1777: =item i
                   1778: 
1.180     matthew  1779: =item date
                   1780: 
                   1781: =back
                   1782: 
                   1783: Inputs: $workbook
                   1784: 
                   1785: Returns: $format, a hash reference.
                   1786: 
1.1057    foxr     1787: 
1.180     matthew  1788: =cut
                   1789: 
                   1790: ###############################################################
                   1791: ###############################################################
                   1792: sub define_excel_formats {
                   1793:     my ($workbook) = @_;
                   1794:     my $format;
                   1795:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1796:                                                 bottom    => 1,
                   1797:                                                 align     => 'center');
                   1798:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1799:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1800:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1801:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1802:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1803:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1804:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1805:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1806:     return $format;
                   1807: }
                   1808: 
                   1809: ###############################################################
                   1810: ###############################################################
1.113     bowersj2 1811: 
                   1812: =pod
                   1813: 
1.648     raeburn  1814: =item * &create_workbook()
1.255     matthew  1815: 
                   1816: Create an Excel worksheet.  If it fails, output message on the
                   1817: request object and return undefs.
                   1818: 
                   1819: Inputs: Apache request object
                   1820: 
                   1821: Returns (undef) on failure, 
                   1822:     Excel worksheet object, scalar with filename, and formats 
                   1823:     from &Apache::loncommon::define_excel_formats on success
                   1824: 
                   1825: =cut
                   1826: 
                   1827: ###############################################################
                   1828: ###############################################################
                   1829: sub create_workbook {
                   1830:     my ($r) = @_;
                   1831:         #
                   1832:     # Create the excel spreadsheet
                   1833:     my $filename = '/prtspool/'.
1.258     albertel 1834:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1835:         time.'_'.rand(1000000000).'.xls';
                   1836:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1837:     if (! defined($workbook)) {
                   1838:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1839:         $r->print(
                   1840:             '<p class="LC_error">'
                   1841:            .&mt('Problems occurred in creating the new Excel file.')
                   1842:            .' '.&mt('This error has been logged.')
                   1843:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1844:            .'</p>'
                   1845:         );
1.255     matthew  1846:         return (undef);
                   1847:     }
                   1848:     #
1.1014    foxr     1849:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1850:     #
                   1851:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1852:     return ($workbook,$filename,$format);
                   1853: }
                   1854: 
                   1855: ###############################################################
                   1856: ###############################################################
                   1857: 
                   1858: =pod
                   1859: 
1.648     raeburn  1860: =item * &create_text_file()
1.113     bowersj2 1861: 
1.542     raeburn  1862: Create a file to write to and eventually make available to the user.
1.256     matthew  1863: If file creation fails, outputs an error message on the request object and 
                   1864: return undefs.
1.113     bowersj2 1865: 
1.256     matthew  1866: Inputs: Apache request object, and file suffix
1.113     bowersj2 1867: 
1.256     matthew  1868: Returns (undef) on failure, 
                   1869:     Filehandle and filename on success.
1.113     bowersj2 1870: 
                   1871: =cut
                   1872: 
1.256     matthew  1873: ###############################################################
                   1874: ###############################################################
                   1875: sub create_text_file {
                   1876:     my ($r,$suffix) = @_;
                   1877:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1878:     my $fh;
                   1879:     my $filename = '/prtspool/'.
1.258     albertel 1880:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1881:         time.'_'.rand(1000000000).'.'.$suffix;
                   1882:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1883:     if (! defined($fh)) {
                   1884:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1885:         $r->print(
                   1886:             '<p class="LC_error">'
                   1887:            .&mt('Problems occurred in creating the output file.')
                   1888:            .' '.&mt('This error has been logged.')
                   1889:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1890:            .'</p>'
                   1891:         );
1.113     bowersj2 1892:     }
1.256     matthew  1893:     return ($fh,$filename)
1.113     bowersj2 1894: }
                   1895: 
                   1896: 
1.256     matthew  1897: =pod 
1.113     bowersj2 1898: 
                   1899: =back
                   1900: 
                   1901: =cut
1.37      matthew  1902: 
                   1903: ###############################################################
1.33      matthew  1904: ##        Home server <option> list generating code          ##
                   1905: ###############################################################
1.35      matthew  1906: 
1.169     www      1907: # ------------------------------------------
                   1908: 
                   1909: sub domain_select {
                   1910:     my ($name,$value,$multiple)=@_;
                   1911:     my %domains=map { 
1.514     albertel 1912: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1913:     } &Apache::lonnet::all_domains();
1.169     www      1914:     if ($multiple) {
                   1915: 	$domains{''}=&mt('Any domain');
1.550     albertel 1916: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1917: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1918:     } else {
1.550     albertel 1919: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1920: 	return &select_form($name,$value,\%domains);
1.169     www      1921:     }
                   1922: }
                   1923: 
1.282     albertel 1924: #-------------------------------------------
                   1925: 
                   1926: =pod
                   1927: 
1.519     raeburn  1928: =head1 Routines for form select boxes
                   1929: 
                   1930: =over 4
                   1931: 
1.648     raeburn  1932: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1933: 
                   1934: Returns a string containing a <select> element int multiple mode
                   1935: 
                   1936: 
                   1937: Args:
                   1938:   $name - name of the <select> element
1.506     raeburn  1939:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1940:   $size - number of rows long the select element is
1.283     albertel 1941:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1942:           (shown text should already have been &mt())
1.506     raeburn  1943:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1944: 
1.282     albertel 1945: =cut
                   1946: 
                   1947: #-------------------------------------------
1.169     www      1948: sub multiple_select_form {
1.284     albertel 1949:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1950:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1951:     my $output='';
1.191     matthew  1952:     if (! defined($size)) {
                   1953:         $size = 4;
1.283     albertel 1954:         if (scalar(keys(%$hash))<4) {
                   1955:             $size = scalar(keys(%$hash));
1.191     matthew  1956:         }
                   1957:     }
1.734     bisitz   1958:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1959:     my @order;
1.506     raeburn  1960:     if (ref($order) eq 'ARRAY')  {
                   1961:         @order = @{$order};
                   1962:     } else {
                   1963:         @order = sort(keys(%$hash));
1.501     banghart 1964:     }
                   1965:     if (exists($$hash{'select_form_order'})) {
                   1966:         @order = @{$$hash{'select_form_order'}};
                   1967:     }
                   1968:         
1.284     albertel 1969:     foreach my $key (@order) {
1.356     albertel 1970:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1971:         $output.='selected="selected" ' if ($selected{$key});
                   1972:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1973:     }
                   1974:     $output.="</select>\n";
                   1975:     return $output;
                   1976: }
                   1977: 
1.88      www      1978: #-------------------------------------------
                   1979: 
                   1980: =pod
                   1981: 
1.970     raeburn  1982: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1983: 
                   1984: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1985: allow a user to select options from a ref to a hash containing:
                   1986: option_name => displayed text. An optional $onchange can include
                   1987: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   1988: 
1.88      www      1989: See lonrights.pm for an example invocation and use.
                   1990: 
                   1991: =cut
                   1992: 
                   1993: #-------------------------------------------
                   1994: sub select_form {
1.970     raeburn  1995:     my ($def,$name,$hashref,$onchange) = @_;
                   1996:     return unless (ref($hashref) eq 'HASH');
                   1997:     if ($onchange) {
                   1998:         $onchange = ' onchange="'.$onchange.'"';
                   1999:     }
                   2000:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2001:     my @keys;
1.970     raeburn  2002:     if (exists($hashref->{'select_form_order'})) {
                   2003: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2004:     } else {
1.970     raeburn  2005: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2006:     }
1.356     albertel 2007:     foreach my $key (@keys) {
                   2008:         $selectform.=
                   2009: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2010:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2011:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2012:     }
                   2013:     $selectform.="</select>";
                   2014:     return $selectform;
                   2015: }
                   2016: 
1.475     www      2017: # For display filters
                   2018: 
                   2019: sub display_filter {
1.1074    raeburn  2020:     my ($context) = @_;
1.475     www      2021:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2022:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2023:     my $phraseinput = 'hidden';
                   2024:     my $includeinput = 'hidden';
                   2025:     my ($checked,$includetypestext);
                   2026:     if ($env{'form.displayfilter'} eq 'containing') {
                   2027:         $phraseinput = 'text'; 
                   2028:         if ($context eq 'parmslog') {
                   2029:             $includeinput = 'checkbox';
                   2030:             if ($env{'form.includetypes'}) {
                   2031:                 $checked = ' checked="checked"';
                   2032:             }
                   2033:             $includetypestext = &mt('Include parameter types');
                   2034:         }
                   2035:     } else {
                   2036:         $includetypestext = '&nbsp;';
                   2037:     }
                   2038:     my ($additional,$secondid,$thirdid);
                   2039:     if ($context eq 'parmslog') {
                   2040:         $additional = 
                   2041:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2042:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2043:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2044:             '</label>';
                   2045:         $secondid = 'includetypes';
                   2046:         $thirdid = 'includetypestext';
                   2047:     }
                   2048:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2049:                                                     '$secondid','$thirdid')";
                   2050:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2051: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2052: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2053: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2054:            &mt('Filter: [_1]',
1.477     www      2055: 	   &select_form($env{'form.displayfilter'},
                   2056: 			'displayfilter',
1.970     raeburn  2057: 			{'currentfolder' => 'Current folder/page',
1.477     www      2058: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2059: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2060: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2061:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2062:                          '" />'.$additional;
                   2063: }
                   2064: 
                   2065: sub display_filter_js {
                   2066:     my $includetext = &mt('Include parameter types');
                   2067:     return <<"ENDJS";
                   2068:   
                   2069: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2070:     var firstType = 'hidden';
                   2071:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2072:         firstType = 'text';
                   2073:     }
                   2074:     firstObject = document.getElementById(firstid);
                   2075:     if (typeof(firstObject) == 'object') {
                   2076:         if (firstObject.type != firstType) {
                   2077:             changeInputType(firstObject,firstType);
                   2078:         }
                   2079:     }
                   2080:     if (context == 'parmslog') {
                   2081:         var secondType = 'hidden';
                   2082:         if (firstType == 'text') {
                   2083:             secondType = 'checkbox';
                   2084:         }
                   2085:         secondObject = document.getElementById(secondid);  
                   2086:         if (typeof(secondObject) == 'object') {
                   2087:             if (secondObject.type != secondType) {
                   2088:                 changeInputType(secondObject,secondType);
                   2089:             }
                   2090:         }
                   2091:         var textItem = document.getElementById(thirdid);
                   2092:         var currtext = textItem.innerHTML;
                   2093:         var newtext;
                   2094:         if (firstType == 'text') {
                   2095:             newtext = '$includetext';
                   2096:         } else {
                   2097:             newtext = '&nbsp;';
                   2098:         }
                   2099:         if (currtext != newtext) {
                   2100:             textItem.innerHTML = newtext;
                   2101:         }
                   2102:     }
                   2103:     return;
                   2104: }
                   2105: 
                   2106: function changeInputType(oldObject,newType) {
                   2107:     var newObject = document.createElement('input');
                   2108:     newObject.type = newType;
                   2109:     if (oldObject.size) {
                   2110:         newObject.size = oldObject.size;
                   2111:     }
                   2112:     if (oldObject.value) {
                   2113:         newObject.value = oldObject.value;
                   2114:     }
                   2115:     if (oldObject.name) {
                   2116:         newObject.name = oldObject.name;
                   2117:     }
                   2118:     if (oldObject.id) {
                   2119:         newObject.id = oldObject.id;
                   2120:     }
                   2121:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2122:     return;
                   2123: }
                   2124: 
                   2125: ENDJS
1.475     www      2126: }
                   2127: 
1.167     www      2128: sub gradeleveldescription {
                   2129:     my $gradelevel=shift;
                   2130:     my %gradelevels=(0 => 'Not specified',
                   2131: 		     1 => 'Grade 1',
                   2132: 		     2 => 'Grade 2',
                   2133: 		     3 => 'Grade 3',
                   2134: 		     4 => 'Grade 4',
                   2135: 		     5 => 'Grade 5',
                   2136: 		     6 => 'Grade 6',
                   2137: 		     7 => 'Grade 7',
                   2138: 		     8 => 'Grade 8',
                   2139: 		     9 => 'Grade 9',
                   2140: 		     10 => 'Grade 10',
                   2141: 		     11 => 'Grade 11',
                   2142: 		     12 => 'Grade 12',
                   2143: 		     13 => 'Grade 13',
                   2144: 		     14 => '100 Level',
                   2145: 		     15 => '200 Level',
                   2146: 		     16 => '300 Level',
                   2147: 		     17 => '400 Level',
                   2148: 		     18 => 'Graduate Level');
                   2149:     return &mt($gradelevels{$gradelevel});
                   2150: }
                   2151: 
1.163     www      2152: sub select_level_form {
                   2153:     my ($deflevel,$name)=@_;
                   2154:     unless ($deflevel) { $deflevel=0; }
1.167     www      2155:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2156:     for (my $i=0; $i<=18; $i++) {
                   2157:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2158:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2159:                 ">".&gradeleveldescription($i)."</option>\n";
                   2160:     }
                   2161:     $selectform.="</select>";
                   2162:     return $selectform;
1.163     www      2163: }
1.167     www      2164: 
1.35      matthew  2165: #-------------------------------------------
                   2166: 
1.45      matthew  2167: =pod
                   2168: 
1.910     raeburn  2169: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
1.35      matthew  2170: 
                   2171: Returns a string containing a <select name='$name' size='1'> form to 
                   2172: allow a user to select the domain to preform an operation in.  
                   2173: See loncreateuser.pm for an example invocation and use.
                   2174: 
1.90      www      2175: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2176: selected");
                   2177: 
1.743     raeburn  2178: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2179: 
1.910     raeburn  2180: 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.
                   2181: 
                   2182: The optional $incdoms is a reference to an array of domains which will be the only available options. 
1.563     raeburn  2183: 
1.35      matthew  2184: =cut
                   2185: 
                   2186: #-------------------------------------------
1.34      matthew  2187: sub select_dom_form {
1.910     raeburn  2188:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
1.872     raeburn  2189:     if ($onchange) {
1.874     raeburn  2190:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2191:     }
1.910     raeburn  2192:     my @domains;
                   2193:     if (ref($incdoms) eq 'ARRAY') {
                   2194:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2195:     } else {
                   2196:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2197:     }
1.90      www      2198:     if ($includeempty) { @domains=('',@domains); }
1.743     raeburn  2199:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2200:     foreach my $dom (@domains) {
                   2201:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2202:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2203:         if ($showdomdesc) {
                   2204:             if ($dom ne '') {
                   2205:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2206:                 if ($domdesc ne '') {
                   2207:                     $selectdomain .= ' ('.$domdesc.')';
                   2208:                 }
                   2209:             } 
                   2210:         }
                   2211:         $selectdomain .= "</option>\n";
1.34      matthew  2212:     }
                   2213:     $selectdomain.="</select>";
                   2214:     return $selectdomain;
                   2215: }
                   2216: 
1.35      matthew  2217: #-------------------------------------------
                   2218: 
1.45      matthew  2219: =pod
                   2220: 
1.648     raeburn  2221: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2222: 
1.586     raeburn  2223: input: 4 arguments (two required, two optional) - 
                   2224:     $domain - domain of new user
                   2225:     $name - name of form element
                   2226:     $default - Value of 'default' causes a default item to be first 
                   2227:                             option, and selected by default. 
                   2228:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2229:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2230: output: returns 2 items: 
1.586     raeburn  2231: (a) form element which contains either:
                   2232:    (i) <select name="$name">
                   2233:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2234:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2235:        </select>
                   2236:        form item if there are multiple library servers in $domain, or
                   2237:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2238:        if there is only one library server in $domain.
                   2239: 
                   2240: (b) number of library servers found.
                   2241: 
                   2242: See loncreateuser.pm for example of use.
1.35      matthew  2243: 
                   2244: =cut
                   2245: 
                   2246: #-------------------------------------------
1.586     raeburn  2247: sub home_server_form_item {
                   2248:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2249:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2250:     my $result;
                   2251:     my $numlib = keys(%servers);
                   2252:     if ($numlib > 1) {
                   2253:         $result .= '<select name="'.$name.'" />'."\n";
                   2254:         if ($default) {
1.804     bisitz   2255:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2256:                        '</option>'."\n";
                   2257:         }
                   2258:         foreach my $hostid (sort(keys(%servers))) {
                   2259:             $result.= '<option value="'.$hostid.'">'.
                   2260: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2261:         }
                   2262:         $result .= '</select>'."\n";
                   2263:     } elsif ($numlib == 1) {
                   2264:         my $hostid;
                   2265:         foreach my $item (keys(%servers)) {
                   2266:             $hostid = $item;
                   2267:         }
                   2268:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2269:                    $hostid.'" />';
                   2270:                    if (!$hide) {
                   2271:                        $result .= $hostid.' '.$servers{$hostid};
                   2272:                    }
                   2273:                    $result .= "\n";
                   2274:     } elsif ($default) {
                   2275:         $result .= '<input type="hidden" name="'.$name.
                   2276:                    '" value="default" />';
                   2277:                    if (!$hide) {
                   2278:                        $result .= &mt('default');
                   2279:                    }
                   2280:                    $result .= "\n";
1.33      matthew  2281:     }
1.586     raeburn  2282:     return ($result,$numlib);
1.33      matthew  2283: }
1.112     bowersj2 2284: 
                   2285: =pod
                   2286: 
1.534     albertel 2287: =back 
                   2288: 
1.112     bowersj2 2289: =cut
1.87      matthew  2290: 
                   2291: ###############################################################
1.112     bowersj2 2292: ##                  Decoding User Agent                      ##
1.87      matthew  2293: ###############################################################
                   2294: 
                   2295: =pod
                   2296: 
1.112     bowersj2 2297: =head1 Decoding the User Agent
                   2298: 
                   2299: =over 4
                   2300: 
                   2301: =item * &decode_user_agent()
1.87      matthew  2302: 
                   2303: Inputs: $r
                   2304: 
                   2305: Outputs:
                   2306: 
                   2307: =over 4
                   2308: 
1.112     bowersj2 2309: =item * $httpbrowser
1.87      matthew  2310: 
1.112     bowersj2 2311: =item * $clientbrowser
1.87      matthew  2312: 
1.112     bowersj2 2313: =item * $clientversion
1.87      matthew  2314: 
1.112     bowersj2 2315: =item * $clientmathml
1.87      matthew  2316: 
1.112     bowersj2 2317: =item * $clientunicode
1.87      matthew  2318: 
1.112     bowersj2 2319: =item * $clientos
1.87      matthew  2320: 
                   2321: =back
                   2322: 
1.157     matthew  2323: =back 
                   2324: 
1.87      matthew  2325: =cut
                   2326: 
                   2327: ###############################################################
                   2328: ###############################################################
                   2329: sub decode_user_agent {
1.247     albertel 2330:     my ($r)=@_;
1.87      matthew  2331:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2332:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2333:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2334:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2335:     my $clientbrowser='unknown';
                   2336:     my $clientversion='0';
                   2337:     my $clientmathml='';
                   2338:     my $clientunicode='0';
                   2339:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2340:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2341: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2342: 	    $clientbrowser=$bname;
                   2343:             $httpbrowser=~/$vreg/i;
                   2344: 	    $clientversion=$1;
                   2345:             $clientmathml=($clientversion>=$minv);
                   2346:             $clientunicode=($clientversion>=$univ);
                   2347: 	}
                   2348:     }
                   2349:     my $clientos='unknown';
                   2350:     if (($httpbrowser=~/linux/i) ||
                   2351:         ($httpbrowser=~/unix/i) ||
                   2352:         ($httpbrowser=~/ux/i) ||
                   2353:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2354:     if (($httpbrowser=~/vax/i) ||
                   2355:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2356:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2357:     if (($httpbrowser=~/mac/i) ||
                   2358:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2359:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2360:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   2361:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   2362:             $clientunicode,$clientos,);
                   2363: }
                   2364: 
1.32      matthew  2365: ###############################################################
                   2366: ##    Authentication changing form generation subroutines    ##
                   2367: ###############################################################
                   2368: ##
                   2369: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2370: ## hash, and have reasonable default values.
                   2371: ##
                   2372: ##    formname = the name given in the <form> tag.
1.35      matthew  2373: #-------------------------------------------
                   2374: 
1.45      matthew  2375: =pod
                   2376: 
1.112     bowersj2 2377: =head1 Authentication Routines
                   2378: 
                   2379: =over 4
                   2380: 
1.648     raeburn  2381: =item * &authform_xxxxxx()
1.35      matthew  2382: 
                   2383: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2384: handle some of the conveniences required for authentication forms.  
                   2385: This is not an optimal method, but it works.  
                   2386: 
                   2387: =over 4
                   2388: 
1.112     bowersj2 2389: =item * authform_header
1.35      matthew  2390: 
1.112     bowersj2 2391: =item * authform_authorwarning
1.35      matthew  2392: 
1.112     bowersj2 2393: =item * authform_nochange
1.35      matthew  2394: 
1.112     bowersj2 2395: =item * authform_kerberos
1.35      matthew  2396: 
1.112     bowersj2 2397: =item * authform_internal
1.35      matthew  2398: 
1.112     bowersj2 2399: =item * authform_filesystem
1.35      matthew  2400: 
                   2401: =back
                   2402: 
1.648     raeburn  2403: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2404: 
1.35      matthew  2405: =cut
                   2406: 
                   2407: #-------------------------------------------
1.32      matthew  2408: sub authform_header{  
                   2409:     my %in = (
                   2410:         formname => 'cu',
1.80      albertel 2411:         kerb_def_dom => '',
1.32      matthew  2412:         @_,
                   2413:     );
                   2414:     $in{'formname'} = 'document.' . $in{'formname'};
                   2415:     my $result='';
1.80      albertel 2416: 
                   2417: #---------------------------------------------- Code for upper case translation
                   2418:     my $Javascript_toUpperCase;
                   2419:     unless ($in{kerb_def_dom}) {
                   2420:         $Javascript_toUpperCase =<<"END";
                   2421:         switch (choice) {
                   2422:            case 'krb': currentform.elements[choicearg].value =
                   2423:                currentform.elements[choicearg].value.toUpperCase();
                   2424:                break;
                   2425:            default:
                   2426:         }
                   2427: END
                   2428:     } else {
                   2429:         $Javascript_toUpperCase = "";
                   2430:     }
                   2431: 
1.165     raeburn  2432:     my $radioval = "'nochange'";
1.591     raeburn  2433:     if (defined($in{'curr_authtype'})) {
                   2434:         if ($in{'curr_authtype'} ne '') {
                   2435:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2436:         }
1.174     matthew  2437:     }
1.165     raeburn  2438:     my $argfield = 'null';
1.591     raeburn  2439:     if (defined($in{'mode'})) {
1.165     raeburn  2440:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2441:             if (defined($in{'curr_autharg'})) {
                   2442:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2443:                     $argfield = "'$in{'curr_autharg'}'";
                   2444:                 }
                   2445:             }
                   2446:         }
                   2447:     }
                   2448: 
1.32      matthew  2449:     $result.=<<"END";
                   2450: var current = new Object();
1.165     raeburn  2451: current.radiovalue = $radioval;
                   2452: current.argfield = $argfield;
1.32      matthew  2453: 
                   2454: function changed_radio(choice,currentform) {
                   2455:     var choicearg = choice + 'arg';
                   2456:     // If a radio button in changed, we need to change the argfield
                   2457:     if (current.radiovalue != choice) {
                   2458:         current.radiovalue = choice;
                   2459:         if (current.argfield != null) {
                   2460:             currentform.elements[current.argfield].value = '';
                   2461:         }
                   2462:         if (choice == 'nochange') {
                   2463:             current.argfield = null;
                   2464:         } else {
                   2465:             current.argfield = choicearg;
                   2466:             switch(choice) {
                   2467:                 case 'krb': 
                   2468:                     currentform.elements[current.argfield].value = 
                   2469:                         "$in{'kerb_def_dom'}";
                   2470:                 break;
                   2471:               default:
                   2472:                 break;
                   2473:             }
                   2474:         }
                   2475:     }
                   2476:     return;
                   2477: }
1.22      www      2478: 
1.32      matthew  2479: function changed_text(choice,currentform) {
                   2480:     var choicearg = choice + 'arg';
                   2481:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2482:         $Javascript_toUpperCase
1.32      matthew  2483:         // clear old field
                   2484:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2485:             currentform.elements[current.argfield].value = '';
                   2486:         }
                   2487:         current.argfield = choicearg;
                   2488:     }
                   2489:     set_auth_radio_buttons(choice,currentform);
                   2490:     return;
1.20      www      2491: }
1.32      matthew  2492: 
                   2493: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2494:     var numauthchoices = currentform.login.length;
                   2495:     if (typeof numauthchoices  == "undefined") {
                   2496:         return;
                   2497:     } 
1.32      matthew  2498:     var i=0;
1.986     raeburn  2499:     while (i < numauthchoices) {
1.32      matthew  2500:         if (currentform.login[i].value == newvalue) { break; }
                   2501:         i++;
                   2502:     }
1.986     raeburn  2503:     if (i == numauthchoices) {
1.32      matthew  2504:         return;
                   2505:     }
                   2506:     current.radiovalue = newvalue;
                   2507:     currentform.login[i].checked = true;
                   2508:     return;
                   2509: }
                   2510: END
                   2511:     return $result;
                   2512: }
                   2513: 
1.1106    raeburn  2514: sub authform_authorwarning {
1.32      matthew  2515:     my $result='';
1.144     matthew  2516:     $result='<i>'.
                   2517:         &mt('As a general rule, only authors or co-authors should be '.
                   2518:             'filesystem authenticated '.
                   2519:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2520:     return $result;
                   2521: }
                   2522: 
1.1106    raeburn  2523: sub authform_nochange {
1.32      matthew  2524:     my %in = (
                   2525:               formname => 'document.cu',
                   2526:               kerb_def_dom => 'MSU.EDU',
                   2527:               @_,
                   2528:           );
1.1106    raeburn  2529:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2530:     my $result;
1.1104    raeburn  2531:     if (!$authnum) {
1.1105    raeburn  2532:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2533:     } else {
                   2534:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2535:                   '<input type="radio" name="login" value="nochange" '.
                   2536:                   'checked="checked" onclick="'.
1.281     albertel 2537:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2538: 	    '</label>';
1.586     raeburn  2539:     }
1.32      matthew  2540:     return $result;
                   2541: }
                   2542: 
1.591     raeburn  2543: sub authform_kerberos {
1.32      matthew  2544:     my %in = (
                   2545:               formname => 'document.cu',
                   2546:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2547:               kerb_def_auth => 'krb4',
1.32      matthew  2548:               @_,
                   2549:               );
1.586     raeburn  2550:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2551:         $autharg,$jscall);
1.1106    raeburn  2552:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2553:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2554:        $check5 = ' checked="checked"';
1.80      albertel 2555:     } else {
1.772     bisitz   2556:        $check4 = ' checked="checked"';
1.80      albertel 2557:     }
1.165     raeburn  2558:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2559:     if (defined($in{'curr_authtype'})) {
                   2560:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2561:             $krbcheck = ' checked="checked"';
1.623     raeburn  2562:             if (defined($in{'mode'})) {
                   2563:                 if ($in{'mode'} eq 'modifyuser') {
                   2564:                     $krbcheck = '';
                   2565:                 }
                   2566:             }
1.591     raeburn  2567:             if (defined($in{'curr_kerb_ver'})) {
                   2568:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2569:                     $check5 = ' checked="checked"';
1.591     raeburn  2570:                     $check4 = '';
                   2571:                 } else {
1.772     bisitz   2572:                     $check4 = ' checked="checked"';
1.591     raeburn  2573:                     $check5 = '';
                   2574:                 }
1.586     raeburn  2575:             }
1.591     raeburn  2576:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2577:                 $krbarg = $in{'curr_autharg'};
                   2578:             }
1.586     raeburn  2579:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2580:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2581:                     $result = 
                   2582:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2583:         $in{'curr_autharg'},$krbver);
                   2584:                 } else {
                   2585:                     $result =
                   2586:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2587:                 }
                   2588:                 return $result; 
                   2589:             }
                   2590:         }
                   2591:     } else {
                   2592:         if ($authnum == 1) {
1.784     bisitz   2593:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2594:         }
                   2595:     }
1.586     raeburn  2596:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2597:         return;
1.587     raeburn  2598:     } elsif ($authtype eq '') {
1.591     raeburn  2599:         if (defined($in{'mode'})) {
1.587     raeburn  2600:             if ($in{'mode'} eq 'modifycourse') {
                   2601:                 if ($authnum == 1) {
1.1104    raeburn  2602:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2603:                 }
                   2604:             }
                   2605:         }
1.586     raeburn  2606:     }
                   2607:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2608:     if ($authtype eq '') {
                   2609:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2610:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2611:                     $krbcheck.' />';
                   2612:     }
                   2613:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2614:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2615:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2616:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2617:          $in{'curr_authtype'} eq 'krb4')) {
                   2618:         $result .= &mt
1.144     matthew  2619:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2620:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2621:          '<label>'.$authtype,
1.281     albertel 2622:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2623:              'value="'.$krbarg.'" '.
1.144     matthew  2624:              'onchange="'.$jscall.'" />',
1.281     albertel 2625:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2626:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2627: 	 '</label>');
1.586     raeburn  2628:     } elsif ($can_assign{'krb4'}) {
                   2629:         $result .= &mt
                   2630:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2631:          '[_3] Version 4 [_4]',
                   2632:          '<label>'.$authtype,
                   2633:          '</label><input type="text" size="10" name="krbarg" '.
                   2634:              'value="'.$krbarg.'" '.
                   2635:              'onchange="'.$jscall.'" />',
                   2636:          '<label><input type="hidden" name="krbver" value="4" />',
                   2637:          '</label>');
                   2638:     } elsif ($can_assign{'krb5'}) {
                   2639:         $result .= &mt
                   2640:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2641:          '[_3] Version 5 [_4]',
                   2642:          '<label>'.$authtype,
                   2643:          '</label><input type="text" size="10" name="krbarg" '.
                   2644:              'value="'.$krbarg.'" '.
                   2645:              'onchange="'.$jscall.'" />',
                   2646:          '<label><input type="hidden" name="krbver" value="5" />',
                   2647:          '</label>');
                   2648:     }
1.32      matthew  2649:     return $result;
                   2650: }
                   2651: 
1.1106    raeburn  2652: sub authform_internal {
1.586     raeburn  2653:     my %in = (
1.32      matthew  2654:                 formname => 'document.cu',
                   2655:                 kerb_def_dom => 'MSU.EDU',
                   2656:                 @_,
                   2657:                 );
1.586     raeburn  2658:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2659:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2660:     if (defined($in{'curr_authtype'})) {
                   2661:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2662:             if ($can_assign{'int'}) {
1.772     bisitz   2663:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2664:                 if (defined($in{'mode'})) {
                   2665:                     if ($in{'mode'} eq 'modifyuser') {
                   2666:                         $intcheck = '';
                   2667:                     }
                   2668:                 }
1.591     raeburn  2669:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2670:                     $intarg = $in{'curr_autharg'};
                   2671:                 }
                   2672:             } else {
                   2673:                 $result = &mt('Currently internally authenticated.');
                   2674:                 return $result;
1.165     raeburn  2675:             }
                   2676:         }
1.586     raeburn  2677:     } else {
                   2678:         if ($authnum == 1) {
1.784     bisitz   2679:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2680:         }
                   2681:     }
                   2682:     if (!$can_assign{'int'}) {
                   2683:         return;
1.587     raeburn  2684:     } elsif ($authtype eq '') {
1.591     raeburn  2685:         if (defined($in{'mode'})) {
1.587     raeburn  2686:             if ($in{'mode'} eq 'modifycourse') {
                   2687:                 if ($authnum == 1) {
1.1104    raeburn  2688:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2689:                 }
                   2690:             }
                   2691:         }
1.165     raeburn  2692:     }
1.586     raeburn  2693:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2694:     if ($authtype eq '') {
                   2695:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2696:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2697:     }
1.605     bisitz   2698:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2699:                $intarg.'" onchange="'.$jscall.'" />';
                   2700:     $result = &mt
1.144     matthew  2701:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2702:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2703:     $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  2704:     return $result;
                   2705: }
                   2706: 
1.1104    raeburn  2707: sub authform_local {
1.32      matthew  2708:     my %in = (
                   2709:               formname => 'document.cu',
                   2710:               kerb_def_dom => 'MSU.EDU',
                   2711:               @_,
                   2712:               );
1.586     raeburn  2713:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2714:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2715:     if (defined($in{'curr_authtype'})) {
                   2716:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2717:             if ($can_assign{'loc'}) {
1.772     bisitz   2718:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2719:                 if (defined($in{'mode'})) {
                   2720:                     if ($in{'mode'} eq 'modifyuser') {
                   2721:                         $loccheck = '';
                   2722:                     }
                   2723:                 }
1.591     raeburn  2724:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2725:                     $locarg = $in{'curr_autharg'};
                   2726:                 }
                   2727:             } else {
                   2728:                 $result = &mt('Currently using local (institutional) authentication.');
                   2729:                 return $result;
1.165     raeburn  2730:             }
                   2731:         }
1.586     raeburn  2732:     } else {
                   2733:         if ($authnum == 1) {
1.784     bisitz   2734:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2735:         }
                   2736:     }
                   2737:     if (!$can_assign{'loc'}) {
                   2738:         return;
1.587     raeburn  2739:     } elsif ($authtype eq '') {
1.591     raeburn  2740:         if (defined($in{'mode'})) {
1.587     raeburn  2741:             if ($in{'mode'} eq 'modifycourse') {
                   2742:                 if ($authnum == 1) {
1.1104    raeburn  2743:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2744:                 }
                   2745:             }
                   2746:         }
1.165     raeburn  2747:     }
1.586     raeburn  2748:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2749:     if ($authtype eq '') {
                   2750:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2751:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2752:                     $jscall.'" />';
                   2753:     }
                   2754:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2755:                $locarg.'" onchange="'.$jscall.'" />';
                   2756:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2757:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2758:     return $result;
                   2759: }
                   2760: 
1.1106    raeburn  2761: sub authform_filesystem {
1.32      matthew  2762:     my %in = (
                   2763:               formname => 'document.cu',
                   2764:               kerb_def_dom => 'MSU.EDU',
                   2765:               @_,
                   2766:               );
1.586     raeburn  2767:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2768:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2769:     if (defined($in{'curr_authtype'})) {
                   2770:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2771:             if ($can_assign{'fsys'}) {
1.772     bisitz   2772:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2773:                 if (defined($in{'mode'})) {
                   2774:                     if ($in{'mode'} eq 'modifyuser') {
                   2775:                         $fsyscheck = '';
                   2776:                     }
                   2777:                 }
1.586     raeburn  2778:             } else {
                   2779:                 $result = &mt('Currently Filesystem Authenticated.');
                   2780:                 return $result;
                   2781:             }           
                   2782:         }
                   2783:     } else {
                   2784:         if ($authnum == 1) {
1.784     bisitz   2785:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2786:         }
                   2787:     }
                   2788:     if (!$can_assign{'fsys'}) {
                   2789:         return;
1.587     raeburn  2790:     } elsif ($authtype eq '') {
1.591     raeburn  2791:         if (defined($in{'mode'})) {
1.587     raeburn  2792:             if ($in{'mode'} eq 'modifycourse') {
                   2793:                 if ($authnum == 1) {
1.1104    raeburn  2794:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2795:                 }
                   2796:             }
                   2797:         }
1.586     raeburn  2798:     }
                   2799:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2800:     if ($authtype eq '') {
                   2801:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2802:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2803:                     $jscall.'" />';
                   2804:     }
                   2805:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2806:                ' onchange="'.$jscall.'" />';
                   2807:     $result = &mt
1.144     matthew  2808:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2809:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2810:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2811:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2812:                   'onchange="'.$jscall.'" />');
1.32      matthew  2813:     return $result;
                   2814: }
                   2815: 
1.586     raeburn  2816: sub get_assignable_auth {
                   2817:     my ($dom) = @_;
                   2818:     if ($dom eq '') {
                   2819:         $dom = $env{'request.role.domain'};
                   2820:     }
                   2821:     my %can_assign = (
                   2822:                           krb4 => 1,
                   2823:                           krb5 => 1,
                   2824:                           int  => 1,
                   2825:                           loc  => 1,
                   2826:                      );
                   2827:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2828:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2829:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2830:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2831:             my $context;
                   2832:             if ($env{'request.role'} =~ /^au/) {
                   2833:                 $context = 'author';
                   2834:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2835:                 $context = 'domain';
                   2836:             } elsif ($env{'request.course.id'}) {
                   2837:                 $context = 'course';
                   2838:             }
                   2839:             if ($context) {
                   2840:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2841:                    %can_assign = %{$authhash->{$context}}; 
                   2842:                 }
                   2843:             }
                   2844:         }
                   2845:     }
                   2846:     my $authnum = 0;
                   2847:     foreach my $key (keys(%can_assign)) {
                   2848:         if ($can_assign{$key}) {
                   2849:             $authnum ++;
                   2850:         }
                   2851:     }
                   2852:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2853:         $authnum --;
                   2854:     }
                   2855:     return ($authnum,%can_assign);
                   2856: }
                   2857: 
1.80      albertel 2858: ###############################################################
                   2859: ##    Get Kerberos Defaults for Domain                 ##
                   2860: ###############################################################
                   2861: ##
                   2862: ## Returns default kerberos version and an associated argument
                   2863: ## as listed in file domain.tab. If not listed, provides
                   2864: ## appropriate default domain and kerberos version.
                   2865: ##
                   2866: #-------------------------------------------
                   2867: 
                   2868: =pod
                   2869: 
1.648     raeburn  2870: =item * &get_kerberos_defaults()
1.80      albertel 2871: 
                   2872: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2873: version and domain. If not found, it defaults to version 4 and the 
                   2874: domain of the server.
1.80      albertel 2875: 
1.648     raeburn  2876: =over 4
                   2877: 
1.80      albertel 2878: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2879: 
1.648     raeburn  2880: =back
                   2881: 
                   2882: =back
                   2883: 
1.80      albertel 2884: =cut
                   2885: 
                   2886: #-------------------------------------------
                   2887: sub get_kerberos_defaults {
                   2888:     my $domain=shift;
1.641     raeburn  2889:     my ($krbdef,$krbdefdom);
                   2890:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2891:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2892:         $krbdef = $domdefaults{'auth_def'};
                   2893:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2894:     } else {
1.80      albertel 2895:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2896:         my $krbdefdom=$1;
                   2897:         $krbdefdom=~tr/a-z/A-Z/;
                   2898:         $krbdef = "krb4";
                   2899:     }
                   2900:     return ($krbdef,$krbdefdom);
                   2901: }
1.112     bowersj2 2902: 
1.32      matthew  2903: 
1.46      matthew  2904: ###############################################################
                   2905: ##                Thesaurus Functions                        ##
                   2906: ###############################################################
1.20      www      2907: 
1.46      matthew  2908: =pod
1.20      www      2909: 
1.112     bowersj2 2910: =head1 Thesaurus Functions
                   2911: 
                   2912: =over 4
                   2913: 
1.648     raeburn  2914: =item * &initialize_keywords()
1.46      matthew  2915: 
                   2916: Initializes the package variable %Keywords if it is empty.  Uses the
                   2917: package variable $thesaurus_db_file.
                   2918: 
                   2919: =cut
                   2920: 
                   2921: ###################################################
                   2922: 
                   2923: sub initialize_keywords {
                   2924:     return 1 if (scalar keys(%Keywords));
                   2925:     # If we are here, %Keywords is empty, so fill it up
                   2926:     #   Make sure the file we need exists...
                   2927:     if (! -e $thesaurus_db_file) {
                   2928:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2929:                                  " failed because it does not exist");
                   2930:         return 0;
                   2931:     }
                   2932:     #   Set up the hash as a database
                   2933:     my %thesaurus_db;
                   2934:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2935:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2936:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2937:                                  $thesaurus_db_file);
                   2938:         return 0;
                   2939:     } 
                   2940:     #  Get the average number of appearances of a word.
                   2941:     my $avecount = $thesaurus_db{'average.count'};
                   2942:     #  Put keywords (those that appear > average) into %Keywords
                   2943:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2944:         my ($count,undef) = split /:/,$data;
                   2945:         $Keywords{$word}++ if ($count > $avecount);
                   2946:     }
                   2947:     untie %thesaurus_db;
                   2948:     # Remove special values from %Keywords.
1.356     albertel 2949:     foreach my $value ('total.count','average.count') {
                   2950:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2951:   }
1.46      matthew  2952:     return 1;
                   2953: }
                   2954: 
                   2955: ###################################################
                   2956: 
                   2957: =pod
                   2958: 
1.648     raeburn  2959: =item * &keyword($word)
1.46      matthew  2960: 
                   2961: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2962: than the average number of times in the thesaurus database.  Calls 
                   2963: &initialize_keywords
                   2964: 
                   2965: =cut
                   2966: 
                   2967: ###################################################
1.20      www      2968: 
                   2969: sub keyword {
1.46      matthew  2970:     return if (!&initialize_keywords());
                   2971:     my $word=lc(shift());
                   2972:     $word=~s/\W//g;
                   2973:     return exists($Keywords{$word});
1.20      www      2974: }
1.46      matthew  2975: 
                   2976: ###############################################################
                   2977: 
                   2978: =pod 
1.20      www      2979: 
1.648     raeburn  2980: =item * &get_related_words()
1.46      matthew  2981: 
1.160     matthew  2982: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2983: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2984: will be returned.  The order of the words returned is determined by the
                   2985: database which holds them.
                   2986: 
                   2987: Uses global $thesaurus_db_file.
                   2988: 
1.1057    foxr     2989: 
1.46      matthew  2990: =cut
                   2991: 
                   2992: ###############################################################
                   2993: sub get_related_words {
                   2994:     my $keyword = shift;
                   2995:     my %thesaurus_db;
                   2996:     if (! -e $thesaurus_db_file) {
                   2997:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2998:                                  "failed because the file does not exist");
                   2999:         return ();
                   3000:     }
                   3001:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3002:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3003:         return ();
                   3004:     } 
                   3005:     my @Words=();
1.429     www      3006:     my $count=0;
1.46      matthew  3007:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3008: 	# The first element is the number of times
                   3009: 	# the word appears.  We do not need it now.
1.429     www      3010: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3011: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3012: 	my $threshold=$mostfrequentcount/10;
                   3013:         foreach my $possibleword (@RelatedWords) {
                   3014:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3015:             if ($wordcount>$threshold) {
                   3016: 		push(@Words,$word);
                   3017:                 $count++;
                   3018:                 if ($count>10) { last; }
                   3019: 	    }
1.20      www      3020:         }
                   3021:     }
1.46      matthew  3022:     untie %thesaurus_db;
                   3023:     return @Words;
1.14      harris41 3024: }
1.1090    foxr     3025: ###############################################################
                   3026: #
                   3027: #  Spell checking
                   3028: #
                   3029: 
                   3030: =pod
                   3031: 
                   3032: =head1 Spell checking
                   3033: 
                   3034: =over 4
                   3035: 
                   3036: =item * &check_spelling($wordlist $language)
                   3037: 
                   3038: Takes a string containing words and feeds it to an external
                   3039: spellcheck program via a pipeline. Returns a string containing
                   3040: them mis-spelled words.
                   3041: 
                   3042: Parameters:
                   3043: 
                   3044: =over 4
                   3045: 
                   3046: =item - $wordlist
                   3047: 
                   3048: String that will be fed into the spellcheck program.
                   3049: 
                   3050: =item - $language
                   3051: 
                   3052: Language string that specifies the language for which the spell
                   3053: check will be performed.
                   3054: 
                   3055: =back
                   3056: 
                   3057: =back
                   3058: 
                   3059: Note: This sub assumes that aspell is installed.
                   3060: 
                   3061: 
                   3062: =cut
                   3063: 
1.46      matthew  3064: 
1.112     bowersj2 3065: =pod
                   3066: 
                   3067: =back
                   3068: 
                   3069: =cut
1.61      www      3070: 
1.1090    foxr     3071: sub check_spelling {
                   3072:     my ($wordlist, $language) = @_;
1.1091    foxr     3073:     my @misspellings;
                   3074:     
                   3075:     # Generate the speller and set the langauge.
                   3076:     # if explicitly selected:
1.1090    foxr     3077: 
1.1091    foxr     3078:     my $speller = Text::Aspell->new;
1.1090    foxr     3079:     if ($language) {
1.1091    foxr     3080: 	$speller->set_option('lang', $language);
1.1090    foxr     3081:     }
                   3082: 
1.1091    foxr     3083:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3084: 
1.1091    foxr     3085:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3086: 
1.1091    foxr     3087:     foreach my $word (@words) {
                   3088: 	if(! $speller->check($word)) {
                   3089: 	    push(@misspellings, $word);
1.1090    foxr     3090: 	}
                   3091:     }
1.1091    foxr     3092:     return join(' ', @misspellings);
                   3093:     
1.1090    foxr     3094: }
                   3095: 
1.61      www      3096: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3097: =pod
                   3098: 
1.112     bowersj2 3099: =head1 User Name Functions
                   3100: 
                   3101: =over 4
                   3102: 
1.648     raeburn  3103: =item * &plainname($uname,$udom,$first)
1.81      albertel 3104: 
1.112     bowersj2 3105: Takes a users logon name and returns it as a string in
1.226     albertel 3106: "first middle last generation" form 
                   3107: if $first is set to 'lastname' then it returns it as
                   3108: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3109: 
                   3110: =cut
1.61      www      3111: 
1.295     www      3112: 
1.81      albertel 3113: ###############################################################
1.61      www      3114: sub plainname {
1.226     albertel 3115:     my ($uname,$udom,$first)=@_;
1.537     albertel 3116:     return if (!defined($uname) || !defined($udom));
1.295     www      3117:     my %names=&getnames($uname,$udom);
1.226     albertel 3118:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3119: 					  $names{'middlename'},
                   3120: 					  $names{'lastname'},
                   3121: 					  $names{'generation'},$first);
                   3122:     $name=~s/^\s+//;
1.62      www      3123:     $name=~s/\s+$//;
                   3124:     $name=~s/\s+/ /g;
1.353     albertel 3125:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3126:     return $name;
1.61      www      3127: }
1.66      www      3128: 
                   3129: # -------------------------------------------------------------------- Nickname
1.81      albertel 3130: =pod
                   3131: 
1.648     raeburn  3132: =item * &nickname($uname,$udom)
1.81      albertel 3133: 
                   3134: Gets a users name and returns it as a string as
                   3135: 
                   3136: "&quot;nickname&quot;"
1.66      www      3137: 
1.81      albertel 3138: if the user has a nickname or
                   3139: 
                   3140: "first middle last generation"
                   3141: 
                   3142: if the user does not
                   3143: 
                   3144: =cut
1.66      www      3145: 
                   3146: sub nickname {
                   3147:     my ($uname,$udom)=@_;
1.537     albertel 3148:     return if (!defined($uname) || !defined($udom));
1.295     www      3149:     my %names=&getnames($uname,$udom);
1.68      albertel 3150:     my $name=$names{'nickname'};
1.66      www      3151:     if ($name) {
                   3152:        $name='&quot;'.$name.'&quot;'; 
                   3153:     } else {
                   3154:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3155: 	     $names{'lastname'}.' '.$names{'generation'};
                   3156:        $name=~s/\s+$//;
                   3157:        $name=~s/\s+/ /g;
                   3158:     }
                   3159:     return $name;
                   3160: }
                   3161: 
1.295     www      3162: sub getnames {
                   3163:     my ($uname,$udom)=@_;
1.537     albertel 3164:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3165:     if ($udom eq 'public' && $uname eq 'public') {
                   3166: 	return ('lastname' => &mt('Public'));
                   3167:     }
1.295     www      3168:     my $id=$uname.':'.$udom;
                   3169:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3170:     if ($cached) {
                   3171: 	return %{$names};
                   3172:     } else {
                   3173: 	my %loadnames=&Apache::lonnet::get('environment',
                   3174:                     ['firstname','middlename','lastname','generation','nickname'],
                   3175: 					 $udom,$uname);
                   3176: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3177: 	return %loadnames;
                   3178:     }
                   3179: }
1.61      www      3180: 
1.542     raeburn  3181: # -------------------------------------------------------------------- getemails
1.648     raeburn  3182: 
1.542     raeburn  3183: =pod
                   3184: 
1.648     raeburn  3185: =item * &getemails($uname,$udom)
1.542     raeburn  3186: 
                   3187: Gets a user's email information and returns it as a hash with keys:
                   3188: notification, critnotification, permanentemail
                   3189: 
                   3190: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3191: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3192:  
1.648     raeburn  3193: 
1.542     raeburn  3194: =cut
                   3195: 
1.648     raeburn  3196: 
1.466     albertel 3197: sub getemails {
                   3198:     my ($uname,$udom)=@_;
                   3199:     if ($udom eq 'public' && $uname eq 'public') {
                   3200: 	return;
                   3201:     }
1.467     www      3202:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3203:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3204:     my $id=$uname.':'.$udom;
                   3205:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3206:     if ($cached) {
                   3207: 	return %{$names};
                   3208:     } else {
                   3209: 	my %loadnames=&Apache::lonnet::get('environment',
                   3210:                     			   ['notification','critnotification',
                   3211: 					    'permanentemail'],
                   3212: 					   $udom,$uname);
                   3213: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3214: 	return %loadnames;
                   3215:     }
                   3216: }
                   3217: 
1.551     albertel 3218: sub flush_email_cache {
                   3219:     my ($uname,$udom)=@_;
                   3220:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3221:     if (!$uname) { $uname=$env{'user.name'};   }
                   3222:     return if ($udom eq 'public' && $uname eq 'public');
                   3223:     my $id=$uname.':'.$udom;
                   3224:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3225: }
                   3226: 
1.728     raeburn  3227: # -------------------------------------------------------------------- getlangs
                   3228: 
                   3229: =pod
                   3230: 
                   3231: =item * &getlangs($uname,$udom)
                   3232: 
                   3233: Gets a user's language preference and returns it as a hash with key:
                   3234: language.
                   3235: 
                   3236: =cut
                   3237: 
                   3238: 
                   3239: sub getlangs {
                   3240:     my ($uname,$udom) = @_;
                   3241:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3242:     if (!$uname) { $uname=$env{'user.name'};   }
                   3243:     my $id=$uname.':'.$udom;
                   3244:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3245:     if ($cached) {
                   3246:         return %{$langs};
                   3247:     } else {
                   3248:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3249:                                            $udom,$uname);
                   3250:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3251:         return %loadlangs;
                   3252:     }
                   3253: }
                   3254: 
                   3255: sub flush_langs_cache {
                   3256:     my ($uname,$udom)=@_;
                   3257:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3258:     if (!$uname) { $uname=$env{'user.name'};   }
                   3259:     return if ($udom eq 'public' && $uname eq 'public');
                   3260:     my $id=$uname.':'.$udom;
                   3261:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3262: }
                   3263: 
1.61      www      3264: # ------------------------------------------------------------------ Screenname
1.81      albertel 3265: 
                   3266: =pod
                   3267: 
1.648     raeburn  3268: =item * &screenname($uname,$udom)
1.81      albertel 3269: 
                   3270: Gets a users screenname and returns it as a string
                   3271: 
                   3272: =cut
1.61      www      3273: 
                   3274: sub screenname {
                   3275:     my ($uname,$udom)=@_;
1.258     albertel 3276:     if ($uname eq $env{'user.name'} &&
                   3277: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3278:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3279:     return $names{'screenname'};
1.62      www      3280: }
                   3281: 
1.212     albertel 3282: 
1.802     bisitz   3283: # ------------------------------------------------------------- Confirm Wrapper
                   3284: =pod
                   3285: 
                   3286: =item confirmwrapper
                   3287: 
                   3288: Wrap messages about completion of operation in box
                   3289: 
                   3290: =cut
                   3291: 
                   3292: sub confirmwrapper {
                   3293:     my ($message)=@_;
                   3294:     if ($message) {
                   3295:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3296:                .$message."\n"
                   3297:                .'</div>'."\n";
                   3298:     } else {
                   3299:         return $message;
                   3300:     }
                   3301: }
                   3302: 
1.62      www      3303: # ------------------------------------------------------------- Message Wrapper
                   3304: 
                   3305: sub messagewrapper {
1.369     www      3306:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3307:     return 
1.441     albertel 3308:         '<a href="/adm/email?compose=individual&amp;'.
                   3309:         'recname='.$username.'&amp;recdom='.$domain.
                   3310: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3311:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3312: }
1.802     bisitz   3313: 
1.74      www      3314: # --------------------------------------------------------------- Notes Wrapper
                   3315: 
                   3316: sub noteswrapper {
                   3317:     my ($link,$un,$do)=@_;
                   3318:     return 
1.896     amueller 3319: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3320: }
1.802     bisitz   3321: 
1.62      www      3322: # ------------------------------------------------------------- Aboutme Wrapper
                   3323: 
                   3324: sub aboutmewrapper {
1.1070    raeburn  3325:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3326:     if (!defined($username)  && !defined($domain)) {
                   3327:         return;
                   3328:     }
1.1096    raeburn  3329:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3330: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3331: }
                   3332: 
                   3333: # ------------------------------------------------------------ Syllabus Wrapper
                   3334: 
                   3335: sub syllabuswrapper {
1.707     bisitz   3336:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3337:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3338: }
1.14      harris41 3339: 
1.802     bisitz   3340: # -----------------------------------------------------------------------------
                   3341: 
1.208     matthew  3342: sub track_student_link {
1.887     raeburn  3343:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3344:     my $link ="/adm/trackstudent?";
1.208     matthew  3345:     my $title = 'View recent activity';
                   3346:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3347:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3348:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3349:         $title .= ' of this student';
1.268     albertel 3350:     } 
1.208     matthew  3351:     if (defined($target) && $target !~ /^\s*$/) {
                   3352:         $target = qq{target="$target"};
                   3353:     } else {
                   3354:         $target = '';
                   3355:     }
1.268     albertel 3356:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3357:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3358:     $title = &mt($title);
                   3359:     $linktext = &mt($linktext);
1.448     albertel 3360:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3361: 	&help_open_topic('View_recent_activity');
1.208     matthew  3362: }
                   3363: 
1.781     raeburn  3364: sub slot_reservations_link {
                   3365:     my ($linktext,$sname,$sdom,$target) = @_;
                   3366:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3367:     my $title = 'View slot reservation history';
                   3368:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3369:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3370:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3371:         $title .= ' of this student';
                   3372:     }
                   3373:     if (defined($target) && $target !~ /^\s*$/) {
                   3374:         $target = qq{target="$target"};
                   3375:     } else {
                   3376:         $target = '';
                   3377:     }
                   3378:     $title = &mt($title);
                   3379:     $linktext = &mt($linktext);
                   3380:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3381: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3382: 
                   3383: }
                   3384: 
1.508     www      3385: # ===================================================== Display a student photo
                   3386: 
                   3387: 
1.509     albertel 3388: sub student_image_tag {
1.508     www      3389:     my ($domain,$user)=@_;
                   3390:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3391:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3392: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3393:     } else {
                   3394: 	return '';
                   3395:     }
                   3396: }
                   3397: 
1.112     bowersj2 3398: =pod
                   3399: 
                   3400: =back
                   3401: 
                   3402: =head1 Access .tab File Data
                   3403: 
                   3404: =over 4
                   3405: 
1.648     raeburn  3406: =item * &languageids() 
1.112     bowersj2 3407: 
                   3408: returns list of all language ids
                   3409: 
                   3410: =cut
                   3411: 
1.14      harris41 3412: sub languageids {
1.16      harris41 3413:     return sort(keys(%language));
1.14      harris41 3414: }
                   3415: 
1.112     bowersj2 3416: =pod
                   3417: 
1.648     raeburn  3418: =item * &languagedescription() 
1.112     bowersj2 3419: 
                   3420: returns description of a specified language id
                   3421: 
                   3422: =cut
                   3423: 
1.14      harris41 3424: sub languagedescription {
1.125     www      3425:     my $code=shift;
                   3426:     return  ($supported_language{$code}?'* ':'').
                   3427:             $language{$code}.
1.126     www      3428: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3429: }
                   3430: 
1.1048    foxr     3431: =pod
                   3432: 
                   3433: =item * &plainlanguagedescription
                   3434: 
                   3435: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3436: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3437: 
                   3438: =cut
                   3439: 
1.145     www      3440: sub plainlanguagedescription {
                   3441:     my $code=shift;
                   3442:     return $language{$code};
                   3443: }
                   3444: 
1.1048    foxr     3445: =pod
                   3446: 
                   3447: =item * &supportedlanguagecode
                   3448: 
                   3449: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3450: code.
                   3451: 
                   3452: =cut
                   3453: 
1.145     www      3454: sub supportedlanguagecode {
                   3455:     my $code=shift;
                   3456:     return $supported_language{$code};
1.97      www      3457: }
                   3458: 
1.112     bowersj2 3459: =pod
                   3460: 
1.1048    foxr     3461: =item * &latexlanguage()
                   3462: 
                   3463: Given a language key code returns the correspondnig language to use
                   3464: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3465: is no supported hyphenation for the language code.
                   3466: 
                   3467: =cut
                   3468: 
                   3469: sub latexlanguage {
                   3470:     my $code = shift;
                   3471:     return $latex_language{$code};
                   3472: }
                   3473: 
                   3474: =pod
                   3475: 
                   3476: =item * &latexhyphenation()
                   3477: 
                   3478: Same as above but what's supplied is the language as it might be stored
                   3479: in the metadata.
                   3480: 
                   3481: =cut
                   3482: 
                   3483: sub latexhyphenation {
                   3484:     my $key = shift;
                   3485:     return $latex_language_bykey{$key};
                   3486: }
                   3487: 
                   3488: =pod
                   3489: 
1.648     raeburn  3490: =item * &copyrightids() 
1.112     bowersj2 3491: 
                   3492: returns list of all copyrights
                   3493: 
                   3494: =cut
                   3495: 
                   3496: sub copyrightids {
                   3497:     return sort(keys(%cprtag));
                   3498: }
                   3499: 
                   3500: =pod
                   3501: 
1.648     raeburn  3502: =item * &copyrightdescription() 
1.112     bowersj2 3503: 
                   3504: returns description of a specified copyright id
                   3505: 
                   3506: =cut
                   3507: 
                   3508: sub copyrightdescription {
1.166     www      3509:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3510: }
1.197     matthew  3511: 
                   3512: =pod
                   3513: 
1.648     raeburn  3514: =item * &source_copyrightids() 
1.192     taceyjo1 3515: 
                   3516: returns list of all source copyrights
                   3517: 
                   3518: =cut
                   3519: 
                   3520: sub source_copyrightids {
                   3521:     return sort(keys(%scprtag));
                   3522: }
                   3523: 
                   3524: =pod
                   3525: 
1.648     raeburn  3526: =item * &source_copyrightdescription() 
1.192     taceyjo1 3527: 
                   3528: returns description of a specified source copyright id
                   3529: 
                   3530: =cut
                   3531: 
                   3532: sub source_copyrightdescription {
                   3533:     return &mt($scprtag{shift(@_)});
                   3534: }
1.112     bowersj2 3535: 
                   3536: =pod
                   3537: 
1.648     raeburn  3538: =item * &filecategories() 
1.112     bowersj2 3539: 
                   3540: returns list of all file categories
                   3541: 
                   3542: =cut
                   3543: 
                   3544: sub filecategories {
                   3545:     return sort(keys(%category_extensions));
                   3546: }
                   3547: 
                   3548: =pod
                   3549: 
1.648     raeburn  3550: =item * &filecategorytypes() 
1.112     bowersj2 3551: 
                   3552: returns list of file types belonging to a given file
                   3553: category
                   3554: 
                   3555: =cut
                   3556: 
                   3557: sub filecategorytypes {
1.356     albertel 3558:     my ($cat) = @_;
                   3559:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3560: }
                   3561: 
                   3562: =pod
                   3563: 
1.648     raeburn  3564: =item * &fileembstyle() 
1.112     bowersj2 3565: 
                   3566: returns embedding style for a specified file type
                   3567: 
                   3568: =cut
                   3569: 
                   3570: sub fileembstyle {
                   3571:     return $fe{lc(shift(@_))};
1.169     www      3572: }
                   3573: 
1.351     www      3574: sub filemimetype {
                   3575:     return $fm{lc(shift(@_))};
                   3576: }
                   3577: 
1.169     www      3578: 
                   3579: sub filecategoryselect {
                   3580:     my ($name,$value)=@_;
1.189     matthew  3581:     return &select_form($value,$name,
1.970     raeburn  3582:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3583: }
                   3584: 
                   3585: =pod
                   3586: 
1.648     raeburn  3587: =item * &filedescription() 
1.112     bowersj2 3588: 
                   3589: returns description for a specified file type
                   3590: 
                   3591: =cut
                   3592: 
                   3593: sub filedescription {
1.188     matthew  3594:     my $file_description = $fd{lc(shift())};
                   3595:     $file_description =~ s:([\[\]]):~$1:g;
                   3596:     return &mt($file_description);
1.112     bowersj2 3597: }
                   3598: 
                   3599: =pod
                   3600: 
1.648     raeburn  3601: =item * &filedescriptionex() 
1.112     bowersj2 3602: 
                   3603: returns description for a specified file type with
                   3604: extra formatting
                   3605: 
                   3606: =cut
                   3607: 
                   3608: sub filedescriptionex {
                   3609:     my $ex=shift;
1.188     matthew  3610:     my $file_description = $fd{lc($ex)};
                   3611:     $file_description =~ s:([\[\]]):~$1:g;
                   3612:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3613: }
                   3614: 
                   3615: # End of .tab access
                   3616: =pod
                   3617: 
                   3618: =back
                   3619: 
                   3620: =cut
                   3621: 
                   3622: # ------------------------------------------------------------------ File Types
                   3623: sub fileextensions {
                   3624:     return sort(keys(%fe));
                   3625: }
                   3626: 
1.97      www      3627: # ----------------------------------------------------------- Display Languages
                   3628: # returns a hash with all desired display languages
                   3629: #
                   3630: 
                   3631: sub display_languages {
                   3632:     my %languages=();
1.695     raeburn  3633:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3634: 	$languages{$lang}=1;
1.97      www      3635:     }
                   3636:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3637:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3638: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3639: 	    $languages{$lang}=1;
1.97      www      3640:         }
                   3641:     }
                   3642:     return %languages;
1.14      harris41 3643: }
                   3644: 
1.582     albertel 3645: sub languages {
                   3646:     my ($possible_langs) = @_;
1.695     raeburn  3647:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3648:     if (!ref($possible_langs)) {
                   3649: 	if( wantarray ) {
                   3650: 	    return @preferred_langs;
                   3651: 	} else {
                   3652: 	    return $preferred_langs[0];
                   3653: 	}
                   3654:     }
                   3655:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3656:     my @preferred_possibilities;
                   3657:     foreach my $preferred_lang (@preferred_langs) {
                   3658: 	if (exists($possibilities{$preferred_lang})) {
                   3659: 	    push(@preferred_possibilities, $preferred_lang);
                   3660: 	}
                   3661:     }
                   3662:     if( wantarray ) {
                   3663: 	return @preferred_possibilities;
                   3664:     }
                   3665:     return $preferred_possibilities[0];
                   3666: }
                   3667: 
1.742     raeburn  3668: sub user_lang {
                   3669:     my ($touname,$toudom,$fromcid) = @_;
                   3670:     my @userlangs;
                   3671:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3672:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3673:                     $env{'course.'.$fromcid.'.languages'}));
                   3674:     } else {
                   3675:         my %langhash = &getlangs($touname,$toudom);
                   3676:         if ($langhash{'languages'} ne '') {
                   3677:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3678:         } else {
                   3679:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3680:             if ($domdefs{'lang_def'} ne '') {
                   3681:                 @userlangs = ($domdefs{'lang_def'});
                   3682:             }
                   3683:         }
                   3684:     }
                   3685:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3686:     my $user_lh = Apache::localize->get_handle(@languages);
                   3687:     return $user_lh;
                   3688: }
                   3689: 
                   3690: 
1.112     bowersj2 3691: ###############################################################
                   3692: ##               Student Answer Attempts                     ##
                   3693: ###############################################################
                   3694: 
                   3695: =pod
                   3696: 
                   3697: =head1 Alternate Problem Views
                   3698: 
                   3699: =over 4
                   3700: 
1.648     raeburn  3701: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3702:     $getattempt, $regexp, $gradesub)
                   3703: 
                   3704: Return string with previous attempt on problem. Arguments:
                   3705: 
                   3706: =over 4
                   3707: 
                   3708: =item * $symb: Problem, including path
                   3709: 
                   3710: =item * $username: username of the desired student
                   3711: 
                   3712: =item * $domain: domain of the desired student
1.14      harris41 3713: 
1.112     bowersj2 3714: =item * $course: Course ID
1.14      harris41 3715: 
1.112     bowersj2 3716: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3717:     something
1.14      harris41 3718: 
1.112     bowersj2 3719: =item * $regexp: if string matches this regexp, the string will be
                   3720:     sent to $gradesub
1.14      harris41 3721: 
1.112     bowersj2 3722: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3723: 
1.112     bowersj2 3724: =back
1.14      harris41 3725: 
1.112     bowersj2 3726: The output string is a table containing all desired attempts, if any.
1.16      harris41 3727: 
1.112     bowersj2 3728: =cut
1.1       albertel 3729: 
                   3730: sub get_previous_attempt {
1.43      ng       3731:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3732:   my $prevattempts='';
1.43      ng       3733:   no strict 'refs';
1.1       albertel 3734:   if ($symb) {
1.3       albertel 3735:     my (%returnhash)=
                   3736:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3737:     if ($returnhash{'version'}) {
                   3738:       my %lasthash=();
                   3739:       my $version;
                   3740:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3741:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3742: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3743:         }
1.1       albertel 3744:       }
1.596     albertel 3745:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3746:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3747:       my (%typeparts,%lasthidden);
1.945     raeburn  3748:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3749:       foreach my $key (sort(keys(%lasthash))) {
                   3750: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3751: 	if ($#parts > 0) {
1.31      albertel 3752: 	  my $data=$parts[-1];
1.989     raeburn  3753:           next if ($data eq 'foilorder');
1.31      albertel 3754: 	  pop(@parts);
1.1010    www      3755:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3756:           if ($data eq 'type') {
                   3757:               unless ($showsurv) {
                   3758:                   my $id = join(',',@parts);
                   3759:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3760:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3761:                       $lasthidden{$ign.'.'.$id} = 1;
                   3762:                   }
1.945     raeburn  3763:               }
1.1010    www      3764:           } 
1.31      albertel 3765: 	} else {
1.41      ng       3766: 	  if ($#parts == 0) {
                   3767: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3768: 	  } else {
                   3769: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3770: 	  }
1.31      albertel 3771: 	}
1.16      harris41 3772:       }
1.596     albertel 3773:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3774:       if ($getattempt eq '') {
                   3775: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3776:             my @hidden;
                   3777:             if (%typeparts) {
                   3778:                 foreach my $id (keys(%typeparts)) {
                   3779:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3780:                         push(@hidden,$id);
                   3781:                     }
                   3782:                 }
                   3783:             }
                   3784:             $prevattempts.=&start_data_table_row().
                   3785:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3786:             if (@hidden) {
                   3787:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3788:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3789:                     my $hide;
                   3790:                     foreach my $id (@hidden) {
                   3791:                         if ($key =~ /^\Q$id\E/) {
                   3792:                             $hide = 1;
                   3793:                             last;
                   3794:                         }
                   3795:                     }
                   3796:                     if ($hide) {
                   3797:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3798:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3799:                             my $value = &format_previous_attempt_value($key,
                   3800:                                              $returnhash{$version.':'.$key});
                   3801:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3802:                         } else {
                   3803:                             $prevattempts.='<td>&nbsp;</td>';
                   3804:                         }
                   3805:                     } else {
                   3806:                         if ($key =~ /\./) {
                   3807:                             my $value = &format_previous_attempt_value($key,
                   3808:                                               $returnhash{$version.':'.$key});
                   3809:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3810:                         } else {
                   3811:                             $prevattempts.='<td>&nbsp;</td>';
                   3812:                         }
                   3813:                     }
                   3814:                 }
                   3815:             } else {
                   3816: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3817:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3818: 		    my $value = &format_previous_attempt_value($key,
                   3819: 			            $returnhash{$version.':'.$key});
                   3820: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3821: 	        }
                   3822:             }
                   3823: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3824: 	 }
1.1       albertel 3825:       }
1.945     raeburn  3826:       my @currhidden = keys(%lasthidden);
1.596     albertel 3827:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3828:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3829:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3830:           if (%typeparts) {
                   3831:               my $hidden;
                   3832:               foreach my $id (@currhidden) {
                   3833:                   if ($key =~ /^\Q$id\E/) {
                   3834:                       $hidden = 1;
                   3835:                       last;
                   3836:                   }
                   3837:               }
                   3838:               if ($hidden) {
                   3839:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3840:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3841:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3842:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3843:                           $value = &$gradesub($value);
                   3844:                       }
                   3845:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3846:                   } else {
                   3847:                       $prevattempts.='<td>&nbsp;</td>';
                   3848:                   }
                   3849:               } else {
                   3850:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3851:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3852:                       $value = &$gradesub($value);
                   3853:                   }
                   3854:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3855:               }
                   3856:           } else {
                   3857: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3858: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3859:                   $value = &$gradesub($value);
                   3860:               }
                   3861: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3862:           }
1.16      harris41 3863:       }
1.596     albertel 3864:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3865:     } else {
1.596     albertel 3866:       $prevattempts=
                   3867: 	  &start_data_table().&start_data_table_row().
                   3868: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3869: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3870:     }
                   3871:   } else {
1.596     albertel 3872:     $prevattempts=
                   3873: 	  &start_data_table().&start_data_table_row().
                   3874: 	  '<td>'.&mt('No data.').'</td>'.
                   3875: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3876:   }
1.10      albertel 3877: }
                   3878: 
1.581     albertel 3879: sub format_previous_attempt_value {
                   3880:     my ($key,$value) = @_;
1.1011    www      3881:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3882: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3883:     } elsif (ref($value) eq 'ARRAY') {
                   3884: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3885:     } elsif ($key =~ /answerstring$/) {
                   3886:         my %answers = &Apache::lonnet::str2hash($value);
                   3887:         my @anskeys = sort(keys(%answers));
                   3888:         if (@anskeys == 1) {
                   3889:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3890:             if ($answer =~ m{\0}) {
                   3891:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3892:             }
                   3893:             my $tag_internal_answer_name = 'INTERNAL';
                   3894:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3895:                 $value = $answer; 
                   3896:             } else {
                   3897:                 $value = $anskeys[0].'='.$answer;
                   3898:             }
                   3899:         } else {
                   3900:             foreach my $ans (@anskeys) {
                   3901:                 my $answer = $answers{$ans};
1.1001    raeburn  3902:                 if ($answer =~ m{\0}) {
                   3903:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3904:                 }
                   3905:                 $value .=  $ans.'='.$answer.'<br />';;
                   3906:             } 
                   3907:         }
1.581     albertel 3908:     } else {
                   3909: 	$value = &unescape($value);
                   3910:     }
                   3911:     return $value;
                   3912: }
                   3913: 
                   3914: 
1.107     albertel 3915: sub relative_to_absolute {
                   3916:     my ($url,$output)=@_;
                   3917:     my $parser=HTML::TokeParser->new(\$output);
                   3918:     my $token;
                   3919:     my $thisdir=$url;
                   3920:     my @rlinks=();
                   3921:     while ($token=$parser->get_token) {
                   3922: 	if ($token->[0] eq 'S') {
                   3923: 	    if ($token->[1] eq 'a') {
                   3924: 		if ($token->[2]->{'href'}) {
                   3925: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3926: 		}
                   3927: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3928: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3929: 	    } elsif ($token->[1] eq 'base') {
                   3930: 		$thisdir=$token->[2]->{'href'};
                   3931: 	    }
                   3932: 	}
                   3933:     }
                   3934:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3935:     foreach my $link (@rlinks) {
1.726     raeburn  3936: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3937: 		($link=~/^\//) ||
                   3938: 		($link=~/^javascript:/i) ||
                   3939: 		($link=~/^mailto:/i) ||
                   3940: 		($link=~/^\#/)) {
                   3941: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3942: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3943: 	}
                   3944:     }
                   3945: # -------------------------------------------------- Deal with Applet codebases
                   3946:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3947:     return $output;
                   3948: }
                   3949: 
1.112     bowersj2 3950: =pod
                   3951: 
1.648     raeburn  3952: =item * &get_student_view()
1.112     bowersj2 3953: 
                   3954: show a snapshot of what student was looking at
                   3955: 
                   3956: =cut
                   3957: 
1.10      albertel 3958: sub get_student_view {
1.186     albertel 3959:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3960:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3961:   my (%form);
1.10      albertel 3962:   my @elements=('symb','courseid','domain','username');
                   3963:   foreach my $element (@elements) {
1.186     albertel 3964:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3965:   }
1.186     albertel 3966:   if (defined($moreenv)) {
                   3967:       %form=(%form,%{$moreenv});
                   3968:   }
1.236     albertel 3969:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3970:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3971:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3972:   $userview=~s/\<body[^\>]*\>//gi;
                   3973:   $userview=~s/\<\/body\>//gi;
                   3974:   $userview=~s/\<html\>//gi;
                   3975:   $userview=~s/\<\/html\>//gi;
                   3976:   $userview=~s/\<head\>//gi;
                   3977:   $userview=~s/\<\/head\>//gi;
                   3978:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3979:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3980:   if (wantarray) {
                   3981:      return ($userview,$response);
                   3982:   } else {
                   3983:      return $userview;
                   3984:   }
                   3985: }
                   3986: 
                   3987: sub get_student_view_with_retries {
                   3988:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3989: 
                   3990:     my $ok = 0;                 # True if we got a good response.
                   3991:     my $content;
                   3992:     my $response;
                   3993: 
                   3994:     # Try to get the student_view done. within the retries count:
                   3995:     
                   3996:     do {
                   3997:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3998:          $ok      = $response->is_success;
                   3999:          if (!$ok) {
                   4000:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4001:          }
                   4002:          $retries--;
                   4003:     } while (!$ok && ($retries > 0));
                   4004:     
                   4005:     if (!$ok) {
                   4006:        $content = '';          # On error return an empty content.
                   4007:     }
1.651     www      4008:     if (wantarray) {
                   4009:        return ($content, $response);
                   4010:     } else {
                   4011:        return $content;
                   4012:     }
1.11      albertel 4013: }
                   4014: 
1.112     bowersj2 4015: =pod
                   4016: 
1.648     raeburn  4017: =item * &get_student_answers() 
1.112     bowersj2 4018: 
                   4019: show a snapshot of how student was answering problem
                   4020: 
                   4021: =cut
                   4022: 
1.11      albertel 4023: sub get_student_answers {
1.100     sakharuk 4024:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4025:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4026:   my (%moreenv);
1.11      albertel 4027:   my @elements=('symb','courseid','domain','username');
                   4028:   foreach my $element (@elements) {
1.186     albertel 4029:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4030:   }
1.186     albertel 4031:   $moreenv{'grade_target'}='answer';
                   4032:   %moreenv=(%form,%moreenv);
1.497     raeburn  4033:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4034:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4035:   return $userview;
1.1       albertel 4036: }
1.116     albertel 4037: 
                   4038: =pod
                   4039: 
                   4040: =item * &submlink()
                   4041: 
1.242     albertel 4042: Inputs: $text $uname $udom $symb $target
1.116     albertel 4043: 
                   4044: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4045: 
                   4046: =cut
                   4047: 
                   4048: ###############################################
                   4049: sub submlink {
1.242     albertel 4050:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4051:     if (!($uname && $udom)) {
                   4052: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4053: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4054: 	if (!$symb) { $symb=$cursymb; }
                   4055:     }
1.254     matthew  4056:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4057:     $symb=&escape($symb);
1.960     bisitz   4058:     if ($target) { $target=" target=\"$target\""; }
                   4059:     return
                   4060:         '<a href="/adm/grades?command=submission'.
                   4061:         '&amp;symb='.$symb.
                   4062:         '&amp;student='.$uname.
                   4063:         '&amp;userdom='.$udom.'"'.
                   4064:         $target.'>'.$text.'</a>';
1.242     albertel 4065: }
                   4066: ##############################################
                   4067: 
                   4068: =pod
                   4069: 
                   4070: =item * &pgrdlink()
                   4071: 
                   4072: Inputs: $text $uname $udom $symb $target
                   4073: 
                   4074: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4075: 
                   4076: =cut
                   4077: 
                   4078: ###############################################
                   4079: sub pgrdlink {
                   4080:     my $link=&submlink(@_);
                   4081:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4082:     return $link;
                   4083: }
                   4084: ##############################################
                   4085: 
                   4086: =pod
                   4087: 
                   4088: =item * &pprmlink()
                   4089: 
                   4090: Inputs: $text $uname $udom $symb $target
                   4091: 
                   4092: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4093: student and a specific resource
1.242     albertel 4094: 
                   4095: =cut
                   4096: 
                   4097: ###############################################
                   4098: sub pprmlink {
                   4099:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4100:     if (!($uname && $udom)) {
                   4101: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4102: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4103: 	if (!$symb) { $symb=$cursymb; }
                   4104:     }
1.254     matthew  4105:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4106:     $symb=&escape($symb);
1.242     albertel 4107:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4108:     return '<a href="/adm/parmset?command=set&amp;'.
                   4109: 	'symb='.$symb.'&amp;uname='.$uname.
                   4110: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4111: }
                   4112: ##############################################
1.37      matthew  4113: 
1.112     bowersj2 4114: =pod
                   4115: 
                   4116: =back
                   4117: 
                   4118: =cut
                   4119: 
1.37      matthew  4120: ###############################################
1.51      www      4121: 
                   4122: 
                   4123: sub timehash {
1.687     raeburn  4124:     my ($thistime) = @_;
                   4125:     my $timezone = &Apache::lonlocal::gettimezone();
                   4126:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4127:                      ->set_time_zone($timezone);
                   4128:     my $wday = $dt->day_of_week();
                   4129:     if ($wday == 7) { $wday = 0; }
                   4130:     return ( 'second' => $dt->second(),
                   4131:              'minute' => $dt->minute(),
                   4132:              'hour'   => $dt->hour(),
                   4133:              'day'     => $dt->day_of_month(),
                   4134:              'month'   => $dt->month(),
                   4135:              'year'    => $dt->year(),
                   4136:              'weekday' => $wday,
                   4137:              'dayyear' => $dt->day_of_year(),
                   4138:              'dlsav'   => $dt->is_dst() );
1.51      www      4139: }
                   4140: 
1.370     www      4141: sub utc_string {
                   4142:     my ($date)=@_;
1.371     www      4143:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4144: }
                   4145: 
1.51      www      4146: sub maketime {
                   4147:     my %th=@_;
1.687     raeburn  4148:     my ($epoch_time,$timezone,$dt);
                   4149:     $timezone = &Apache::lonlocal::gettimezone();
                   4150:     eval {
                   4151:         $dt = DateTime->new( year   => $th{'year'},
                   4152:                              month  => $th{'month'},
                   4153:                              day    => $th{'day'},
                   4154:                              hour   => $th{'hour'},
                   4155:                              minute => $th{'minute'},
                   4156:                              second => $th{'second'},
                   4157:                              time_zone => $timezone,
                   4158:                          );
                   4159:     };
                   4160:     if (!$@) {
                   4161:         $epoch_time = $dt->epoch;
                   4162:         if ($epoch_time) {
                   4163:             return $epoch_time;
                   4164:         }
                   4165:     }
1.51      www      4166:     return POSIX::mktime(
                   4167:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4168:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4169: }
                   4170: 
                   4171: #########################################
1.51      www      4172: 
                   4173: sub findallcourses {
1.482     raeburn  4174:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4175:     my %roles;
                   4176:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4177:     my %courses;
1.51      www      4178:     my $now=time;
1.482     raeburn  4179:     if (!defined($uname)) {
                   4180:         $uname = $env{'user.name'};
                   4181:     }
                   4182:     if (!defined($udom)) {
                   4183:         $udom = $env{'user.domain'};
                   4184:     }
                   4185:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4186:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4187:         if (!%roles) {
                   4188:             %roles = (
                   4189:                        cc => 1,
1.907     raeburn  4190:                        co => 1,
1.482     raeburn  4191:                        in => 1,
                   4192:                        ep => 1,
                   4193:                        ta => 1,
                   4194:                        cr => 1,
                   4195:                        st => 1,
                   4196:              );
                   4197:         }
                   4198:         foreach my $entry (keys(%roleshash)) {
                   4199:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4200:             if ($trole =~ /^cr/) { 
                   4201:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4202:             } else {
                   4203:                 next if (!exists($roles{$trole}));
                   4204:             }
                   4205:             if ($tend) {
                   4206:                 next if ($tend < $now);
                   4207:             }
                   4208:             if ($tstart) {
                   4209:                 next if ($tstart > $now);
                   4210:             }
1.1058    raeburn  4211:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4212:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4213:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4214:             if ($secpart eq '') {
                   4215:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4216:                 $sec = 'none';
1.1058    raeburn  4217:                 $value .= $cnum.'/';
1.482     raeburn  4218:             } else {
                   4219:                 $cnum = $cnumpart;
                   4220:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4221:                 $value .= $cnum.'/'.$sec;
                   4222:             }
                   4223:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4224:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4225:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4226:                 }
                   4227:             } else {
                   4228:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4229:             }
1.482     raeburn  4230:         }
                   4231:     } else {
                   4232:         foreach my $key (keys(%env)) {
1.483     albertel 4233: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4234:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4235: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4236: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4237: 	        next if (%roles && !exists($roles{$role}));
                   4238: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4239:                 my $active=1;
                   4240:                 if ($starttime) {
                   4241: 		    if ($now<$starttime) { $active=0; }
                   4242:                 }
                   4243:                 if ($endtime) {
                   4244:                     if ($now>$endtime) { $active=0; }
                   4245:                 }
                   4246:                 if ($active) {
1.1058    raeburn  4247:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4248:                     if ($sec eq '') {
                   4249:                         $sec = 'none';
1.1058    raeburn  4250:                     } else {
                   4251:                         $value .= $sec;
                   4252:                     }
                   4253:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4254:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4255:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4256:                         }
                   4257:                     } else {
                   4258:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4259:                     }
1.474     raeburn  4260:                 }
                   4261:             }
1.51      www      4262:         }
                   4263:     }
1.474     raeburn  4264:     return %courses;
1.51      www      4265: }
1.37      matthew  4266: 
1.54      www      4267: ###############################################
1.474     raeburn  4268: 
                   4269: sub blockcheck {
1.1062    raeburn  4270:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4271: 
                   4272:     if (!defined($udom)) {
                   4273:         $udom = $env{'user.domain'};
                   4274:     }
                   4275:     if (!defined($uname)) {
                   4276:         $uname = $env{'user.name'};
                   4277:     }
                   4278: 
                   4279:     # If uname and udom are for a course, check for blocks in the course.
                   4280: 
                   4281:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4282:         my ($startblock,$endblock,$triggerblock) = 
                   4283:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4284:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4285:     }
1.474     raeburn  4286: 
1.502     raeburn  4287:     my $startblock = 0;
                   4288:     my $endblock = 0;
1.1062    raeburn  4289:     my $triggerblock = '';
1.482     raeburn  4290:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4291: 
1.490     raeburn  4292:     # If uname is for a user, and activity is course-specific, i.e.,
                   4293:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4294: 
1.490     raeburn  4295:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4296:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4297:         foreach my $key (keys(%live_courses)) {
                   4298:             if ($key ne $env{'request.course.id'}) {
                   4299:                 delete($live_courses{$key});
                   4300:             }
                   4301:         }
                   4302:     }
                   4303: 
                   4304:     my $otheruser = 0;
                   4305:     my %own_courses;
                   4306:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4307:         # Resource belongs to user other than current user.
                   4308:         $otheruser = 1;
                   4309:         # Gather courses for current user
                   4310:         %own_courses = 
                   4311:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4312:     }
                   4313: 
                   4314:     # Gather active course roles - course coordinator, instructor, 
                   4315:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4316: 
                   4317:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4318:         my ($cdom,$cnum);
                   4319:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4320:             $cdom = $env{'course.'.$course.'.domain'};
                   4321:             $cnum = $env{'course.'.$course.'.num'};
                   4322:         } else {
1.490     raeburn  4323:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4324:         }
                   4325:         my $no_ownblock = 0;
                   4326:         my $no_userblock = 0;
1.533     raeburn  4327:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4328:             # Check if current user has 'evb' priv for this
                   4329:             if (defined($own_courses{$course})) {
                   4330:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4331:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4332:                     if ($sec ne 'none') {
                   4333:                         $checkrole .= '/'.$sec;
                   4334:                     }
                   4335:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4336:                         $no_ownblock = 1;
                   4337:                         last;
                   4338:                     }
                   4339:                 }
                   4340:             }
                   4341:             # if they have 'evb' priv and are currently not playing student
                   4342:             next if (($no_ownblock) &&
                   4343:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4344:         }
1.474     raeburn  4345:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4346:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4347:             if ($sec ne 'none') {
1.482     raeburn  4348:                 $checkrole .= '/'.$sec;
1.474     raeburn  4349:             }
1.490     raeburn  4350:             if ($otheruser) {
                   4351:                 # Resource belongs to user other than current user.
                   4352:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4353:                 my (%allroles,%userroles);
                   4354:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4355:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4356:                         my ($trole,$tdom,$tnum,$tsec);
                   4357:                         if ($entry =~ /^cr/) {
                   4358:                             ($trole,$tdom,$tnum,$tsec) = 
                   4359:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4360:                         } else {
                   4361:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4362:                         }
                   4363:                         my ($spec,$area,$trest);
                   4364:                         $area = '/'.$tdom.'/'.$tnum;
                   4365:                         $trest = $tnum;
                   4366:                         if ($tsec ne '') {
                   4367:                             $area .= '/'.$tsec;
                   4368:                             $trest .= '/'.$tsec;
                   4369:                         }
                   4370:                         $spec = $trole.'.'.$area;
                   4371:                         if ($trole =~ /^cr/) {
                   4372:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4373:                                                               $tdom,$spec,$trest,$area);
                   4374:                         } else {
                   4375:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4376:                                                                 $tdom,$spec,$trest,$area);
                   4377:                         }
                   4378:                     }
                   4379:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4380:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4381:                         if ($1) {
                   4382:                             $no_userblock = 1;
                   4383:                             last;
                   4384:                         }
1.486     raeburn  4385:                     }
                   4386:                 }
1.490     raeburn  4387:             } else {
                   4388:                 # Resource belongs to current user
                   4389:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4390:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4391:                     $no_ownblock = 1;
                   4392:                     last;
                   4393:                 }
1.474     raeburn  4394:             }
                   4395:         }
                   4396:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4397:         next if (($no_ownblock) &&
1.491     albertel 4398:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4399:         next if ($no_userblock);
1.474     raeburn  4400: 
1.866     kalberla 4401:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4402:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4403:         
1.1062    raeburn  4404:         my ($start,$end,$trigger) = 
                   4405:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4406:         if (($start != 0) && 
                   4407:             (($startblock == 0) || ($startblock > $start))) {
                   4408:             $startblock = $start;
1.1062    raeburn  4409:             if ($trigger ne '') {
                   4410:                 $triggerblock = $trigger;
                   4411:             }
1.502     raeburn  4412:         }
                   4413:         if (($end != 0)  &&
                   4414:             (($endblock == 0) || ($endblock < $end))) {
                   4415:             $endblock = $end;
1.1062    raeburn  4416:             if ($trigger ne '') {
                   4417:                 $triggerblock = $trigger;
                   4418:             }
1.502     raeburn  4419:         }
1.490     raeburn  4420:     }
1.1062    raeburn  4421:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4422: }
                   4423: 
                   4424: sub get_blocks {
1.1062    raeburn  4425:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4426:     my $startblock = 0;
                   4427:     my $endblock = 0;
1.1062    raeburn  4428:     my $triggerblock = '';
1.490     raeburn  4429:     my $course = $cdom.'_'.$cnum;
                   4430:     $setters->{$course} = {};
                   4431:     $setters->{$course}{'staff'} = [];
                   4432:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4433:     $setters->{$course}{'triggers'} = [];
                   4434:     my (@blockers,%triggered);
                   4435:     my $now = time;
                   4436:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4437:     if ($activity eq 'docs') {
                   4438:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4439:         foreach my $block (@blockers) {
                   4440:             if ($block =~ /^firstaccess____(.+)$/) {
                   4441:                 my $item = $1;
                   4442:                 my $type = 'map';
                   4443:                 my $timersymb = $item;
                   4444:                 if ($item eq 'course') {
                   4445:                     $type = 'course';
                   4446:                 } elsif ($item =~ /___\d+___/) {
                   4447:                     $type = 'resource';
                   4448:                 } else {
                   4449:                     $timersymb = &Apache::lonnet::symbread($item);
                   4450:                 }
                   4451:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4452:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4453:                 $triggered{$block} = {
                   4454:                                        start => $start,
                   4455:                                        end   => $end,
                   4456:                                        type  => $type,
                   4457:                                      };
                   4458:             }
                   4459:         }
                   4460:     } else {
                   4461:         foreach my $block (keys(%commblocks)) {
                   4462:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4463:                 my ($start,$end) = ($1,$2);
                   4464:                 if ($start <= time && $end >= time) {
                   4465:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4466:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4467:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4468:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4469:                                     push(@blockers,$block);
                   4470:                                 }
                   4471:                             }
                   4472:                         }
                   4473:                     }
                   4474:                 }
                   4475:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4476:                 my $item = $1;
                   4477:                 my $timersymb = $item; 
                   4478:                 my $type = 'map';
                   4479:                 if ($item eq 'course') {
                   4480:                     $type = 'course';
                   4481:                 } elsif ($item =~ /___\d+___/) {
                   4482:                     $type = 'resource';
                   4483:                 } else {
                   4484:                     $timersymb = &Apache::lonnet::symbread($item);
                   4485:                 }
                   4486:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4487:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4488:                 if ($start && $end) {
                   4489:                     if (($start <= time) && ($end >= time)) {
                   4490:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4491:                             push(@blockers,$block);
                   4492:                             $triggered{$block} = {
                   4493:                                                    start => $start,
                   4494:                                                    end   => $end,
                   4495:                                                    type  => $type,
                   4496:                                                  };
                   4497:                         }
                   4498:                     }
1.490     raeburn  4499:                 }
1.1062    raeburn  4500:             }
                   4501:         }
                   4502:     }
                   4503:     foreach my $blocker (@blockers) {
                   4504:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4505:             &parse_block_record($commblocks{$blocker});
                   4506:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4507:         my ($start,$end,$triggertype);
                   4508:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4509:             ($start,$end) = ($1,$2);
                   4510:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4511:             $start = $triggered{$blocker}{'start'};
                   4512:             $end = $triggered{$blocker}{'end'};
                   4513:             $triggertype = $triggered{$blocker}{'type'};
                   4514:         }
                   4515:         if ($start) {
                   4516:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4517:             if ($triggertype) {
                   4518:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4519:             } else {
                   4520:                 push(@{$$setters{$course}{'triggers'}},0);
                   4521:             }
                   4522:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4523:                 $startblock = $start;
                   4524:                 if ($triggertype) {
                   4525:                     $triggerblock = $blocker;
1.474     raeburn  4526:                 }
                   4527:             }
1.1062    raeburn  4528:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4529:                $endblock = $end;
                   4530:                if ($triggertype) {
                   4531:                    $triggerblock = $blocker;
                   4532:                }
                   4533:             }
1.474     raeburn  4534:         }
                   4535:     }
1.1062    raeburn  4536:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4537: }
                   4538: 
                   4539: sub parse_block_record {
                   4540:     my ($record) = @_;
                   4541:     my ($setuname,$setudom,$title,$blocks);
                   4542:     if (ref($record) eq 'HASH') {
                   4543:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4544:         $title = &unescape($record->{'event'});
                   4545:         $blocks = $record->{'blocks'};
                   4546:     } else {
                   4547:         my @data = split(/:/,$record,3);
                   4548:         if (scalar(@data) eq 2) {
                   4549:             $title = $data[1];
                   4550:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4551:         } else {
                   4552:             ($setuname,$setudom,$title) = @data;
                   4553:         }
                   4554:         $blocks = { 'com' => 'on' };
                   4555:     }
                   4556:     return ($setuname,$setudom,$title,$blocks);
                   4557: }
                   4558: 
1.854     kalberla 4559: sub blocking_status {
1.1062    raeburn  4560:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4561:     my %setters;
1.890     droeschl 4562: 
1.1061    raeburn  4563: # check for active blocking
1.1062    raeburn  4564:     my ($startblock,$endblock,$triggerblock) = 
                   4565:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4566:     my $blocked = 0;
                   4567:     if ($startblock && $endblock) {
                   4568:         $blocked = 1;
                   4569:     }
1.890     droeschl 4570: 
1.1061    raeburn  4571: # caller just wants to know whether a block is active
                   4572:     if (!wantarray) { return $blocked; }
                   4573: 
                   4574: # build a link to a popup window containing the details
                   4575:     my $querystring  = "?activity=$activity";
                   4576: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4577:     if ($activity eq 'port') {
                   4578:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4579:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4580:     } elsif ($activity eq 'docs') {
                   4581:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4582:     }
1.1061    raeburn  4583: 
                   4584:     my $output .= <<'END_MYBLOCK';
                   4585: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4586:     var options = "width=" + w + ",height=" + h + ",";
                   4587:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4588:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4589:     var newWin = window.open(url, wdwName, options);
                   4590:     newWin.focus();
                   4591: }
1.890     droeschl 4592: END_MYBLOCK
1.854     kalberla 4593: 
1.1061    raeburn  4594:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4595:   
1.1061    raeburn  4596:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4597:     my $text = &mt('Communication Blocked');
                   4598:     if ($activity eq 'docs') {
                   4599:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4600:     } elsif ($activity eq 'printout') {
                   4601:         $text = &mt('Printing Blocked');
1.1062    raeburn  4602:     }
1.1061    raeburn  4603:     $output .= <<"END_BLOCK";
1.867     kalberla 4604: <div class='LC_comblock'>
1.869     kalberla 4605:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4606:   title='$text'>
                   4607:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4608:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4609:   title='$text'>$text</a>
1.867     kalberla 4610: </div>
                   4611: 
                   4612: END_BLOCK
1.474     raeburn  4613: 
1.1061    raeburn  4614:     return ($blocked, $output);
1.854     kalberla 4615: }
1.490     raeburn  4616: 
1.60      matthew  4617: ###############################################
                   4618: 
1.682     raeburn  4619: sub check_ip_acc {
                   4620:     my ($acc)=@_;
                   4621:     &Apache::lonxml::debug("acc is $acc");
                   4622:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4623:         return 1;
                   4624:     }
                   4625:     my $allowed=0;
                   4626:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4627: 
                   4628:     my $name;
                   4629:     foreach my $pattern (split(',',$acc)) {
                   4630:         $pattern =~ s/^\s*//;
                   4631:         $pattern =~ s/\s*$//;
                   4632:         if ($pattern =~ /\*$/) {
                   4633:             #35.8.*
                   4634:             $pattern=~s/\*//;
                   4635:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4636:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4637:             #35.8.3.[34-56]
                   4638:             my $low=$2;
                   4639:             my $high=$3;
                   4640:             $pattern=$1;
                   4641:             if ($ip =~ /^\Q$pattern\E/) {
                   4642:                 my $last=(split(/\./,$ip))[3];
                   4643:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4644:             }
                   4645:         } elsif ($pattern =~ /^\*/) {
                   4646:             #*.msu.edu
                   4647:             $pattern=~s/\*//;
                   4648:             if (!defined($name)) {
                   4649:                 use Socket;
                   4650:                 my $netaddr=inet_aton($ip);
                   4651:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4652:             }
                   4653:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4654:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4655:             #127.0.0.1
                   4656:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4657:         } else {
                   4658:             #some.name.com
                   4659:             if (!defined($name)) {
                   4660:                 use Socket;
                   4661:                 my $netaddr=inet_aton($ip);
                   4662:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4663:             }
                   4664:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4665:         }
                   4666:         if ($allowed) { last; }
                   4667:     }
                   4668:     return $allowed;
                   4669: }
                   4670: 
                   4671: ###############################################
                   4672: 
1.60      matthew  4673: =pod
                   4674: 
1.112     bowersj2 4675: =head1 Domain Template Functions
                   4676: 
                   4677: =over 4
                   4678: 
                   4679: =item * &determinedomain()
1.60      matthew  4680: 
                   4681: Inputs: $domain (usually will be undef)
                   4682: 
1.63      www      4683: Returns: Determines which domain should be used for designs
1.60      matthew  4684: 
                   4685: =cut
1.54      www      4686: 
1.60      matthew  4687: ###############################################
1.63      www      4688: sub determinedomain {
                   4689:     my $domain=shift;
1.531     albertel 4690:     if (! $domain) {
1.60      matthew  4691:         # Determine domain if we have not been given one
1.893     raeburn  4692:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4693:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4694:         if ($env{'request.role.domain'}) { 
                   4695:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4696:         }
                   4697:     }
1.63      www      4698:     return $domain;
                   4699: }
                   4700: ###############################################
1.517     raeburn  4701: 
1.518     albertel 4702: sub devalidate_domconfig_cache {
                   4703:     my ($udom)=@_;
                   4704:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4705: }
                   4706: 
                   4707: # ---------------------- Get domain configuration for a domain
                   4708: sub get_domainconf {
                   4709:     my ($udom) = @_;
                   4710:     my $cachetime=1800;
                   4711:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4712:     if (defined($cached)) { return %{$result}; }
                   4713: 
                   4714:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4715: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4716:     my (%designhash,%legacy);
1.518     albertel 4717:     if (keys(%domconfig) > 0) {
                   4718:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4719:             if (keys(%{$domconfig{'login'}})) {
                   4720:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4721:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4722:                         if ($key eq 'loginvia') {
                   4723:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4724:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4725:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4726:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4727:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4728:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4729:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4730: 
                   4731:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4732:                                             } else {
1.1013    raeburn  4733:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4734:                                             }
                   4735:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4736:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4737:                                             }
1.946     raeburn  4738:                                         }
                   4739:                                     }
                   4740:                                 }
                   4741:                             }
                   4742:                         } else {
                   4743:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4744:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4745:                                     $domconfig{'login'}{$key}{$img};
                   4746:                             }
1.699     raeburn  4747:                         }
                   4748:                     } else {
                   4749:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4750:                     }
1.632     raeburn  4751:                 }
                   4752:             } else {
                   4753:                 $legacy{'login'} = 1;
1.518     albertel 4754:             }
1.632     raeburn  4755:         } else {
                   4756:             $legacy{'login'} = 1;
1.518     albertel 4757:         }
                   4758:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4759:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4760:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4761:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4762:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4763:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4764:                         }
1.518     albertel 4765:                     }
                   4766:                 }
1.632     raeburn  4767:             } else {
                   4768:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4769:             }
1.632     raeburn  4770:         } else {
                   4771:             $legacy{'rolecolors'} = 1;
1.518     albertel 4772:         }
1.948     raeburn  4773:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4774:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4775:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4776:             }
                   4777:         }
1.632     raeburn  4778:         if (keys(%legacy) > 0) {
                   4779:             my %legacyhash = &get_legacy_domconf($udom);
                   4780:             foreach my $item (keys(%legacyhash)) {
                   4781:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4782:                     if ($legacy{'login'}) { 
                   4783:                         $designhash{$item} = $legacyhash{$item};
                   4784:                     }
                   4785:                 } else {
                   4786:                     if ($legacy{'rolecolors'}) {
                   4787:                         $designhash{$item} = $legacyhash{$item};
                   4788:                     }
1.518     albertel 4789:                 }
                   4790:             }
                   4791:         }
1.632     raeburn  4792:     } else {
                   4793:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4794:     }
                   4795:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4796: 				  $cachetime);
                   4797:     return %designhash;
                   4798: }
                   4799: 
1.632     raeburn  4800: sub get_legacy_domconf {
                   4801:     my ($udom) = @_;
                   4802:     my %legacyhash;
                   4803:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4804:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4805:     if (-e $designfile) {
                   4806:         if ( open (my $fh,"<$designfile") ) {
                   4807:             while (my $line = <$fh>) {
                   4808:                 next if ($line =~ /^\#/);
                   4809:                 chomp($line);
                   4810:                 my ($key,$val)=(split(/\=/,$line));
                   4811:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4812:             }
                   4813:             close($fh);
                   4814:         }
                   4815:     }
1.1026    raeburn  4816:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4817:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4818:     }
                   4819:     return %legacyhash;
                   4820: }
                   4821: 
1.63      www      4822: =pod
                   4823: 
1.112     bowersj2 4824: =item * &domainlogo()
1.63      www      4825: 
                   4826: Inputs: $domain (usually will be undef)
                   4827: 
                   4828: Returns: A link to a domain logo, if the domain logo exists.
                   4829: If the domain logo does not exist, a description of the domain.
                   4830: 
                   4831: =cut
1.112     bowersj2 4832: 
1.63      www      4833: ###############################################
                   4834: sub domainlogo {
1.517     raeburn  4835:     my $domain = &determinedomain(shift);
1.518     albertel 4836:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4837:     # See if there is a logo
                   4838:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4839:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4840:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4841: 	    if ($imgsrc =~ m{^/res/}) {
                   4842: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4843: 		&Apache::lonnet::repcopy($local_name);
                   4844: 	    }
                   4845: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4846:         } 
                   4847:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4848:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4849:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4850:     } else {
1.60      matthew  4851:         return '';
1.59      www      4852:     }
                   4853: }
1.63      www      4854: ##############################################
                   4855: 
                   4856: =pod
                   4857: 
1.112     bowersj2 4858: =item * &designparm()
1.63      www      4859: 
                   4860: Inputs: $which parameter; $domain (usually will be undef)
                   4861: 
                   4862: Returns: value of designparamter $which
                   4863: 
                   4864: =cut
1.112     bowersj2 4865: 
1.397     albertel 4866: 
1.400     albertel 4867: ##############################################
1.397     albertel 4868: sub designparm {
                   4869:     my ($which,$domain)=@_;
                   4870:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4871:         return $env{'environment.color.'.$which};
1.96      www      4872:     }
1.63      www      4873:     $domain=&determinedomain($domain);
1.1016    raeburn  4874:     my %domdesign;
                   4875:     unless ($domain eq 'public') {
                   4876:         %domdesign = &get_domainconf($domain);
                   4877:     }
1.520     raeburn  4878:     my $output;
1.517     raeburn  4879:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4880:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4881:     } else {
1.520     raeburn  4882:         $output = $defaultdesign{$which};
                   4883:     }
                   4884:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4885:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4886:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4887:             if ($output =~ m{^/res/}) {
                   4888:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4889:                 &Apache::lonnet::repcopy($local_name);
                   4890:             }
1.520     raeburn  4891:             $output = &lonhttpdurl($output);
                   4892:         }
1.63      www      4893:     }
1.520     raeburn  4894:     return $output;
1.63      www      4895: }
1.59      www      4896: 
1.822     bisitz   4897: ##############################################
                   4898: =pod
                   4899: 
1.832     bisitz   4900: =item * &authorspace()
                   4901: 
1.1028    raeburn  4902: Inputs: $url (usually will be undef).
1.832     bisitz   4903: 
1.1028    raeburn  4904: Returns: Path to Construction Space containing the resource or 
                   4905:          directory being viewed (or for which action is being taken). 
                   4906:          If $url is provided, and begins /priv/<domain>/<uname>
                   4907:          the path will be that portion of the $context argument.
                   4908:          Otherwise the path will be for the author space of the current
                   4909:          user when the current role is author, or for that of the 
                   4910:          co-author/assistant co-author space when the current role 
                   4911:          is co-author or assistant co-author.
1.832     bisitz   4912: 
                   4913: =cut
                   4914: 
                   4915: sub authorspace {
1.1028    raeburn  4916:     my ($url) = @_;
                   4917:     if ($url ne '') {
                   4918:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4919:            return $1;
                   4920:         }
                   4921:     }
1.832     bisitz   4922:     my $caname = '';
1.1024    www      4923:     my $cadom = '';
1.1028    raeburn  4924:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4925:         ($cadom,$caname) =
1.832     bisitz   4926:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4927:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4928:         $caname = $env{'user.name'};
1.1024    www      4929:         $cadom = $env{'user.domain'};
1.832     bisitz   4930:     }
1.1028    raeburn  4931:     if (($caname ne '') && ($cadom ne '')) {
                   4932:         return "/priv/$cadom/$caname/";
                   4933:     }
                   4934:     return;
1.832     bisitz   4935: }
                   4936: 
                   4937: ##############################################
                   4938: =pod
                   4939: 
1.822     bisitz   4940: =item * &head_subbox()
                   4941: 
                   4942: Inputs: $content (contains HTML code with page functions, etc.)
                   4943: 
                   4944: Returns: HTML div with $content
                   4945:          To be included in page header
                   4946: 
                   4947: =cut
                   4948: 
                   4949: sub head_subbox {
                   4950:     my ($content)=@_;
                   4951:     my $output =
1.993     raeburn  4952:         '<div class="LC_head_subbox">'
1.822     bisitz   4953:        .$content
                   4954:        .'</div>'
                   4955: }
                   4956: 
                   4957: ##############################################
                   4958: =pod
                   4959: 
                   4960: =item * &CSTR_pageheader()
                   4961: 
1.1026    raeburn  4962: Input: (optional) filename from which breadcrumb trail is built.
                   4963:        In most cases no input as needed, as $env{'request.filename'}
                   4964:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4965: 
                   4966: Returns: HTML div with CSTR path and recent box
                   4967:          To be included on Construction Space pages
                   4968: 
                   4969: =cut
                   4970: 
                   4971: sub CSTR_pageheader {
1.1026    raeburn  4972:     my ($trailfile) = @_;
                   4973:     if ($trailfile eq '') {
                   4974:         $trailfile = $env{'request.filename'};
                   4975:     }
                   4976: 
                   4977: # this is for resources; directories have customtitle, and crumbs
                   4978: # and select recent are created in lonpubdir.pm
                   4979: 
                   4980:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      4981:     my ($udom,$uname,$thisdisfn)=
1.1026    raeburn  4982:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
                   4983:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   4984:     $formaction =~ s{/+}{/}g;
1.822     bisitz   4985: 
                   4986:     my $parentpath = '';
                   4987:     my $lastitem = '';
                   4988:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4989:         $parentpath = $1;
                   4990:         $lastitem = $2;
                   4991:     } else {
                   4992:         $lastitem = $thisdisfn;
                   4993:     }
1.921     bisitz   4994: 
                   4995:     my $output =
1.822     bisitz   4996:          '<div>'
                   4997:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
                   4998:         .'<b>'.&mt('Construction Space:').'</b> '
                   4999:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5000:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5001:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5002: 
                   5003:     if ($lastitem) {
                   5004:         $output .=
                   5005:              '<span class="LC_filename">'
                   5006:             .$lastitem
                   5007:             .'</span>';
                   5008:     }
                   5009:     $output .=
                   5010:          '<br />'
1.822     bisitz   5011:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5012:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5013:         .'</form>'
                   5014:         .&Apache::lonmenu::constspaceform()
                   5015:         .'</div>';
1.921     bisitz   5016: 
                   5017:     return $output;
1.822     bisitz   5018: }
                   5019: 
1.60      matthew  5020: ###############################################
                   5021: ###############################################
                   5022: 
                   5023: =pod
                   5024: 
1.112     bowersj2 5025: =back
                   5026: 
1.549     albertel 5027: =head1 HTML Helpers
1.112     bowersj2 5028: 
                   5029: =over 4
                   5030: 
                   5031: =item * &bodytag()
1.60      matthew  5032: 
                   5033: Returns a uniform header for LON-CAPA web pages.
                   5034: 
                   5035: Inputs: 
                   5036: 
1.112     bowersj2 5037: =over 4
                   5038: 
                   5039: =item * $title, A title to be displayed on the page.
                   5040: 
                   5041: =item * $function, the current role (can be undef).
                   5042: 
                   5043: =item * $addentries, extra parameters for the <body> tag.
                   5044: 
                   5045: =item * $bodyonly, if defined, only return the <body> tag.
                   5046: 
                   5047: =item * $domain, if defined, force a given domain.
                   5048: 
                   5049: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5050:             text interface only)
1.60      matthew  5051: 
1.814     bisitz   5052: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5053:                      navigational links
1.317     albertel 5054: 
1.338     albertel 5055: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5056: 
1.460     albertel 5057: =item * $args, optional argument valid values are
                   5058:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5059:             inherit_jsmath -> when creating popup window in a page,
                   5060:                               should it have jsmath forced on by the
                   5061:                               current page
1.460     albertel 5062: 
1.1096    raeburn  5063: =item * $advtoolsref, optional argument, ref to an array containing
                   5064:             inlineremote items to be added in "Functions" menu below
                   5065:             breadcrumbs.
                   5066: 
1.112     bowersj2 5067: =back
                   5068: 
1.60      matthew  5069: Returns: A uniform header for LON-CAPA web pages.  
                   5070: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5071: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5072: other decorations will be returned.
                   5073: 
                   5074: =cut
                   5075: 
1.54      www      5076: sub bodytag {
1.831     bisitz   5077:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5078:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5079: 
1.954     raeburn  5080:     my $public;
                   5081:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5082:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5083:         $public = 1;
                   5084:     }
1.460     albertel 5085:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 5086: 
1.183     matthew  5087:     $function = &get_users_function() if (!$function);
1.339     albertel 5088:     my $img =    &designparm($function.'.img',$domain);
                   5089:     my $font =   &designparm($function.'.font',$domain);
                   5090:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5091: 
1.803     bisitz   5092:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5093: 		   'bgcolor' => $pgbg,
1.339     albertel 5094: 		   'text'    => $font,
                   5095:                    'alink'   => &designparm($function.'.alink',$domain),
                   5096: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5097: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5098:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5099: 
1.63      www      5100:  # role and realm
1.378     raeburn  5101:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5102:     if ($role  eq 'ca') {
1.479     albertel 5103:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5104:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5105:     } 
1.55      www      5106: # realm
1.258     albertel 5107:     if ($env{'request.course.id'}) {
1.378     raeburn  5108:         if ($env{'request.role'} !~ /^cr/) {
                   5109:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5110:         }
1.898     raeburn  5111:         if ($env{'request.course.sec'}) {
                   5112:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5113:         }   
1.359     albertel 5114: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5115:     } else {
                   5116:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5117:     }
1.433     albertel 5118: 
1.359     albertel 5119:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5120: 
1.438     albertel 5121:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5122: 
1.101     www      5123: # construct main body tag
1.359     albertel 5124:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5125: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5126: 
1.530     albertel 5127:     if ($bodyonly) {
1.60      matthew  5128:         return $bodytag;
1.798     tempelho 5129:     } 
1.359     albertel 5130: 
1.410     albertel 5131:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.954     raeburn  5132:     if ($public) {
1.433     albertel 5133: 	undef($role);
1.434     albertel 5134:     } else {
1.1070    raeburn  5135: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5136:                                 undef,'LC_menubuttons_link');
1.433     albertel 5137:     }
1.359     albertel 5138:     
1.762     bisitz   5139:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5140:     #
                   5141:     # Extra info if you are the DC
                   5142:     my $dc_info = '';
                   5143:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5144:                         $env{'course.'.$env{'request.course.id'}.
                   5145:                                  '.domain'}.'/'})) {
                   5146:         my $cid = $env{'request.course.id'};
1.917     raeburn  5147:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5148:         $dc_info =~ s/\s+$//;
1.359     albertel 5149:     }
                   5150: 
1.898     raeburn  5151:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5152:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5153: 
1.916     droeschl 5154:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
                   5155:             return $bodytag; 
                   5156:         } 
1.903     droeschl 5157: 
                   5158:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5159: 
                   5160:         #    if ($env{'request.state'} eq 'construct') {
                   5161:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5162:         #    }
                   5163: 
1.359     albertel 5164: 
                   5165: 
1.916     droeschl 5166:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5167:              if ($dc_info) {
                   5168:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5169:              }
1.916     droeschl 5170:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
                   5171:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5172:             return $bodytag;
                   5173:         }
1.894     droeschl 5174: 
1.927     raeburn  5175:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   5176:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
                   5177:         }
1.916     droeschl 5178: 
1.903     droeschl 5179:         $bodytag .= Apache::lonhtmlcommon::scripttag(
                   5180:             Apache::lonmenu::utilityfunctions(), 'start');
1.816     bisitz   5181: 
1.903     droeschl 5182:         $bodytag .= Apache::lonmenu::primary_menu();
1.852     droeschl 5183: 
1.917     raeburn  5184:         if ($dc_info) {
                   5185:             $dc_info = &dc_courseid_toggle($dc_info);
                   5186:         }
                   5187:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5188: 
1.903     droeschl 5189:         #don't show menus for public users
1.954     raeburn  5190:         if (!$public){
1.903     droeschl 5191:             $bodytag .= Apache::lonmenu::secondary_menu();
                   5192:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5193:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5194:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5195:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5196:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5197:             } elsif ($forcereg) {
                   5198:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5199:                                                             $args->{'group'});
                   5200:             } else {
                   5201:                 $bodytag .= 
                   5202:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5203:                                                         $forcereg,$args->{'group'},
                   5204:                                                         $args->{'bread_crumbs'},
                   5205:                                                         $advtoolsref);
1.920     raeburn  5206:             }
1.903     droeschl 5207:         }else{
                   5208:             # this is to seperate menu from content when there's no secondary
                   5209:             # menu. Especially needed for public accessible ressources.
                   5210:             $bodytag .= '<hr style="clear:both" />';
                   5211:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5212:         }
1.903     droeschl 5213: 
1.235     raeburn  5214:         return $bodytag;
1.182     matthew  5215: }
                   5216: 
1.917     raeburn  5217: sub dc_courseid_toggle {
                   5218:     my ($dc_info) = @_;
1.980     raeburn  5219:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5220:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5221:            &mt('(More ...)').'</a></span>'.
                   5222:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5223: }
                   5224: 
1.330     albertel 5225: sub make_attr_string {
                   5226:     my ($register,$attr_ref) = @_;
                   5227: 
                   5228:     if ($attr_ref && !ref($attr_ref)) {
                   5229: 	die("addentries Must be a hash ref ".
                   5230: 	    join(':',caller(1))." ".
                   5231: 	    join(':',caller(0))." ");
                   5232:     }
                   5233: 
                   5234:     if ($register) {
1.339     albertel 5235: 	my ($on_load,$on_unload);
                   5236: 	foreach my $key (keys(%{$attr_ref})) {
                   5237: 	    if      (lc($key) eq 'onload') {
                   5238: 		$on_load.=$attr_ref->{$key}.';';
                   5239: 		delete($attr_ref->{$key});
                   5240: 
                   5241: 	    } elsif (lc($key) eq 'onunload') {
                   5242: 		$on_unload.=$attr_ref->{$key}.';';
                   5243: 		delete($attr_ref->{$key});
                   5244: 	    }
                   5245: 	}
1.953     droeschl 5246: 	$attr_ref->{'onload'}  = $on_load;
                   5247: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5248:     }
1.339     albertel 5249: 
1.330     albertel 5250:     my $attr_string;
                   5251:     foreach my $attr (keys(%$attr_ref)) {
                   5252: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5253:     }
                   5254:     return $attr_string;
                   5255: }
                   5256: 
                   5257: 
1.182     matthew  5258: ###############################################
1.251     albertel 5259: ###############################################
                   5260: 
                   5261: =pod
                   5262: 
                   5263: =item * &endbodytag()
                   5264: 
                   5265: Returns a uniform footer for LON-CAPA web pages.
                   5266: 
1.635     raeburn  5267: Inputs: 1 - optional reference to an args hash
                   5268: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5269: a 'Continue' link is not displayed if the page contains an
                   5270: internal redirect in the <head></head> section,
                   5271: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5272: 
                   5273: =cut
                   5274: 
                   5275: sub endbodytag {
1.635     raeburn  5276:     my ($args) = @_;
1.1080    raeburn  5277:     my $endbodytag;
                   5278:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5279:         $endbodytag='</body>';
                   5280:     }
1.269     albertel 5281:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5282:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5283:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5284: 	    $endbodytag=
                   5285: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5286: 	        &mt('Continue').'</a>'.
                   5287: 	        $endbodytag;
                   5288:         }
1.315     albertel 5289:     }
1.251     albertel 5290:     return $endbodytag;
                   5291: }
                   5292: 
1.352     albertel 5293: =pod
                   5294: 
                   5295: =item * &standard_css()
                   5296: 
                   5297: Returns a style sheet
                   5298: 
                   5299: Inputs: (all optional)
                   5300:             domain         -> force to color decorate a page for a specific
                   5301:                                domain
                   5302:             function       -> force usage of a specific rolish color scheme
                   5303:             bgcolor        -> override the default page bgcolor
                   5304: 
                   5305: =cut
                   5306: 
1.343     albertel 5307: sub standard_css {
1.345     albertel 5308:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5309:     $function  = &get_users_function() if (!$function);
                   5310:     my $img    = &designparm($function.'.img',   $domain);
                   5311:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5312:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5313:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5314: #second colour for later usage
1.345     albertel 5315:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5316:     my $pgbg_or_bgcolor =
                   5317: 	         $bgcolor ||
1.352     albertel 5318: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5319:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5320:     my $alink  = &designparm($function.'.alink', $domain);
                   5321:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5322:     my $link   = &designparm($function.'.link',  $domain);
                   5323: 
1.602     albertel 5324:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5325:     my $mono                 = 'monospace';
1.850     bisitz   5326:     my $data_table_head      = $sidebg;
                   5327:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5328:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5329:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5330:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5331:     my $mail_new             = '#FFBB77';
                   5332:     my $mail_new_hover       = '#DD9955';
                   5333:     my $mail_read            = '#BBBB77';
                   5334:     my $mail_read_hover      = '#999944';
                   5335:     my $mail_replied         = '#AAAA88';
                   5336:     my $mail_replied_hover   = '#888855';
                   5337:     my $mail_other           = '#99BBBB';
                   5338:     my $mail_other_hover     = '#669999';
1.391     albertel 5339:     my $table_header         = '#DDDDDD';
1.489     raeburn  5340:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5341:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5342:     my $button_hover         = '#BF2317';
1.392     albertel 5343: 
1.608     albertel 5344:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5345:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5346:                                              : '0 3px 0 4px';
1.448     albertel 5347: 
1.523     albertel 5348: 
1.343     albertel 5349:     return <<END;
1.947     droeschl 5350: 
                   5351: /* needed for iframe to allow 100% height in FF */
                   5352: body, html { 
                   5353:     margin: 0;
                   5354:     padding: 0 0.5%;
                   5355:     height: 99%; /* to avoid scrollbars */
                   5356: }
                   5357: 
1.795     www      5358: body {
1.911     bisitz   5359:   font-family: $sans;
                   5360:   line-height:130%;
                   5361:   font-size:0.83em;
                   5362:   color:$font;
1.795     www      5363: }
                   5364: 
1.959     onken    5365: a:focus,
                   5366: a:focus img {
1.795     www      5367:   color: red;
                   5368: }
1.698     harmsja  5369: 
1.911     bisitz   5370: form, .inline {
                   5371:   display: inline;
1.795     www      5372: }
1.721     harmsja  5373: 
1.795     www      5374: .LC_right {
1.911     bisitz   5375:   text-align:right;
1.795     www      5376: }
                   5377: 
                   5378: .LC_middle {
1.911     bisitz   5379:   vertical-align:middle;
1.795     www      5380: }
1.721     harmsja  5381: 
1.911     bisitz   5382: .LC_400Box {
                   5383:   width:400px;
                   5384: }
1.721     harmsja  5385: 
1.947     droeschl 5386: .LC_iframecontainer {
                   5387:     width: 98%;
                   5388:     margin: 0;
                   5389:     position: fixed;
                   5390:     top: 8.5em;
                   5391:     bottom: 0;
                   5392: }
                   5393: 
                   5394: .LC_iframecontainer iframe{
                   5395:     border: none;
                   5396:     width: 100%;
                   5397:     height: 100%;
                   5398: }
                   5399: 
1.778     bisitz   5400: .LC_filename {
                   5401:   font-family: $mono;
                   5402:   white-space:pre;
1.921     bisitz   5403:   font-size: 120%;
1.778     bisitz   5404: }
                   5405: 
                   5406: .LC_fileicon {
                   5407:   border: none;
                   5408:   height: 1.3em;
                   5409:   vertical-align: text-bottom;
                   5410:   margin-right: 0.3em;
                   5411:   text-decoration:none;
                   5412: }
                   5413: 
1.1008    www      5414: .LC_setting {
                   5415:   text-decoration:underline;
                   5416: }
                   5417: 
1.350     albertel 5418: .LC_error {
                   5419:   color: red;
                   5420: }
1.795     www      5421: 
1.1097    bisitz   5422: .LC_warning {
                   5423:   color: darkorange;
                   5424: }
                   5425: 
1.457     albertel 5426: .LC_diff_removed {
1.733     bisitz   5427:   color: red;
1.394     albertel 5428: }
1.532     albertel 5429: 
                   5430: .LC_info,
1.457     albertel 5431: .LC_success,
                   5432: .LC_diff_added {
1.350     albertel 5433:   color: green;
                   5434: }
1.795     www      5435: 
1.802     bisitz   5436: div.LC_confirm_box {
                   5437:   background-color: #FAFAFA;
                   5438:   border: 1px solid $lg_border_color;
                   5439:   margin-right: 0;
                   5440:   padding: 5px;
                   5441: }
                   5442: 
                   5443: div.LC_confirm_box .LC_error img,
                   5444: div.LC_confirm_box .LC_success img {
                   5445:   vertical-align: middle;
                   5446: }
                   5447: 
1.440     albertel 5448: .LC_icon {
1.771     droeschl 5449:   border: none;
1.790     droeschl 5450:   vertical-align: middle;
1.771     droeschl 5451: }
                   5452: 
1.543     albertel 5453: .LC_docs_spacer {
                   5454:   width: 25px;
                   5455:   height: 1px;
1.771     droeschl 5456:   border: none;
1.543     albertel 5457: }
1.346     albertel 5458: 
1.532     albertel 5459: .LC_internal_info {
1.735     bisitz   5460:   color: #999999;
1.532     albertel 5461: }
                   5462: 
1.794     www      5463: .LC_discussion {
1.1050    www      5464:   background: $data_table_dark;
1.911     bisitz   5465:   border: 1px solid black;
                   5466:   margin: 2px;
1.794     www      5467: }
                   5468: 
                   5469: .LC_disc_action_left {
1.1050    www      5470:   background: $sidebg;
1.911     bisitz   5471:   text-align: left;
1.1050    www      5472:   padding: 4px;
                   5473:   margin: 2px;
1.794     www      5474: }
                   5475: 
                   5476: .LC_disc_action_right {
1.1050    www      5477:   background: $sidebg;
1.911     bisitz   5478:   text-align: right;
1.1050    www      5479:   padding: 4px;
                   5480:   margin: 2px;
1.794     www      5481: }
                   5482: 
                   5483: .LC_disc_new_item {
1.911     bisitz   5484:   background: white;
                   5485:   border: 2px solid red;
1.1050    www      5486:   margin: 4px;
                   5487:   padding: 4px;
1.794     www      5488: }
                   5489: 
                   5490: .LC_disc_old_item {
1.911     bisitz   5491:   background: white;
1.1050    www      5492:   margin: 4px;
                   5493:   padding: 4px;
1.794     www      5494: }
                   5495: 
1.458     albertel 5496: table.LC_pastsubmission {
                   5497:   border: 1px solid black;
                   5498:   margin: 2px;
                   5499: }
                   5500: 
1.924     bisitz   5501: table#LC_menubuttons {
1.345     albertel 5502:   width: 100%;
                   5503:   background: $pgbg;
1.392     albertel 5504:   border: 2px;
1.402     albertel 5505:   border-collapse: separate;
1.803     bisitz   5506:   padding: 0;
1.345     albertel 5507: }
1.392     albertel 5508: 
1.801     tempelho 5509: table#LC_title_bar a {
                   5510:   color: $fontmenu;
                   5511: }
1.836     bisitz   5512: 
1.807     droeschl 5513: table#LC_title_bar {
1.819     tempelho 5514:   clear: both;
1.836     bisitz   5515:   display: none;
1.807     droeschl 5516: }
                   5517: 
1.795     www      5518: table#LC_title_bar,
1.933     droeschl 5519: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5520: table#LC_title_bar.LC_with_remote {
1.359     albertel 5521:   width: 100%;
1.392     albertel 5522:   border-color: $pgbg;
                   5523:   border-style: solid;
                   5524:   border-width: $border;
1.379     albertel 5525:   background: $pgbg;
1.801     tempelho 5526:   color: $fontmenu;
1.392     albertel 5527:   border-collapse: collapse;
1.803     bisitz   5528:   padding: 0;
1.819     tempelho 5529:   margin: 0;
1.359     albertel 5530: }
1.795     www      5531: 
1.933     droeschl 5532: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5533:     margin: 0;
                   5534:     padding: 0;
1.933     droeschl 5535:     position: relative;
                   5536:     list-style: none;
1.913     droeschl 5537: }
1.933     droeschl 5538: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5539:     display: inline;
                   5540: }
1.933     droeschl 5541: 
                   5542: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5543:     padding: 0;
1.933     droeschl 5544:     margin: 0;
                   5545:     float: left;
1.913     droeschl 5546: }
1.933     droeschl 5547: .LC_breadcrumb_tools_tools {
                   5548:     padding: 0;
                   5549:     margin: 0;
1.913     droeschl 5550:     float: right;
                   5551: }
                   5552: 
1.359     albertel 5553: table#LC_title_bar td {
                   5554:   background: $tabbg;
                   5555: }
1.795     www      5556: 
1.911     bisitz   5557: table#LC_menubuttons img {
1.803     bisitz   5558:   border: none;
1.346     albertel 5559: }
1.795     www      5560: 
1.842     droeschl 5561: .LC_breadcrumbs_component {
1.911     bisitz   5562:   float: right;
                   5563:   margin: 0 1em;
1.357     albertel 5564: }
1.842     droeschl 5565: .LC_breadcrumbs_component img {
1.911     bisitz   5566:   vertical-align: middle;
1.777     tempelho 5567: }
1.795     www      5568: 
1.383     albertel 5569: td.LC_table_cell_checkbox {
                   5570:   text-align: center;
                   5571: }
1.795     www      5572: 
                   5573: .LC_fontsize_small {
1.911     bisitz   5574:   font-size: 70%;
1.705     tempelho 5575: }
                   5576: 
1.844     bisitz   5577: #LC_breadcrumbs {
1.911     bisitz   5578:   clear:both;
                   5579:   background: $sidebg;
                   5580:   border-bottom: 1px solid $lg_border_color;
                   5581:   line-height: 2.5em;
1.933     droeschl 5582:   overflow: hidden;
1.911     bisitz   5583:   margin: 0;
                   5584:   padding: 0;
1.995     raeburn  5585:   text-align: left;
1.819     tempelho 5586: }
1.862     bisitz   5587: 
1.1098    bisitz   5588: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5589:   clear:both;
                   5590:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5591:   border: 1px solid $sidebg;
1.1098    bisitz   5592:   margin: 0 0 10px 0;
1.966     bisitz   5593:   padding: 3px;
1.995     raeburn  5594:   text-align: left;
1.822     bisitz   5595: }
                   5596: 
1.795     www      5597: .LC_fontsize_medium {
1.911     bisitz   5598:   font-size: 85%;
1.705     tempelho 5599: }
                   5600: 
1.795     www      5601: .LC_fontsize_large {
1.911     bisitz   5602:   font-size: 120%;
1.705     tempelho 5603: }
                   5604: 
1.346     albertel 5605: .LC_menubuttons_inline_text {
                   5606:   color: $font;
1.698     harmsja  5607:   font-size: 90%;
1.701     harmsja  5608:   padding-left:3px;
1.346     albertel 5609: }
                   5610: 
1.934     droeschl 5611: .LC_menubuttons_inline_text img{
                   5612:   vertical-align: middle;
                   5613: }
                   5614: 
1.1051    www      5615: li.LC_menubuttons_inline_text img {
1.951     onken    5616:   cursor:pointer;
1.1002    droeschl 5617:   text-decoration: none;
1.951     onken    5618: }
                   5619: 
1.526     www      5620: .LC_menubuttons_link {
                   5621:   text-decoration: none;
                   5622: }
1.795     www      5623: 
1.522     albertel 5624: .LC_menubuttons_category {
1.521     www      5625:   color: $font;
1.526     www      5626:   background: $pgbg;
1.521     www      5627:   font-size: larger;
                   5628:   font-weight: bold;
                   5629: }
                   5630: 
1.346     albertel 5631: td.LC_menubuttons_text {
1.911     bisitz   5632:   color: $font;
1.346     albertel 5633: }
1.706     harmsja  5634: 
1.346     albertel 5635: .LC_current_location {
                   5636:   background: $tabbg;
                   5637: }
1.795     www      5638: 
1.938     bisitz   5639: table.LC_data_table {
1.347     albertel 5640:   border: 1px solid #000000;
1.402     albertel 5641:   border-collapse: separate;
1.426     albertel 5642:   border-spacing: 1px;
1.610     albertel 5643:   background: $pgbg;
1.347     albertel 5644: }
1.795     www      5645: 
1.422     albertel 5646: .LC_data_table_dense {
                   5647:   font-size: small;
                   5648: }
1.795     www      5649: 
1.507     raeburn  5650: table.LC_nested_outer {
                   5651:   border: 1px solid #000000;
1.589     raeburn  5652:   border-collapse: collapse;
1.803     bisitz   5653:   border-spacing: 0;
1.507     raeburn  5654:   width: 100%;
                   5655: }
1.795     www      5656: 
1.879     raeburn  5657: table.LC_innerpickbox,
1.507     raeburn  5658: table.LC_nested {
1.803     bisitz   5659:   border: none;
1.589     raeburn  5660:   border-collapse: collapse;
1.803     bisitz   5661:   border-spacing: 0;
1.507     raeburn  5662:   width: 100%;
                   5663: }
1.795     www      5664: 
1.911     bisitz   5665: table.LC_data_table tr th,
                   5666: table.LC_calendar tr th,
1.879     raeburn  5667: table.LC_prior_tries tr th,
                   5668: table.LC_innerpickbox tr th {
1.349     albertel 5669:   font-weight: bold;
                   5670:   background-color: $data_table_head;
1.801     tempelho 5671:   color:$fontmenu;
1.701     harmsja  5672:   font-size:90%;
1.347     albertel 5673: }
1.795     www      5674: 
1.879     raeburn  5675: table.LC_innerpickbox tr th,
                   5676: table.LC_innerpickbox tr td {
                   5677:   vertical-align: top;
                   5678: }
                   5679: 
1.711     raeburn  5680: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5681:   background-color: #CCCCCC;
1.711     raeburn  5682:   font-weight: bold;
                   5683:   text-align: left;
                   5684: }
1.795     www      5685: 
1.912     bisitz   5686: table.LC_data_table tr.LC_odd_row > td {
                   5687:   background-color: $data_table_light;
                   5688:   padding: 2px;
                   5689:   vertical-align: top;
                   5690: }
                   5691: 
1.809     bisitz   5692: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5693:   background-color: $data_table_light;
1.912     bisitz   5694:   vertical-align: top;
                   5695: }
                   5696: 
                   5697: table.LC_data_table tr.LC_even_row > td {
                   5698:   background-color: $data_table_dark;
1.425     albertel 5699:   padding: 2px;
1.900     bisitz   5700:   vertical-align: top;
1.347     albertel 5701: }
1.795     www      5702: 
1.809     bisitz   5703: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5704:   background-color: $data_table_dark;
1.900     bisitz   5705:   vertical-align: top;
1.347     albertel 5706: }
1.795     www      5707: 
1.425     albertel 5708: table.LC_data_table tr.LC_data_table_highlight td {
                   5709:   background-color: $data_table_darker;
                   5710: }
1.795     www      5711: 
1.639     raeburn  5712: table.LC_data_table tr td.LC_leftcol_header {
                   5713:   background-color: $data_table_head;
                   5714:   font-weight: bold;
                   5715: }
1.795     www      5716: 
1.451     albertel 5717: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5718: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5719:   font-weight: bold;
                   5720:   font-style: italic;
                   5721:   text-align: center;
                   5722:   padding: 8px;
1.347     albertel 5723: }
1.795     www      5724: 
1.940     bisitz   5725: table.LC_data_table tr.LC_empty_row td {
                   5726:   background-color: $sidebg;
                   5727: }
                   5728: 
                   5729: table.LC_nested tr.LC_empty_row td {
                   5730:   background-color: #FFFFFF;
                   5731: }
                   5732: 
1.890     droeschl 5733: table.LC_caption {
                   5734: }
                   5735: 
1.507     raeburn  5736: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5737:   padding: 4ex
                   5738: }
1.795     www      5739: 
1.507     raeburn  5740: table.LC_nested_outer tr th {
                   5741:   font-weight: bold;
1.801     tempelho 5742:   color:$fontmenu;
1.507     raeburn  5743:   background-color: $data_table_head;
1.701     harmsja  5744:   font-size: small;
1.507     raeburn  5745:   border-bottom: 1px solid #000000;
                   5746: }
1.795     www      5747: 
1.507     raeburn  5748: table.LC_nested_outer tr td.LC_subheader {
                   5749:   background-color: $data_table_head;
                   5750:   font-weight: bold;
                   5751:   font-size: small;
                   5752:   border-bottom: 1px solid #000000;
                   5753:   text-align: right;
1.451     albertel 5754: }
1.795     www      5755: 
1.507     raeburn  5756: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5757:   background-color: #CCCCCC;
1.451     albertel 5758:   font-weight: bold;
                   5759:   font-size: small;
1.507     raeburn  5760:   text-align: center;
                   5761: }
1.795     www      5762: 
1.589     raeburn  5763: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5764: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5765:   text-align: left;
1.451     albertel 5766: }
1.795     www      5767: 
1.507     raeburn  5768: table.LC_nested td {
1.735     bisitz   5769:   background-color: #FFFFFF;
1.451     albertel 5770:   font-size: small;
1.507     raeburn  5771: }
1.795     www      5772: 
1.507     raeburn  5773: table.LC_nested_outer tr th.LC_right_item,
                   5774: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5775: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5776: table.LC_nested tr td.LC_right_item {
1.451     albertel 5777:   text-align: right;
                   5778: }
                   5779: 
1.507     raeburn  5780: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5781:   background-color: #EEEEEE;
1.451     albertel 5782: }
                   5783: 
1.473     raeburn  5784: table.LC_createuser {
                   5785: }
                   5786: 
                   5787: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5788:   font-size: small;
1.473     raeburn  5789: }
                   5790: 
                   5791: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5792:   background-color: #CCCCCC;
1.473     raeburn  5793:   font-weight: bold;
                   5794:   text-align: center;
                   5795: }
                   5796: 
1.349     albertel 5797: table.LC_calendar {
                   5798:   border: 1px solid #000000;
                   5799:   border-collapse: collapse;
1.917     raeburn  5800:   width: 98%;
1.349     albertel 5801: }
1.795     www      5802: 
1.349     albertel 5803: table.LC_calendar_pickdate {
                   5804:   font-size: xx-small;
                   5805: }
1.795     www      5806: 
1.349     albertel 5807: table.LC_calendar tr td {
                   5808:   border: 1px solid #000000;
                   5809:   vertical-align: top;
1.917     raeburn  5810:   width: 14%;
1.349     albertel 5811: }
1.795     www      5812: 
1.349     albertel 5813: table.LC_calendar tr td.LC_calendar_day_empty {
                   5814:   background-color: $data_table_dark;
                   5815: }
1.795     www      5816: 
1.779     bisitz   5817: table.LC_calendar tr td.LC_calendar_day_current {
                   5818:   background-color: $data_table_highlight;
1.777     tempelho 5819: }
1.795     www      5820: 
1.938     bisitz   5821: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5822:   background-color: $mail_new;
                   5823: }
1.795     www      5824: 
1.938     bisitz   5825: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5826:   background-color: $mail_new_hover;
                   5827: }
1.795     www      5828: 
1.938     bisitz   5829: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5830:   background-color: $mail_read;
                   5831: }
1.795     www      5832: 
1.938     bisitz   5833: /*
                   5834: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5835:   background-color: $mail_read_hover;
                   5836: }
1.938     bisitz   5837: */
1.795     www      5838: 
1.938     bisitz   5839: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5840:   background-color: $mail_replied;
                   5841: }
1.795     www      5842: 
1.938     bisitz   5843: /*
                   5844: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5845:   background-color: $mail_replied_hover;
                   5846: }
1.938     bisitz   5847: */
1.795     www      5848: 
1.938     bisitz   5849: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5850:   background-color: $mail_other;
                   5851: }
1.795     www      5852: 
1.938     bisitz   5853: /*
                   5854: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5855:   background-color: $mail_other_hover;
                   5856: }
1.938     bisitz   5857: */
1.494     raeburn  5858: 
1.777     tempelho 5859: table.LC_data_table tr > td.LC_browser_file,
                   5860: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5861:   background: #AAEE77;
1.389     albertel 5862: }
1.795     www      5863: 
1.777     tempelho 5864: table.LC_data_table tr > td.LC_browser_file_locked,
                   5865: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5866:   background: #FFAA99;
1.387     albertel 5867: }
1.795     www      5868: 
1.777     tempelho 5869: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5870:   background: #888888;
1.779     bisitz   5871: }
1.795     www      5872: 
1.777     tempelho 5873: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5874: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5875:   background: #F8F866;
1.777     tempelho 5876: }
1.795     www      5877: 
1.696     bisitz   5878: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5879:   background: #E0E8FF;
1.387     albertel 5880: }
1.696     bisitz   5881: 
1.707     bisitz   5882: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5883:   /* background: #77FF77; */
1.707     bisitz   5884: }
1.795     www      5885: 
1.707     bisitz   5886: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5887:   border-right: 8px solid #FFFF77;
1.707     bisitz   5888: }
1.795     www      5889: 
1.707     bisitz   5890: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5891:   border-right: 8px solid #FFAA77;
1.707     bisitz   5892: }
1.795     www      5893: 
1.707     bisitz   5894: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5895:   border-right: 8px solid #FF7777;
1.707     bisitz   5896: }
1.795     www      5897: 
1.707     bisitz   5898: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5899:   border-right: 8px solid #AAFF77;
1.707     bisitz   5900: }
1.795     www      5901: 
1.707     bisitz   5902: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5903:   border-right: 8px solid #11CC55;
1.707     bisitz   5904: }
                   5905: 
1.388     albertel 5906: span.LC_current_location {
1.701     harmsja  5907:   font-size:larger;
1.388     albertel 5908:   background: $pgbg;
                   5909: }
1.387     albertel 5910: 
1.1029    www      5911: span.LC_current_nav_location {
                   5912:   font-weight:bold;
                   5913:   background: $sidebg;
                   5914: }
                   5915: 
1.395     albertel 5916: span.LC_parm_menu_item {
                   5917:   font-size: larger;
                   5918: }
1.795     www      5919: 
1.395     albertel 5920: span.LC_parm_scope_all {
                   5921:   color: red;
                   5922: }
1.795     www      5923: 
1.395     albertel 5924: span.LC_parm_scope_folder {
                   5925:   color: green;
                   5926: }
1.795     www      5927: 
1.395     albertel 5928: span.LC_parm_scope_resource {
                   5929:   color: orange;
                   5930: }
1.795     www      5931: 
1.395     albertel 5932: span.LC_parm_part {
                   5933:   color: blue;
                   5934: }
1.795     www      5935: 
1.911     bisitz   5936: span.LC_parm_folder,
                   5937: span.LC_parm_symb {
1.395     albertel 5938:   font-size: x-small;
                   5939:   font-family: $mono;
                   5940:   color: #AAAAAA;
                   5941: }
                   5942: 
1.977     bisitz   5943: ul.LC_parm_parmlist li {
                   5944:   display: inline-block;
                   5945:   padding: 0.3em 0.8em;
                   5946:   vertical-align: top;
                   5947:   width: 150px;
                   5948:   border-top:1px solid $lg_border_color;
                   5949: }
                   5950: 
1.795     www      5951: td.LC_parm_overview_level_menu,
                   5952: td.LC_parm_overview_map_menu,
                   5953: td.LC_parm_overview_parm_selectors,
                   5954: td.LC_parm_overview_restrictions  {
1.396     albertel 5955:   border: 1px solid black;
                   5956:   border-collapse: collapse;
                   5957: }
1.795     www      5958: 
1.396     albertel 5959: table.LC_parm_overview_restrictions td {
                   5960:   border-width: 1px 4px 1px 4px;
                   5961:   border-style: solid;
                   5962:   border-color: $pgbg;
                   5963:   text-align: center;
                   5964: }
1.795     www      5965: 
1.396     albertel 5966: table.LC_parm_overview_restrictions th {
                   5967:   background: $tabbg;
                   5968:   border-width: 1px 4px 1px 4px;
                   5969:   border-style: solid;
                   5970:   border-color: $pgbg;
                   5971: }
1.795     www      5972: 
1.398     albertel 5973: table#LC_helpmenu {
1.803     bisitz   5974:   border: none;
1.398     albertel 5975:   height: 55px;
1.803     bisitz   5976:   border-spacing: 0;
1.398     albertel 5977: }
                   5978: 
                   5979: table#LC_helpmenu fieldset legend {
                   5980:   font-size: larger;
                   5981: }
1.795     www      5982: 
1.397     albertel 5983: table#LC_helpmenu_links {
                   5984:   width: 100%;
                   5985:   border: 1px solid black;
                   5986:   background: $pgbg;
1.803     bisitz   5987:   padding: 0;
1.397     albertel 5988:   border-spacing: 1px;
                   5989: }
1.795     www      5990: 
1.397     albertel 5991: table#LC_helpmenu_links tr td {
                   5992:   padding: 1px;
                   5993:   background: $tabbg;
1.399     albertel 5994:   text-align: center;
                   5995:   font-weight: bold;
1.397     albertel 5996: }
1.396     albertel 5997: 
1.795     www      5998: table#LC_helpmenu_links a:link,
                   5999: table#LC_helpmenu_links a:visited,
1.397     albertel 6000: table#LC_helpmenu_links a:active {
                   6001:   text-decoration: none;
                   6002:   color: $font;
                   6003: }
1.795     www      6004: 
1.397     albertel 6005: table#LC_helpmenu_links a:hover {
                   6006:   text-decoration: underline;
                   6007:   color: $vlink;
                   6008: }
1.396     albertel 6009: 
1.417     albertel 6010: .LC_chrt_popup_exists {
                   6011:   border: 1px solid #339933;
                   6012:   margin: -1px;
                   6013: }
1.795     www      6014: 
1.417     albertel 6015: .LC_chrt_popup_up {
                   6016:   border: 1px solid yellow;
                   6017:   margin: -1px;
                   6018: }
1.795     www      6019: 
1.417     albertel 6020: .LC_chrt_popup {
                   6021:   border: 1px solid #8888FF;
                   6022:   background: #CCCCFF;
                   6023: }
1.795     www      6024: 
1.421     albertel 6025: table.LC_pick_box {
                   6026:   border-collapse: separate;
                   6027:   background: white;
                   6028:   border: 1px solid black;
                   6029:   border-spacing: 1px;
                   6030: }
1.795     www      6031: 
1.421     albertel 6032: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6033:   background: $sidebg;
1.421     albertel 6034:   font-weight: bold;
1.900     bisitz   6035:   text-align: left;
1.740     bisitz   6036:   vertical-align: top;
1.421     albertel 6037:   width: 184px;
                   6038:   padding: 8px;
                   6039: }
1.795     www      6040: 
1.579     raeburn  6041: table.LC_pick_box td.LC_pick_box_value {
                   6042:   text-align: left;
                   6043:   padding: 8px;
                   6044: }
1.795     www      6045: 
1.579     raeburn  6046: table.LC_pick_box td.LC_pick_box_select {
                   6047:   text-align: left;
                   6048:   padding: 8px;
                   6049: }
1.795     www      6050: 
1.424     albertel 6051: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6052:   padding: 0;
1.421     albertel 6053:   height: 1px;
                   6054:   background: black;
                   6055: }
1.795     www      6056: 
1.421     albertel 6057: table.LC_pick_box td.LC_pick_box_submit {
                   6058:   text-align: right;
                   6059: }
1.795     www      6060: 
1.579     raeburn  6061: table.LC_pick_box td.LC_evenrow_value {
                   6062:   text-align: left;
                   6063:   padding: 8px;
                   6064:   background-color: $data_table_light;
                   6065: }
1.795     www      6066: 
1.579     raeburn  6067: table.LC_pick_box td.LC_oddrow_value {
                   6068:   text-align: left;
                   6069:   padding: 8px;
                   6070:   background-color: $data_table_light;
                   6071: }
1.795     www      6072: 
1.579     raeburn  6073: span.LC_helpform_receipt_cat {
                   6074:   font-weight: bold;
                   6075: }
1.795     www      6076: 
1.424     albertel 6077: table.LC_group_priv_box {
                   6078:   background: white;
                   6079:   border: 1px solid black;
                   6080:   border-spacing: 1px;
                   6081: }
1.795     www      6082: 
1.424     albertel 6083: table.LC_group_priv_box td.LC_pick_box_title {
                   6084:   background: $tabbg;
                   6085:   font-weight: bold;
                   6086:   text-align: right;
                   6087:   width: 184px;
                   6088: }
1.795     www      6089: 
1.424     albertel 6090: table.LC_group_priv_box td.LC_groups_fixed {
                   6091:   background: $data_table_light;
                   6092:   text-align: center;
                   6093: }
1.795     www      6094: 
1.424     albertel 6095: table.LC_group_priv_box td.LC_groups_optional {
                   6096:   background: $data_table_dark;
                   6097:   text-align: center;
                   6098: }
1.795     www      6099: 
1.424     albertel 6100: table.LC_group_priv_box td.LC_groups_functionality {
                   6101:   background: $data_table_darker;
                   6102:   text-align: center;
                   6103:   font-weight: bold;
                   6104: }
1.795     www      6105: 
1.424     albertel 6106: table.LC_group_priv td {
                   6107:   text-align: left;
1.803     bisitz   6108:   padding: 0;
1.424     albertel 6109: }
                   6110: 
                   6111: .LC_navbuttons {
                   6112:   margin: 2ex 0ex 2ex 0ex;
                   6113: }
1.795     www      6114: 
1.423     albertel 6115: .LC_topic_bar {
                   6116:   font-weight: bold;
                   6117:   background: $tabbg;
1.918     wenzelju 6118:   margin: 1em 0em 1em 2em;
1.805     bisitz   6119:   padding: 3px;
1.918     wenzelju 6120:   font-size: 1.2em;
1.423     albertel 6121: }
1.795     www      6122: 
1.423     albertel 6123: .LC_topic_bar span {
1.918     wenzelju 6124:   left: 0.5em;
                   6125:   position: absolute;
1.423     albertel 6126:   vertical-align: middle;
1.918     wenzelju 6127:   font-size: 1.2em;
1.423     albertel 6128: }
1.795     www      6129: 
1.423     albertel 6130: table.LC_course_group_status {
                   6131:   margin: 20px;
                   6132: }
1.795     www      6133: 
1.423     albertel 6134: table.LC_status_selector td {
                   6135:   vertical-align: top;
                   6136:   text-align: center;
1.424     albertel 6137:   padding: 4px;
                   6138: }
1.795     www      6139: 
1.599     albertel 6140: div.LC_feedback_link {
1.616     albertel 6141:   clear: both;
1.829     kalberla 6142:   background: $sidebg;
1.779     bisitz   6143:   width: 100%;
1.829     kalberla 6144:   padding-bottom: 10px;
                   6145:   border: 1px $tabbg solid;
1.833     kalberla 6146:   height: 22px;
                   6147:   line-height: 22px;
                   6148:   padding-top: 5px;
                   6149: }
                   6150: 
                   6151: div.LC_feedback_link img {
                   6152:   height: 22px;
1.867     kalberla 6153:   vertical-align:middle;
1.829     kalberla 6154: }
                   6155: 
1.911     bisitz   6156: div.LC_feedback_link a {
1.829     kalberla 6157:   text-decoration: none;
1.489     raeburn  6158: }
1.795     www      6159: 
1.867     kalberla 6160: div.LC_comblock {
1.911     bisitz   6161:   display:inline;
1.867     kalberla 6162:   color:$font;
                   6163:   font-size:90%;
                   6164: }
                   6165: 
                   6166: div.LC_feedback_link div.LC_comblock {
                   6167:   padding-left:5px;
                   6168: }
                   6169: 
                   6170: div.LC_feedback_link div.LC_comblock a {
                   6171:   color:$font;
                   6172: }
                   6173: 
1.489     raeburn  6174: span.LC_feedback_link {
1.858     bisitz   6175:   /* background: $feedback_link_bg; */
1.599     albertel 6176:   font-size: larger;
                   6177: }
1.795     www      6178: 
1.599     albertel 6179: span.LC_message_link {
1.858     bisitz   6180:   /* background: $feedback_link_bg; */
1.599     albertel 6181:   font-size: larger;
                   6182:   position: absolute;
                   6183:   right: 1em;
1.489     raeburn  6184: }
1.421     albertel 6185: 
1.515     albertel 6186: table.LC_prior_tries {
1.524     albertel 6187:   border: 1px solid #000000;
                   6188:   border-collapse: separate;
                   6189:   border-spacing: 1px;
1.515     albertel 6190: }
1.523     albertel 6191: 
1.515     albertel 6192: table.LC_prior_tries td {
1.524     albertel 6193:   padding: 2px;
1.515     albertel 6194: }
1.523     albertel 6195: 
                   6196: .LC_answer_correct {
1.795     www      6197:   background: lightgreen;
                   6198:   color: darkgreen;
                   6199:   padding: 6px;
1.523     albertel 6200: }
1.795     www      6201: 
1.523     albertel 6202: .LC_answer_charged_try {
1.797     www      6203:   background: #FFAAAA;
1.795     www      6204:   color: darkred;
                   6205:   padding: 6px;
1.523     albertel 6206: }
1.795     www      6207: 
1.779     bisitz   6208: .LC_answer_not_charged_try,
1.523     albertel 6209: .LC_answer_no_grade,
                   6210: .LC_answer_late {
1.795     www      6211:   background: lightyellow;
1.523     albertel 6212:   color: black;
1.795     www      6213:   padding: 6px;
1.523     albertel 6214: }
1.795     www      6215: 
1.523     albertel 6216: .LC_answer_previous {
1.795     www      6217:   background: lightblue;
                   6218:   color: darkblue;
                   6219:   padding: 6px;
1.523     albertel 6220: }
1.795     www      6221: 
1.779     bisitz   6222: .LC_answer_no_message {
1.777     tempelho 6223:   background: #FFFFFF;
                   6224:   color: black;
1.795     www      6225:   padding: 6px;
1.779     bisitz   6226: }
1.795     www      6227: 
1.779     bisitz   6228: .LC_answer_unknown {
                   6229:   background: orange;
                   6230:   color: black;
1.795     www      6231:   padding: 6px;
1.777     tempelho 6232: }
1.795     www      6233: 
1.529     albertel 6234: span.LC_prior_numerical,
                   6235: span.LC_prior_string,
                   6236: span.LC_prior_custom,
                   6237: span.LC_prior_reaction,
                   6238: span.LC_prior_math {
1.925     bisitz   6239:   font-family: $mono;
1.523     albertel 6240:   white-space: pre;
                   6241: }
                   6242: 
1.525     albertel 6243: span.LC_prior_string {
1.925     bisitz   6244:   font-family: $mono;
1.525     albertel 6245:   white-space: pre;
                   6246: }
                   6247: 
1.523     albertel 6248: table.LC_prior_option {
                   6249:   width: 100%;
                   6250:   border-collapse: collapse;
                   6251: }
1.795     www      6252: 
1.911     bisitz   6253: table.LC_prior_rank,
1.795     www      6254: table.LC_prior_match {
1.528     albertel 6255:   border-collapse: collapse;
                   6256: }
1.795     www      6257: 
1.528     albertel 6258: table.LC_prior_option tr td,
                   6259: table.LC_prior_rank tr td,
                   6260: table.LC_prior_match tr td {
1.524     albertel 6261:   border: 1px solid #000000;
1.515     albertel 6262: }
                   6263: 
1.855     bisitz   6264: .LC_nobreak {
1.544     albertel 6265:   white-space: nowrap;
1.519     raeburn  6266: }
                   6267: 
1.576     raeburn  6268: span.LC_cusr_emph {
                   6269:   font-style: italic;
                   6270: }
                   6271: 
1.633     raeburn  6272: span.LC_cusr_subheading {
                   6273:   font-weight: normal;
                   6274:   font-size: 85%;
                   6275: }
                   6276: 
1.861     bisitz   6277: div.LC_docs_entry_move {
1.859     bisitz   6278:   border: 1px solid #BBBBBB;
1.545     albertel 6279:   background: #DDDDDD;
1.861     bisitz   6280:   width: 22px;
1.859     bisitz   6281:   padding: 1px;
                   6282:   margin: 0;
1.545     albertel 6283: }
                   6284: 
1.861     bisitz   6285: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6286: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6287:   font-size: x-small;
                   6288: }
1.795     www      6289: 
1.861     bisitz   6290: .LC_docs_entry_parameter {
                   6291:   white-space: nowrap;
                   6292: }
                   6293: 
1.544     albertel 6294: .LC_docs_copy {
1.545     albertel 6295:   color: #000099;
1.544     albertel 6296: }
1.795     www      6297: 
1.544     albertel 6298: .LC_docs_cut {
1.545     albertel 6299:   color: #550044;
1.544     albertel 6300: }
1.795     www      6301: 
1.544     albertel 6302: .LC_docs_rename {
1.545     albertel 6303:   color: #009900;
1.544     albertel 6304: }
1.795     www      6305: 
1.544     albertel 6306: .LC_docs_remove {
1.545     albertel 6307:   color: #990000;
                   6308: }
                   6309: 
1.547     albertel 6310: .LC_docs_reinit_warn,
                   6311: .LC_docs_ext_edit {
                   6312:   font-size: x-small;
                   6313: }
                   6314: 
1.545     albertel 6315: table.LC_docs_adddocs td,
                   6316: table.LC_docs_adddocs th {
                   6317:   border: 1px solid #BBBBBB;
                   6318:   padding: 4px;
                   6319:   background: #DDDDDD;
1.543     albertel 6320: }
                   6321: 
1.584     albertel 6322: table.LC_sty_begin {
                   6323:   background: #BBFFBB;
                   6324: }
1.795     www      6325: 
1.584     albertel 6326: table.LC_sty_end {
                   6327:   background: #FFBBBB;
                   6328: }
                   6329: 
1.589     raeburn  6330: table.LC_double_column {
1.803     bisitz   6331:   border-width: 0;
1.589     raeburn  6332:   border-collapse: collapse;
                   6333:   width: 100%;
                   6334:   padding: 2px;
                   6335: }
                   6336: 
                   6337: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6338:   top: 2px;
1.589     raeburn  6339:   left: 2px;
                   6340:   width: 47%;
                   6341:   vertical-align: top;
                   6342: }
                   6343: 
                   6344: table.LC_double_column tr td.LC_right_col {
                   6345:   top: 2px;
1.779     bisitz   6346:   right: 2px;
1.589     raeburn  6347:   width: 47%;
                   6348:   vertical-align: top;
                   6349: }
                   6350: 
1.591     raeburn  6351: div.LC_left_float {
                   6352:   float: left;
                   6353:   padding-right: 5%;
1.597     albertel 6354:   padding-bottom: 4px;
1.591     raeburn  6355: }
                   6356: 
                   6357: div.LC_clear_float_header {
1.597     albertel 6358:   padding-bottom: 2px;
1.591     raeburn  6359: }
                   6360: 
                   6361: div.LC_clear_float_footer {
1.597     albertel 6362:   padding-top: 10px;
1.591     raeburn  6363:   clear: both;
                   6364: }
                   6365: 
1.597     albertel 6366: div.LC_grade_show_user {
1.941     bisitz   6367: /*  border-left: 5px solid $sidebg; */
                   6368:   border-top: 5px solid #000000;
                   6369:   margin: 50px 0 0 0;
1.936     bisitz   6370:   padding: 15px 0 5px 10px;
1.597     albertel 6371: }
1.795     www      6372: 
1.936     bisitz   6373: div.LC_grade_show_user_odd_row {
1.941     bisitz   6374: /*  border-left: 5px solid #000000; */
                   6375: }
                   6376: 
                   6377: div.LC_grade_show_user div.LC_Box {
                   6378:   margin-right: 50px;
1.597     albertel 6379: }
                   6380: 
                   6381: div.LC_grade_submissions,
                   6382: div.LC_grade_message_center,
1.936     bisitz   6383: div.LC_grade_info_links {
1.597     albertel 6384:   margin: 5px;
                   6385:   width: 99%;
                   6386:   background: #FFFFFF;
                   6387: }
1.795     www      6388: 
1.597     albertel 6389: div.LC_grade_submissions_header,
1.936     bisitz   6390: div.LC_grade_message_center_header {
1.705     tempelho 6391:   font-weight: bold;
                   6392:   font-size: large;
1.597     albertel 6393: }
1.795     www      6394: 
1.597     albertel 6395: div.LC_grade_submissions_body,
1.936     bisitz   6396: div.LC_grade_message_center_body {
1.597     albertel 6397:   border: 1px solid black;
                   6398:   width: 99%;
                   6399:   background: #FFFFFF;
                   6400: }
1.795     www      6401: 
1.613     albertel 6402: table.LC_scantron_action {
                   6403:   width: 100%;
                   6404: }
1.795     www      6405: 
1.613     albertel 6406: table.LC_scantron_action tr th {
1.698     harmsja  6407:   font-weight:bold;
                   6408:   font-style:normal;
1.613     albertel 6409: }
1.795     www      6410: 
1.779     bisitz   6411: .LC_edit_problem_header,
1.614     albertel 6412: div.LC_edit_problem_footer {
1.705     tempelho 6413:   font-weight: normal;
                   6414:   font-size:  medium;
1.602     albertel 6415:   margin: 2px;
1.1060    bisitz   6416:   background-color: $sidebg;
1.600     albertel 6417: }
1.795     www      6418: 
1.600     albertel 6419: div.LC_edit_problem_header,
1.602     albertel 6420: div.LC_edit_problem_header div,
1.614     albertel 6421: div.LC_edit_problem_footer,
                   6422: div.LC_edit_problem_footer div,
1.602     albertel 6423: div.LC_edit_problem_editxml_header,
                   6424: div.LC_edit_problem_editxml_header div {
1.600     albertel 6425:   margin-top: 5px;
                   6426: }
1.795     www      6427: 
1.600     albertel 6428: div.LC_edit_problem_header_title {
1.705     tempelho 6429:   font-weight: bold;
                   6430:   font-size: larger;
1.602     albertel 6431:   background: $tabbg;
                   6432:   padding: 3px;
1.1060    bisitz   6433:   margin: 0 0 5px 0;
1.602     albertel 6434: }
1.795     www      6435: 
1.602     albertel 6436: table.LC_edit_problem_header_title {
                   6437:   width: 100%;
1.600     albertel 6438:   background: $tabbg;
1.602     albertel 6439: }
                   6440: 
                   6441: div.LC_edit_problem_discards {
                   6442:   float: left;
                   6443:   padding-bottom: 5px;
                   6444: }
1.795     www      6445: 
1.602     albertel 6446: div.LC_edit_problem_saves {
                   6447:   float: right;
                   6448:   padding-bottom: 5px;
1.600     albertel 6449: }
1.795     www      6450: 
1.911     bisitz   6451: img.stift {
1.803     bisitz   6452:   border-width: 0;
                   6453:   vertical-align: middle;
1.677     riegler  6454: }
1.680     riegler  6455: 
1.923     bisitz   6456: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6457:   vertical-align: top;
1.777     tempelho 6458: }
1.795     www      6459: 
1.716     raeburn  6460: div.LC_createcourse {
1.911     bisitz   6461:   margin: 10px 10px 10px 10px;
1.716     raeburn  6462: }
                   6463: 
1.917     raeburn  6464: .LC_dccid {
                   6465:   margin: 0.2em 0 0 0;
                   6466:   padding: 0;
                   6467:   font-size: 90%;
                   6468:   display:none;
                   6469: }
                   6470: 
1.897     wenzelju 6471: ol.LC_primary_menu a:hover,
1.721     harmsja  6472: ol#LC_MenuBreadcrumbs a:hover,
                   6473: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6474: ul#LC_secondary_menu a:hover,
1.721     harmsja  6475: .LC_FormSectionClearButton input:hover
1.795     www      6476: ul.LC_TabContent   li:hover a {
1.952     onken    6477:   color:$button_hover;
1.911     bisitz   6478:   text-decoration:none;
1.693     droeschl 6479: }
                   6480: 
1.779     bisitz   6481: h1 {
1.911     bisitz   6482:   padding: 0;
                   6483:   line-height:130%;
1.693     droeschl 6484: }
1.698     harmsja  6485: 
1.911     bisitz   6486: h2,
                   6487: h3,
                   6488: h4,
                   6489: h5,
                   6490: h6 {
                   6491:   margin: 5px 0 5px 0;
                   6492:   padding: 0;
                   6493:   line-height:130%;
1.693     droeschl 6494: }
1.795     www      6495: 
                   6496: .LC_hcell {
1.911     bisitz   6497:   padding:3px 15px 3px 15px;
                   6498:   margin: 0;
                   6499:   background-color:$tabbg;
                   6500:   color:$fontmenu;
                   6501:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6502: }
1.795     www      6503: 
1.840     bisitz   6504: .LC_Box > .LC_hcell {
1.911     bisitz   6505:   margin: 0 -10px 10px -10px;
1.835     bisitz   6506: }
                   6507: 
1.721     harmsja  6508: .LC_noBorder {
1.911     bisitz   6509:   border: 0;
1.698     harmsja  6510: }
1.693     droeschl 6511: 
1.721     harmsja  6512: .LC_FormSectionClearButton input {
1.911     bisitz   6513:   background-color:transparent;
                   6514:   border: none;
                   6515:   cursor:pointer;
                   6516:   text-decoration:underline;
1.693     droeschl 6517: }
1.763     bisitz   6518: 
                   6519: .LC_help_open_topic {
1.911     bisitz   6520:   color: #FFFFFF;
                   6521:   background-color: #EEEEFF;
                   6522:   margin: 1px;
                   6523:   padding: 4px;
                   6524:   border: 1px solid #000033;
                   6525:   white-space: nowrap;
                   6526:   /* vertical-align: middle; */
1.759     neumanie 6527: }
1.693     droeschl 6528: 
1.911     bisitz   6529: dl,
                   6530: ul,
                   6531: div,
                   6532: fieldset {
                   6533:   margin: 10px 10px 10px 0;
                   6534:   /* overflow: hidden; */
1.693     droeschl 6535: }
1.795     www      6536: 
1.838     bisitz   6537: fieldset > legend {
1.911     bisitz   6538:   font-weight: bold;
                   6539:   padding: 0 5px 0 5px;
1.838     bisitz   6540: }
                   6541: 
1.813     bisitz   6542: #LC_nav_bar {
1.911     bisitz   6543:   float: left;
1.995     raeburn  6544:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6545:   margin: 0 0 2px 0;
1.807     droeschl 6546: }
                   6547: 
1.916     droeschl 6548: #LC_realm {
                   6549:   margin: 0.2em 0 0 0;
                   6550:   padding: 0;
                   6551:   font-weight: bold;
                   6552:   text-align: center;
1.995     raeburn  6553:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6554: }
                   6555: 
1.911     bisitz   6556: #LC_nav_bar em {
                   6557:   font-weight: bold;
                   6558:   font-style: normal;
1.807     droeschl 6559: }
                   6560: 
1.897     wenzelju 6561: ol.LC_primary_menu {
1.911     bisitz   6562:   float: right;
1.934     droeschl 6563:   margin: 0;
1.1076    raeburn  6564:   padding: 0;
1.995     raeburn  6565:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6566: }
                   6567: 
1.852     droeschl 6568: ol#LC_PathBreadcrumbs {
1.911     bisitz   6569:   margin: 0;
1.693     droeschl 6570: }
                   6571: 
1.897     wenzelju 6572: ol.LC_primary_menu li {
1.1076    raeburn  6573:   color: RGB(80, 80, 80);
                   6574:   vertical-align: middle;
                   6575:   text-align: left;
                   6576:   list-style: none;
                   6577:   float: left;
                   6578: }
                   6579: 
                   6580: ol.LC_primary_menu li a {
                   6581:   display: block;
                   6582:   margin: 0;
                   6583:   padding: 0 5px 0 10px;
                   6584:   text-decoration: none;
                   6585: }
                   6586: 
                   6587: ol.LC_primary_menu li ul {
                   6588:   display: none;
                   6589:   width: 10em;
                   6590:   background-color: $data_table_light;
                   6591: }
                   6592: 
                   6593: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6594:   display: block;
                   6595:   position: absolute;
                   6596:   margin: 0;
                   6597:   padding: 0;
1.1078    raeburn  6598:   z-index: 2;
1.1076    raeburn  6599: }
                   6600: 
                   6601: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6602:   font-size: 90%;
1.911     bisitz   6603:   vertical-align: top;
1.1076    raeburn  6604:   float: none;
1.1079    raeburn  6605:   border-left: 1px solid black;
                   6606:   border-right: 1px solid black;
1.1076    raeburn  6607: }
                   6608: 
                   6609: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1078    raeburn  6610:   background-color:$data_table_light;
1.1076    raeburn  6611: }
                   6612: 
                   6613: ol.LC_primary_menu li li a:hover {
                   6614:    color:$button_hover;
                   6615:    background-color:$data_table_dark;
1.693     droeschl 6616: }
                   6617: 
1.897     wenzelju 6618: ol.LC_primary_menu li img {
1.911     bisitz   6619:   vertical-align: bottom;
1.934     droeschl 6620:   height: 1.1em;
1.1077    raeburn  6621:   margin: 0.2em 0 0 0;
1.693     droeschl 6622: }
                   6623: 
1.897     wenzelju 6624: ol.LC_primary_menu a {
1.911     bisitz   6625:   color: RGB(80, 80, 80);
                   6626:   text-decoration: none;
1.693     droeschl 6627: }
1.795     www      6628: 
1.949     droeschl 6629: ol.LC_primary_menu a.LC_new_message {
                   6630:   font-weight:bold;
                   6631:   color: darkred;
                   6632: }
                   6633: 
1.975     raeburn  6634: ol.LC_docs_parameters {
                   6635:   margin-left: 0;
                   6636:   padding: 0;
                   6637:   list-style: none;
                   6638: }
                   6639: 
                   6640: ol.LC_docs_parameters li {
                   6641:   margin: 0;
                   6642:   padding-right: 20px;
                   6643:   display: inline;
                   6644: }
                   6645: 
1.976     raeburn  6646: ol.LC_docs_parameters li:before {
                   6647:   content: "\\002022 \\0020";
                   6648: }
                   6649: 
                   6650: li.LC_docs_parameters_title {
                   6651:   font-weight: bold;
                   6652: }
                   6653: 
                   6654: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6655:   content: "";
                   6656: }
                   6657: 
1.897     wenzelju 6658: ul#LC_secondary_menu {
1.1107  ! raeburn  6659:   clear: right;
1.911     bisitz   6660:   color: $fontmenu;
                   6661:   background: $tabbg;
                   6662:   list-style: none;
                   6663:   padding: 0;
                   6664:   margin: 0;
                   6665:   width: 100%;
1.995     raeburn  6666:   text-align: left;
1.1107  ! raeburn  6667:   float: left;
1.808     droeschl 6668: }
                   6669: 
1.897     wenzelju 6670: ul#LC_secondary_menu li {
1.911     bisitz   6671:   font-weight: bold;
                   6672:   line-height: 1.8em;
1.1107  ! raeburn  6673:   border-right: 1px solid black;
        !          6674:   float: left;
        !          6675: }
        !          6676: 
        !          6677: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
        !          6678:   background-color: $data_table_light;
        !          6679: }
        !          6680: 
        !          6681: ul#LC_secondary_menu li a {
1.911     bisitz   6682:   padding: 0 0.8em;
1.1107  ! raeburn  6683: }
        !          6684: 
        !          6685: ul#LC_secondary_menu li ul {
        !          6686:   display: none;
        !          6687: }
        !          6688: 
        !          6689: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
        !          6690:   display: block;
        !          6691:   position: absolute;
        !          6692:   margin: 0;
        !          6693:   padding: 0;
        !          6694:   list-style:none;
        !          6695:   float: none;
        !          6696:   background-color: $data_table_light;
        !          6697:   z-index: 2;
        !          6698:   margin-left: -1px;
        !          6699: }
        !          6700: 
        !          6701: ul#LC_secondary_menu li ul li {
        !          6702:   font-size: 90%;
        !          6703:   vertical-align: top;
        !          6704:   border-left: 1px solid black;
1.911     bisitz   6705:   border-right: 1px solid black;
1.1107  ! raeburn  6706:   background-color: $data_table_light
        !          6707:   list-style:none;
        !          6708:   float: none;
        !          6709: }
        !          6710: 
        !          6711: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
        !          6712:   background-color: $data_table_dark;
1.807     droeschl 6713: }
                   6714: 
1.847     tempelho 6715: ul.LC_TabContent {
1.911     bisitz   6716:   display:block;
                   6717:   background: $sidebg;
                   6718:   border-bottom: solid 1px $lg_border_color;
                   6719:   list-style:none;
1.1020    raeburn  6720:   margin: -1px -10px 0 -10px;
1.911     bisitz   6721:   padding: 0;
1.693     droeschl 6722: }
                   6723: 
1.795     www      6724: ul.LC_TabContent li,
                   6725: ul.LC_TabContentBigger li {
1.911     bisitz   6726:   float:left;
1.741     harmsja  6727: }
1.795     www      6728: 
1.897     wenzelju 6729: ul#LC_secondary_menu li a {
1.911     bisitz   6730:   color: $fontmenu;
                   6731:   text-decoration: none;
1.693     droeschl 6732: }
1.795     www      6733: 
1.721     harmsja  6734: ul.LC_TabContent {
1.952     onken    6735:   min-height:20px;
1.721     harmsja  6736: }
1.795     www      6737: 
                   6738: ul.LC_TabContent li {
1.911     bisitz   6739:   vertical-align:middle;
1.959     onken    6740:   padding: 0 16px 0 10px;
1.911     bisitz   6741:   background-color:$tabbg;
                   6742:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6743:   border-left: solid 1px $font;
1.721     harmsja  6744: }
1.795     www      6745: 
1.847     tempelho 6746: ul.LC_TabContent .right {
1.911     bisitz   6747:   float:right;
1.847     tempelho 6748: }
                   6749: 
1.911     bisitz   6750: ul.LC_TabContent li a,
                   6751: ul.LC_TabContent li {
                   6752:   color:rgb(47,47,47);
                   6753:   text-decoration:none;
                   6754:   font-size:95%;
                   6755:   font-weight:bold;
1.952     onken    6756:   min-height:20px;
                   6757: }
                   6758: 
1.959     onken    6759: ul.LC_TabContent li a:hover,
                   6760: ul.LC_TabContent li a:focus {
1.952     onken    6761:   color: $button_hover;
1.959     onken    6762:   background:none;
                   6763:   outline:none;
1.952     onken    6764: }
                   6765: 
                   6766: ul.LC_TabContent li:hover {
                   6767:   color: $button_hover;
                   6768:   cursor:pointer;
1.721     harmsja  6769: }
1.795     www      6770: 
1.911     bisitz   6771: ul.LC_TabContent li.active {
1.952     onken    6772:   color: $font;
1.911     bisitz   6773:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6774:   border-bottom:solid 1px #FFFFFF;
                   6775:   cursor: default;
1.744     ehlerst  6776: }
1.795     www      6777: 
1.959     onken    6778: ul.LC_TabContent li.active a {
                   6779:   color:$font;
                   6780:   background:#FFFFFF;
                   6781:   outline: none;
                   6782: }
1.1047    raeburn  6783: 
                   6784: ul.LC_TabContent li.goback {
                   6785:   float: left;
                   6786:   border-left: none;
                   6787: }
                   6788: 
1.870     tempelho 6789: #maincoursedoc {
1.911     bisitz   6790:   clear:both;
1.870     tempelho 6791: }
                   6792: 
                   6793: ul.LC_TabContentBigger {
1.911     bisitz   6794:   display:block;
                   6795:   list-style:none;
                   6796:   padding: 0;
1.870     tempelho 6797: }
                   6798: 
1.795     www      6799: ul.LC_TabContentBigger li {
1.911     bisitz   6800:   vertical-align:bottom;
                   6801:   height: 30px;
                   6802:   font-size:110%;
                   6803:   font-weight:bold;
                   6804:   color: #737373;
1.841     tempelho 6805: }
                   6806: 
1.957     onken    6807: ul.LC_TabContentBigger li.active {
                   6808:   position: relative;
                   6809:   top: 1px;
                   6810: }
                   6811: 
1.870     tempelho 6812: ul.LC_TabContentBigger li a {
1.911     bisitz   6813:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6814:   height: 30px;
                   6815:   line-height: 30px;
                   6816:   text-align: center;
                   6817:   display: block;
                   6818:   text-decoration: none;
1.958     onken    6819:   outline: none;  
1.741     harmsja  6820: }
1.795     www      6821: 
1.870     tempelho 6822: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6823:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6824:   color:$font;
1.744     ehlerst  6825: }
1.795     www      6826: 
1.870     tempelho 6827: ul.LC_TabContentBigger li b {
1.911     bisitz   6828:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6829:   display: block;
                   6830:   float: left;
                   6831:   padding: 0 30px;
1.957     onken    6832:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6833: }
                   6834: 
1.956     onken    6835: ul.LC_TabContentBigger li:hover b {
                   6836:   color:$button_hover;
                   6837: }
                   6838: 
1.870     tempelho 6839: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6840:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6841:   color:$font;
1.957     onken    6842:   border: 0;
1.741     harmsja  6843: }
1.693     droeschl 6844: 
1.870     tempelho 6845: 
1.862     bisitz   6846: ul.LC_CourseBreadcrumbs {
                   6847:   background: $sidebg;
1.1020    raeburn  6848:   height: 2em;
1.862     bisitz   6849:   padding-left: 10px;
1.1020    raeburn  6850:   margin: 0;
1.862     bisitz   6851:   list-style-position: inside;
                   6852: }
                   6853: 
1.911     bisitz   6854: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6855: ol#LC_PathBreadcrumbs {
1.911     bisitz   6856:   padding-left: 10px;
                   6857:   margin: 0;
1.933     droeschl 6858:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6859: }
                   6860: 
1.911     bisitz   6861: ol#LC_MenuBreadcrumbs li,
                   6862: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6863: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6864:   display: inline;
1.933     droeschl 6865:   white-space: normal;  
1.693     droeschl 6866: }
                   6867: 
1.823     bisitz   6868: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6869: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6870:   text-decoration: none;
                   6871:   font-size:90%;
1.693     droeschl 6872: }
1.795     www      6873: 
1.969     droeschl 6874: ol#LC_MenuBreadcrumbs h1 {
                   6875:   display: inline;
                   6876:   font-size: 90%;
                   6877:   line-height: 2.5em;
                   6878:   margin: 0;
                   6879:   padding: 0;
                   6880: }
                   6881: 
1.795     www      6882: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6883:   text-decoration:none;
                   6884:   font-size:100%;
                   6885:   font-weight:bold;
1.693     droeschl 6886: }
1.795     www      6887: 
1.840     bisitz   6888: .LC_Box {
1.911     bisitz   6889:   border: solid 1px $lg_border_color;
                   6890:   padding: 0 10px 10px 10px;
1.746     neumanie 6891: }
1.795     www      6892: 
1.1020    raeburn  6893: .LC_DocsBox {
                   6894:   border: solid 1px $lg_border_color;
                   6895:   padding: 0 0 10px 10px;
                   6896: }
                   6897: 
1.795     www      6898: .LC_AboutMe_Image {
1.911     bisitz   6899:   float:left;
                   6900:   margin-right:10px;
1.747     neumanie 6901: }
1.795     www      6902: 
                   6903: .LC_Clear_AboutMe_Image {
1.911     bisitz   6904:   clear:left;
1.747     neumanie 6905: }
1.795     www      6906: 
1.721     harmsja  6907: dl.LC_ListStyleClean dt {
1.911     bisitz   6908:   padding-right: 5px;
                   6909:   display: table-header-group;
1.693     droeschl 6910: }
                   6911: 
1.721     harmsja  6912: dl.LC_ListStyleClean dd {
1.911     bisitz   6913:   display: table-row;
1.693     droeschl 6914: }
                   6915: 
1.721     harmsja  6916: .LC_ListStyleClean,
                   6917: .LC_ListStyleSimple,
                   6918: .LC_ListStyleNormal,
1.795     www      6919: .LC_ListStyleSpecial {
1.911     bisitz   6920:   /* display:block; */
                   6921:   list-style-position: inside;
                   6922:   list-style-type: none;
                   6923:   overflow: hidden;
                   6924:   padding: 0;
1.693     droeschl 6925: }
                   6926: 
1.721     harmsja  6927: .LC_ListStyleSimple li,
                   6928: .LC_ListStyleSimple dd,
                   6929: .LC_ListStyleNormal li,
                   6930: .LC_ListStyleNormal dd,
                   6931: .LC_ListStyleSpecial li,
1.795     www      6932: .LC_ListStyleSpecial dd {
1.911     bisitz   6933:   margin: 0;
                   6934:   padding: 5px 5px 5px 10px;
                   6935:   clear: both;
1.693     droeschl 6936: }
                   6937: 
1.721     harmsja  6938: .LC_ListStyleClean li,
                   6939: .LC_ListStyleClean dd {
1.911     bisitz   6940:   padding-top: 0;
                   6941:   padding-bottom: 0;
1.693     droeschl 6942: }
                   6943: 
1.721     harmsja  6944: .LC_ListStyleSimple dd,
1.795     www      6945: .LC_ListStyleSimple li {
1.911     bisitz   6946:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6947: }
                   6948: 
1.721     harmsja  6949: .LC_ListStyleSpecial li,
                   6950: .LC_ListStyleSpecial dd {
1.911     bisitz   6951:   list-style-type: none;
                   6952:   background-color: RGB(220, 220, 220);
                   6953:   margin-bottom: 4px;
1.693     droeschl 6954: }
                   6955: 
1.721     harmsja  6956: table.LC_SimpleTable {
1.911     bisitz   6957:   margin:5px;
                   6958:   border:solid 1px $lg_border_color;
1.795     www      6959: }
1.693     droeschl 6960: 
1.721     harmsja  6961: table.LC_SimpleTable tr {
1.911     bisitz   6962:   padding: 0;
                   6963:   border:solid 1px $lg_border_color;
1.693     droeschl 6964: }
1.795     www      6965: 
                   6966: table.LC_SimpleTable thead {
1.911     bisitz   6967:   background:rgb(220,220,220);
1.693     droeschl 6968: }
                   6969: 
1.721     harmsja  6970: div.LC_columnSection {
1.911     bisitz   6971:   display: block;
                   6972:   clear: both;
                   6973:   overflow: hidden;
                   6974:   margin: 0;
1.693     droeschl 6975: }
                   6976: 
1.721     harmsja  6977: div.LC_columnSection>* {
1.911     bisitz   6978:   float: left;
                   6979:   margin: 10px 20px 10px 0;
                   6980:   overflow:hidden;
1.693     droeschl 6981: }
1.721     harmsja  6982: 
1.795     www      6983: table em {
1.911     bisitz   6984:   font-weight: bold;
                   6985:   font-style: normal;
1.748     schulted 6986: }
1.795     www      6987: 
1.779     bisitz   6988: table.LC_tableBrowseRes,
1.795     www      6989: table.LC_tableOfContent {
1.911     bisitz   6990:   border:none;
                   6991:   border-spacing: 1px;
                   6992:   padding: 3px;
                   6993:   background-color: #FFFFFF;
                   6994:   font-size: 90%;
1.753     droeschl 6995: }
1.789     droeschl 6996: 
1.911     bisitz   6997: table.LC_tableOfContent {
                   6998:   border-collapse: collapse;
1.789     droeschl 6999: }
                   7000: 
1.771     droeschl 7001: table.LC_tableBrowseRes a,
1.768     schulted 7002: table.LC_tableOfContent a {
1.911     bisitz   7003:   background-color: transparent;
                   7004:   text-decoration: none;
1.753     droeschl 7005: }
                   7006: 
1.795     www      7007: table.LC_tableOfContent img {
1.911     bisitz   7008:   border: none;
                   7009:   height: 1.3em;
                   7010:   vertical-align: text-bottom;
                   7011:   margin-right: 0.3em;
1.753     droeschl 7012: }
1.757     schulted 7013: 
1.795     www      7014: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7015:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7016: }
                   7017: 
1.795     www      7018: a#LC_content_toolbar_everything {
1.911     bisitz   7019:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7020: }
                   7021: 
1.795     www      7022: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7023:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7024: }
                   7025: 
1.795     www      7026: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7027:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7028: }
                   7029: 
1.795     www      7030: a#LC_content_toolbar_changefolder {
1.911     bisitz   7031:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7032: }
                   7033: 
1.795     www      7034: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7035:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7036: }
                   7037: 
1.1043    raeburn  7038: a#LC_content_toolbar_edittoplevel {
                   7039:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7040: }
                   7041: 
1.795     www      7042: ul#LC_toolbar li a:hover {
1.911     bisitz   7043:   background-position: bottom center;
1.757     schulted 7044: }
                   7045: 
1.795     www      7046: ul#LC_toolbar {
1.911     bisitz   7047:   padding: 0;
                   7048:   margin: 2px;
                   7049:   list-style:none;
                   7050:   position:relative;
                   7051:   background-color:white;
1.1082    raeburn  7052:   overflow: auto;
1.757     schulted 7053: }
                   7054: 
1.795     www      7055: ul#LC_toolbar li {
1.911     bisitz   7056:   border:1px solid white;
                   7057:   padding: 0;
                   7058:   margin: 0;
                   7059:   float: left;
                   7060:   display:inline;
                   7061:   vertical-align:middle;
1.1082    raeburn  7062:   white-space: nowrap;
1.911     bisitz   7063: }
1.757     schulted 7064: 
1.783     amueller 7065: 
1.795     www      7066: a.LC_toolbarItem {
1.911     bisitz   7067:   display:block;
                   7068:   padding: 0;
                   7069:   margin: 0;
                   7070:   height: 32px;
                   7071:   width: 32px;
                   7072:   color:white;
                   7073:   border: none;
                   7074:   background-repeat:no-repeat;
                   7075:   background-color:transparent;
1.757     schulted 7076: }
                   7077: 
1.915     droeschl 7078: ul.LC_funclist {
                   7079:     margin: 0;
                   7080:     padding: 0.5em 1em 0.5em 0;
                   7081: }
                   7082: 
1.933     droeschl 7083: ul.LC_funclist > li:first-child {
                   7084:     font-weight:bold; 
                   7085:     margin-left:0.8em;
                   7086: }
                   7087: 
1.915     droeschl 7088: ul.LC_funclist + ul.LC_funclist {
                   7089:     /* 
                   7090:        left border as a seperator if we have more than
                   7091:        one list 
                   7092:     */
                   7093:     border-left: 1px solid $sidebg;
                   7094:     /* 
                   7095:        this hides the left border behind the border of the 
                   7096:        outer box if element is wrapped to the next 'line' 
                   7097:     */
                   7098:     margin-left: -1px;
                   7099: }
                   7100: 
1.843     bisitz   7101: ul.LC_funclist li {
1.915     droeschl 7102:   display: inline;
1.782     bisitz   7103:   white-space: nowrap;
1.915     droeschl 7104:   margin: 0 0 0 25px;
                   7105:   line-height: 150%;
1.782     bisitz   7106: }
                   7107: 
1.974     wenzelju 7108: .LC_hidden {
                   7109:   display: none;
                   7110: }
                   7111: 
1.1030    www      7112: .LCmodal-overlay {
                   7113: 		position:fixed;
                   7114: 		top:0;
                   7115: 		right:0;
                   7116: 		bottom:0;
                   7117: 		left:0;
                   7118: 		height:100%;
                   7119: 		width:100%;
                   7120: 		margin:0;
                   7121: 		padding:0;
                   7122: 		background:#999;
                   7123: 		opacity:.75;
                   7124: 		filter: alpha(opacity=75);
                   7125: 		-moz-opacity: 0.75;
                   7126: 		z-index:101;
                   7127: }
                   7128: 
                   7129: * html .LCmodal-overlay {   
                   7130: 		position: absolute;
                   7131: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7132: }
                   7133: 
                   7134: .LCmodal-window {
                   7135: 		position:fixed;
                   7136: 		top:50%;
                   7137: 		left:50%;
                   7138: 		margin:0;
                   7139: 		padding:0;
                   7140: 		z-index:102;
                   7141: 	}
                   7142: 
                   7143: * html .LCmodal-window {
                   7144: 		position:absolute;
                   7145: }
                   7146: 
                   7147: .LCclose-window {
                   7148: 		position:absolute;
                   7149: 		width:32px;
                   7150: 		height:32px;
                   7151: 		right:8px;
                   7152: 		top:8px;
                   7153: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7154: 		text-indent:-99999px;
                   7155: 		overflow:hidden;
                   7156: 		cursor:pointer;
                   7157: }
                   7158: 
1.1100    raeburn  7159: /*
                   7160:   styles used by TTH when "Default set of options to pass to tth/m
                   7161:   when converting TeX" in course settings has been set
                   7162: 
                   7163:   option passed: -t
                   7164: 
                   7165: */
                   7166: 
                   7167: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7168: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7169: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7170: td div.norm {line-height:normal;}
                   7171: 
                   7172: /*
                   7173:   option passed -y3
                   7174: */
                   7175: 
                   7176: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7177: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7178: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7179: 
1.343     albertel 7180: END
                   7181: }
                   7182: 
1.306     albertel 7183: =pod
                   7184: 
                   7185: =item * &headtag()
                   7186: 
                   7187: Returns a uniform footer for LON-CAPA web pages.
                   7188: 
1.307     albertel 7189: Inputs: $title - optional title for the head
                   7190:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7191:         $args - optional arguments
1.319     albertel 7192:             force_register - if is true call registerurl so the remote is 
                   7193:                              informed
1.415     albertel 7194:             redirect       -> array ref of
                   7195:                                    1- seconds before redirect occurs
                   7196:                                    2- url to redirect to
                   7197:                                    3- whether the side effect should occur
1.315     albertel 7198:                            (side effect of setting 
                   7199:                                $env{'internal.head.redirect'} to the url 
                   7200:                                redirected too)
1.352     albertel 7201:             domain         -> force to color decorate a page for a specific
                   7202:                                domain
                   7203:             function       -> force usage of a specific rolish color scheme
                   7204:             bgcolor        -> override the default page bgcolor
1.460     albertel 7205:             no_auto_mt_title
                   7206:                            -> prevent &mt()ing the title arg
1.464     albertel 7207: 
1.306     albertel 7208: =cut
                   7209: 
                   7210: sub headtag {
1.313     albertel 7211:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7212:     
1.363     albertel 7213:     my $function = $args->{'function'} || &get_users_function();
                   7214:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7215:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 7216:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7217: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7218: 		   #time(),
1.418     albertel 7219: 		   $env{'environment.color.timestamp'},
1.363     albertel 7220: 		   $function,$domain,$bgcolor);
                   7221: 
1.369     www      7222:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7223: 
1.308     albertel 7224:     my $result =
                   7225: 	'<head>'.
1.461     albertel 7226: 	&font_settings();
1.319     albertel 7227: 
1.1064    raeburn  7228:     my $inhibitprint = &print_suppression();
                   7229: 
1.461     albertel 7230:     if (!$args->{'frameset'}) {
                   7231: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7232:     }
1.962     droeschl 7233:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7234:         $result .= Apache::lonxml::display_title();
1.319     albertel 7235:     }
1.436     albertel 7236:     if (!$args->{'no_nav_bar'} 
                   7237: 	&& !$args->{'only_body'}
                   7238: 	&& !$args->{'frameset'}) {
                   7239: 	$result .= &help_menu_js();
1.1032    www      7240:         $result.=&modal_window();
1.1038    www      7241:         $result.=&togglebox_script();
1.1034    www      7242:         $result.=&wishlist_window();
1.1041    www      7243:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7244:     } else {
                   7245:         if ($args->{'add_modal'}) {
                   7246:            $result.=&modal_window();
                   7247:         }
                   7248:         if ($args->{'add_wishlist'}) {
                   7249:            $result.=&wishlist_window();
                   7250:         }
1.1038    www      7251:         if ($args->{'add_togglebox'}) {
                   7252:            $result.=&togglebox_script();
                   7253:         }
1.1041    www      7254:         if ($args->{'add_progressbar'}) {
                   7255:            $result.=&LCprogressbarUpdate_script();
                   7256:         }
1.436     albertel 7257:     }
1.314     albertel 7258:     if (ref($args->{'redirect'})) {
1.414     albertel 7259: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7260: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7261: 	if (!$inhibit_continue) {
                   7262: 	    $env{'internal.head.redirect'} = $url;
                   7263: 	}
1.313     albertel 7264: 	$result.=<<ADDMETA
                   7265: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7266: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7267: ADDMETA
                   7268:     }
1.306     albertel 7269:     if (!defined($title)) {
                   7270: 	$title = 'The LearningOnline Network with CAPA';
                   7271:     }
1.460     albertel 7272:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7273:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7274: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7275:         .$inhibitprint
1.414     albertel 7276: 	.$head_extra;
1.962     droeschl 7277:     return $result.'</head>';
1.306     albertel 7278: }
                   7279: 
                   7280: =pod
                   7281: 
1.340     albertel 7282: =item * &font_settings()
                   7283: 
                   7284: Returns neccessary <meta> to set the proper encoding
                   7285: 
                   7286: Inputs: none
                   7287: 
                   7288: =cut
                   7289: 
                   7290: sub font_settings {
                   7291:     my $headerstring='';
1.647     www      7292:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 7293: 	$headerstring.=
                   7294: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   7295:     }
                   7296:     return $headerstring;
                   7297: }
                   7298: 
1.341     albertel 7299: =pod
                   7300: 
1.1064    raeburn  7301: =item * &print_suppression()
                   7302: 
                   7303: In course context returns css which causes the body to be blank when media="print",
                   7304: if printout generation is unavailable for the current resource.
                   7305: 
                   7306: This could be because:
                   7307: 
                   7308: (a) printstartdate is in the future
                   7309: 
                   7310: (b) printenddate is in the past
                   7311: 
                   7312: (c) there is an active exam block with "printout"
                   7313: functionality blocked
                   7314: 
                   7315: Users with pav, pfo or evb privileges are exempt.
                   7316: 
                   7317: Inputs: none
                   7318: 
                   7319: =cut
                   7320: 
                   7321: 
                   7322: sub print_suppression {
                   7323:     my $noprint;
                   7324:     if ($env{'request.course.id'}) {
                   7325:         my $scope = $env{'request.course.id'};
                   7326:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7327:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7328:             return;
                   7329:         }
                   7330:         if ($env{'request.course.sec'} ne '') {
                   7331:             $scope .= "/$env{'request.course.sec'}";
                   7332:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7333:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7334:                 return;
1.1064    raeburn  7335:             }
                   7336:         }
                   7337:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7338:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7339:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7340:         if ($blocked) {
                   7341:             my $checkrole = "cm./$cdom/$cnum";
                   7342:             if ($env{'request.course.sec'} ne '') {
                   7343:                 $checkrole .= "/$env{'request.course.sec'}";
                   7344:             }
                   7345:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7346:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7347:                 $noprint = 1;
                   7348:             }
                   7349:         }
                   7350:         unless ($noprint) {
                   7351:             my $symb = &Apache::lonnet::symbread();
                   7352:             if ($symb ne '') {
                   7353:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7354:                 if (ref($navmap)) {
                   7355:                     my $res = $navmap->getBySymb($symb);
                   7356:                     if (ref($res)) {
                   7357:                         if (!$res->resprintable()) {
                   7358:                             $noprint = 1;
                   7359:                         }
                   7360:                     }
                   7361:                 }
                   7362:             }
                   7363:         }
                   7364:         if ($noprint) {
                   7365:             return <<"ENDSTYLE";
                   7366: <style type="text/css" media="print">
                   7367:     body { display:none }
                   7368: </style>
                   7369: ENDSTYLE
                   7370:         }
                   7371:     }
                   7372:     return;
                   7373: }
                   7374: 
                   7375: =pod
                   7376: 
1.341     albertel 7377: =item * &xml_begin()
                   7378: 
                   7379: Returns the needed doctype and <html>
                   7380: 
                   7381: Inputs: none
                   7382: 
                   7383: =cut
                   7384: 
                   7385: sub xml_begin {
                   7386:     my $output='';
                   7387: 
                   7388:     if ($env{'browser.mathml'}) {
                   7389: 	$output='<?xml version="1.0"?>'
                   7390:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7391: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7392:             
                   7393: #	    .'<!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">] >'
                   7394: 	    .'<!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">'
                   7395:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7396: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7397:     } else {
1.849     bisitz   7398: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                   7399:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 7400:     }
                   7401:     return $output;
                   7402: }
1.340     albertel 7403: 
                   7404: =pod
                   7405: 
1.306     albertel 7406: =item * &start_page()
                   7407: 
                   7408: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7409: 
1.648     raeburn  7410: Inputs:
                   7411: 
                   7412: =over 4
                   7413: 
                   7414: $title - optional title for the page
                   7415: 
                   7416: $head_extra - optional extra HTML to incude inside the <head>
                   7417: 
                   7418: $args - additional optional args supported are:
                   7419: 
                   7420: =over 8
                   7421: 
                   7422:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7423:                                     arg on
1.814     bisitz   7424:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7425:              add_entries    -> additional attributes to add to the  <body>
                   7426:              domain         -> force to color decorate a page for a 
1.317     albertel 7427:                                     specific domain
1.648     raeburn  7428:              function       -> force usage of a specific rolish color
1.317     albertel 7429:                                     scheme
1.648     raeburn  7430:              redirect       -> see &headtag()
                   7431:              bgcolor        -> override the default page bg color
                   7432:              js_ready       -> return a string ready for being used in 
1.317     albertel 7433:                                     a javascript writeln
1.648     raeburn  7434:              html_encode    -> return a string ready for being used in 
1.320     albertel 7435:                                     a html attribute
1.648     raeburn  7436:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7437:                                     $forcereg arg
1.648     raeburn  7438:              frameset       -> if true will start with a <frameset>
1.330     albertel 7439:                                     rather than <body>
1.648     raeburn  7440:              skip_phases    -> hash ref of 
1.338     albertel 7441:                                     head -> skip the <html><head> generation
                   7442:                                     body -> skip all <body> generation
1.648     raeburn  7443:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7444:              inherit_jsmath -> when creating popup window in a page,
                   7445:                                     should it have jsmath forced on by the
                   7446:                                     current page
1.867     kalberla 7447:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7448:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7449:              group          -> includes the current group, if page is for a 
                   7450:                                specific group  
1.361     albertel 7451: 
1.648     raeburn  7452: =back
1.460     albertel 7453: 
1.648     raeburn  7454: =back
1.562     albertel 7455: 
1.306     albertel 7456: =cut
                   7457: 
                   7458: sub start_page {
1.309     albertel 7459:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7460:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7461: 
1.315     albertel 7462:     $env{'internal.start_page'}++;
1.1096    raeburn  7463:     my ($result,@advtools);
1.964     droeschl 7464: 
1.338     albertel 7465:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7466:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7467:     }
                   7468:     
                   7469:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7470: 	if ($args->{'frameset'}) {
                   7471: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7472: 						$args->{'add_entries'});
                   7473: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7474:         } else {
                   7475:             $result .=
                   7476:                 &bodytag($title, 
                   7477:                          $args->{'function'},       $args->{'add_entries'},
                   7478:                          $args->{'only_body'},      $args->{'domain'},
                   7479:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  7480:                          $args->{'bgcolor'},        $args,
                   7481:                          \@advtools);
1.831     bisitz   7482:         }
1.330     albertel 7483:     }
1.338     albertel 7484: 
1.315     albertel 7485:     if ($args->{'js_ready'}) {
1.713     kaisler  7486: 		$result = &js_ready($result);
1.315     albertel 7487:     }
1.320     albertel 7488:     if ($args->{'html_encode'}) {
1.713     kaisler  7489: 		$result = &html_encode($result);
                   7490:     }
                   7491: 
1.813     bisitz   7492:     # Preparation for new and consistent functionlist at top of screen
                   7493:     # if ($args->{'functionlist'}) {
                   7494:     #            $result .= &build_functionlist();
                   7495:     #}
                   7496: 
1.964     droeschl 7497:     # Don't add anything more if only_body wanted or in const space
                   7498:     return $result if    $args->{'only_body'} 
                   7499:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7500: 
                   7501:     #Breadcrumbs
1.758     kaisler  7502:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7503: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7504: 		#if any br links exists, add them to the breadcrumbs
                   7505: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7506: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7507: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7508: 			}
                   7509: 		}
1.1096    raeburn  7510:                 # if @advtools array contains items add then to the breadcrumbs
                   7511:                 if (@advtools > 0) {
                   7512:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7513:                 }
1.758     kaisler  7514: 
                   7515: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7516: 		if(exists($args->{'bread_crumbs_component'})){
                   7517: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7518: 		}else{
                   7519: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7520: 		}
1.320     albertel 7521:     }
1.315     albertel 7522:     return $result;
1.306     albertel 7523: }
                   7524: 
                   7525: sub end_page {
1.315     albertel 7526:     my ($args) = @_;
                   7527:     $env{'internal.end_page'}++;
1.330     albertel 7528:     my $result;
1.335     albertel 7529:     if ($args->{'discussion'}) {
                   7530: 	my ($target,$parser);
                   7531: 	if (ref($args->{'discussion'})) {
                   7532: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7533: 				$args->{'discussion'}{'parser'});
                   7534: 	}
                   7535: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7536:     }
1.330     albertel 7537:     if ($args->{'frameset'}) {
                   7538: 	$result .= '</frameset>';
                   7539:     } else {
1.635     raeburn  7540: 	$result .= &endbodytag($args);
1.330     albertel 7541:     }
1.1080    raeburn  7542:     unless ($args->{'notbody'}) {
                   7543:         $result .= "\n</html>";
                   7544:     }
1.330     albertel 7545: 
1.315     albertel 7546:     if ($args->{'js_ready'}) {
1.317     albertel 7547: 	$result = &js_ready($result);
1.315     albertel 7548:     }
1.335     albertel 7549: 
1.320     albertel 7550:     if ($args->{'html_encode'}) {
                   7551: 	$result = &html_encode($result);
                   7552:     }
1.335     albertel 7553: 
1.315     albertel 7554:     return $result;
                   7555: }
                   7556: 
1.1034    www      7557: sub wishlist_window {
                   7558:     return(<<'ENDWISHLIST');
1.1046    raeburn  7559: <script type="text/javascript">
1.1034    www      7560: // <![CDATA[
                   7561: // <!-- BEGIN LON-CAPA Internal
                   7562: function set_wishlistlink(title, path) {
                   7563:     if (!title) {
                   7564:         title = document.title;
                   7565:         title = title.replace(/^LON-CAPA /,'');
                   7566:     }
                   7567:     if (!path) {
                   7568:         path = location.pathname;
                   7569:     }
                   7570:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7571:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7572: }
                   7573: // END LON-CAPA Internal -->
                   7574: // ]]>
                   7575: </script>
                   7576: ENDWISHLIST
                   7577: }
                   7578: 
1.1030    www      7579: sub modal_window {
                   7580:     return(<<'ENDMODAL');
1.1046    raeburn  7581: <script type="text/javascript">
1.1030    www      7582: // <![CDATA[
                   7583: // <!-- BEGIN LON-CAPA Internal
                   7584: var modalWindow = {
                   7585: 	parent:"body",
                   7586: 	windowId:null,
                   7587: 	content:null,
                   7588: 	width:null,
                   7589: 	height:null,
                   7590: 	close:function()
                   7591: 	{
                   7592: 	        $(".LCmodal-window").remove();
                   7593: 	        $(".LCmodal-overlay").remove();
                   7594: 	},
                   7595: 	open:function()
                   7596: 	{
                   7597: 		var modal = "";
                   7598: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7599: 		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;\">";
                   7600: 		modal += this.content;
                   7601: 		modal += "</div>";	
                   7602: 
                   7603: 		$(this.parent).append(modal);
                   7604: 
                   7605: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7606: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7607: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7608: 	}
                   7609: };
1.1031    www      7610: 	var openMyModal = function(source,width,height,scrolling)
1.1030    www      7611: 	{
                   7612: 		modalWindow.windowId = "myModal";
                   7613: 		modalWindow.width = width;
                   7614: 		modalWindow.height = height;
1.1031    www      7615: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
1.1030    www      7616: 		modalWindow.open();
                   7617: 	};	
                   7618: // END LON-CAPA Internal -->
                   7619: // ]]>
                   7620: </script>
                   7621: ENDMODAL
                   7622: }
                   7623: 
                   7624: sub modal_link {
1.1052    www      7625:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
1.1030    www      7626:     unless ($width) { $width=480; }
                   7627:     unless ($height) { $height=400; }
1.1031    www      7628:     unless ($scrolling) { $scrolling='yes'; }
1.1074    raeburn  7629:     my $target_attr;
                   7630:     if (defined($target)) {
                   7631:         $target_attr = 'target="'.$target.'"';
                   7632:     }
                   7633:     return <<"ENDLINK";
                   7634: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
                   7635:            $linktext</a>
                   7636: ENDLINK
1.1030    www      7637: }
                   7638: 
1.1032    www      7639: sub modal_adhoc_script {
                   7640:     my ($funcname,$width,$height,$content)=@_;
                   7641:     return (<<ENDADHOC);
1.1046    raeburn  7642: <script type="text/javascript">
1.1032    www      7643: // <![CDATA[
                   7644:         var $funcname = function()
                   7645:         {
                   7646:                 modalWindow.windowId = "myModal";
                   7647:                 modalWindow.width = $width;
                   7648:                 modalWindow.height = $height;
                   7649:                 modalWindow.content = '$content';
                   7650:                 modalWindow.open();
                   7651:         };  
                   7652: // ]]>
                   7653: </script>
                   7654: ENDADHOC
                   7655: }
                   7656: 
1.1041    www      7657: sub modal_adhoc_inner {
                   7658:     my ($funcname,$width,$height,$content)=@_;
                   7659:     my $innerwidth=$width-20;
                   7660:     $content=&js_ready(
1.1042    www      7661:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1041    www      7662:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
                   7663:                     $content.
                   7664:                  &end_scrollbox().
                   7665:                &end_page()
                   7666:              );
                   7667:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7668: }
                   7669: 
                   7670: sub modal_adhoc_window {
                   7671:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7672:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7673:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7674: }
                   7675: 
                   7676: sub modal_adhoc_launch {
                   7677:     my ($funcname,$width,$height,$content)=@_;
                   7678:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7679: <script type="text/javascript">
                   7680: // <![CDATA[
                   7681: $funcname();
                   7682: // ]]>
                   7683: </script>
                   7684: ENDLAUNCH
                   7685: }
                   7686: 
                   7687: sub modal_adhoc_close {
                   7688:     return (<<ENDCLOSE);
                   7689: <script type="text/javascript">
                   7690: // <![CDATA[
                   7691: modalWindow.close();
                   7692: // ]]>
                   7693: </script>
                   7694: ENDCLOSE
                   7695: }
                   7696: 
1.1038    www      7697: sub togglebox_script {
                   7698:    return(<<ENDTOGGLE);
                   7699: <script type="text/javascript"> 
                   7700: // <![CDATA[
                   7701: function LCtoggleDisplay(id,hidetext,showtext) {
                   7702:    link = document.getElementById(id + "link").childNodes[0];
                   7703:    with (document.getElementById(id).style) {
                   7704:       if (display == "none" ) {
                   7705:           display = "inline";
                   7706:           link.nodeValue = hidetext;
                   7707:         } else {
                   7708:           display = "none";
                   7709:           link.nodeValue = showtext;
                   7710:        }
                   7711:    }
                   7712: }
                   7713: // ]]>
                   7714: </script>
                   7715: ENDTOGGLE
                   7716: }
                   7717: 
1.1039    www      7718: sub start_togglebox {
                   7719:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7720:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7721:     unless ($showtext) { $showtext=&mt('show'); }
                   7722:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7723:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7724:     return &start_data_table().
                   7725:            &start_data_table_header_row().
                   7726:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7727:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7728:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7729:            &end_data_table_header_row().
                   7730:            '<tr id="'.$id.'" style="display:none""><td>';
                   7731: }
                   7732: 
                   7733: sub end_togglebox {
                   7734:     return '</td></tr>'.&end_data_table();
                   7735: }
                   7736: 
1.1041    www      7737: sub LCprogressbar_script {
1.1045    www      7738:    my ($id)=@_;
1.1041    www      7739:    return(<<ENDPROGRESS);
                   7740: <script type="text/javascript">
                   7741: // <![CDATA[
1.1045    www      7742: \$('#progressbar$id').progressbar({
1.1041    www      7743:   value: 0,
                   7744:   change: function(event, ui) {
                   7745:     var newVal = \$(this).progressbar('option', 'value');
                   7746:     \$('.pblabel', this).text(LCprogressTxt);
                   7747:   }
                   7748: });
                   7749: // ]]>
                   7750: </script>
                   7751: ENDPROGRESS
                   7752: }
                   7753: 
                   7754: sub LCprogressbarUpdate_script {
                   7755:    return(<<ENDPROGRESSUPDATE);
                   7756: <style type="text/css">
                   7757: .ui-progressbar { position:relative; }
                   7758: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7759: </style>
                   7760: <script type="text/javascript">
                   7761: // <![CDATA[
1.1045    www      7762: var LCprogressTxt='---';
                   7763: 
                   7764: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7765:    LCprogressTxt=progresstext;
1.1045    www      7766:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7767: }
                   7768: // ]]>
                   7769: </script>
                   7770: ENDPROGRESSUPDATE
                   7771: }
                   7772: 
1.1042    www      7773: my $LClastpercent;
1.1045    www      7774: my $LCidcnt;
                   7775: my $LCcurrentid;
1.1042    www      7776: 
1.1041    www      7777: sub LCprogressbar {
1.1042    www      7778:     my ($r)=(@_);
                   7779:     $LClastpercent=0;
1.1045    www      7780:     $LCidcnt++;
                   7781:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7782:     my $starting=&mt('Starting');
                   7783:     my $content=(<<ENDPROGBAR);
                   7784: <p>
1.1045    www      7785:   <div id="progressbar$LCcurrentid">
1.1041    www      7786:     <span class="pblabel">$starting</span>
                   7787:   </div>
                   7788: </p>
                   7789: ENDPROGBAR
1.1045    www      7790:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7791: }
                   7792: 
                   7793: sub LCprogressbarUpdate {
1.1042    www      7794:     my ($r,$val,$text)=@_;
                   7795:     unless ($val) { 
                   7796:        if ($LClastpercent) {
                   7797:            $val=$LClastpercent;
                   7798:        } else {
                   7799:            $val=0;
                   7800:        }
                   7801:     }
1.1041    www      7802:     if ($val<0) { $val=0; }
                   7803:     if ($val>100) { $val=0; }
1.1042    www      7804:     $LClastpercent=$val;
1.1041    www      7805:     unless ($text) { $text=$val.'%'; }
                   7806:     $text=&js_ready($text);
1.1044    www      7807:     &r_print($r,<<ENDUPDATE);
1.1041    www      7808: <script type="text/javascript">
                   7809: // <![CDATA[
1.1045    www      7810: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7811: // ]]>
                   7812: </script>
                   7813: ENDUPDATE
1.1035    www      7814: }
                   7815: 
1.1042    www      7816: sub LCprogressbarClose {
                   7817:     my ($r)=@_;
                   7818:     $LClastpercent=0;
1.1044    www      7819:     &r_print($r,<<ENDCLOSE);
1.1042    www      7820: <script type="text/javascript">
                   7821: // <![CDATA[
1.1045    www      7822: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7823: // ]]>
                   7824: </script>
                   7825: ENDCLOSE
1.1044    www      7826: }
                   7827: 
                   7828: sub r_print {
                   7829:     my ($r,$to_print)=@_;
                   7830:     if ($r) {
                   7831:       $r->print($to_print);
                   7832:       $r->rflush();
                   7833:     } else {
                   7834:       print($to_print);
                   7835:     }
1.1042    www      7836: }
                   7837: 
1.320     albertel 7838: sub html_encode {
                   7839:     my ($result) = @_;
                   7840: 
1.322     albertel 7841:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7842:     
                   7843:     return $result;
                   7844: }
1.1044    www      7845: 
1.317     albertel 7846: sub js_ready {
                   7847:     my ($result) = @_;
                   7848: 
1.323     albertel 7849:     $result =~ s/[\n\r]/ /xmsg;
                   7850:     $result =~ s/\\/\\\\/xmsg;
                   7851:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7852:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7853:     
                   7854:     return $result;
                   7855: }
                   7856: 
1.315     albertel 7857: sub validate_page {
                   7858:     if (  exists($env{'internal.start_page'})
1.316     albertel 7859: 	  &&     $env{'internal.start_page'} > 1) {
                   7860: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7861: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7862: 				 $ENV{'request.filename'});
1.315     albertel 7863:     }
                   7864:     if (  exists($env{'internal.end_page'})
1.316     albertel 7865: 	  &&     $env{'internal.end_page'} > 1) {
                   7866: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7867: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7868: 				 $env{'request.filename'});
1.315     albertel 7869:     }
                   7870:     if (     exists($env{'internal.start_page'})
                   7871: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7872: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7873: 				 $env{'request.filename'});
1.315     albertel 7874:     }
                   7875:     if (   ! exists($env{'internal.start_page'})
                   7876: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7877: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7878: 				 $env{'request.filename'});
1.315     albertel 7879:     }
1.306     albertel 7880: }
1.315     albertel 7881: 
1.996     www      7882: 
                   7883: sub start_scrollbox {
1.1075    raeburn  7884:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
1.998     raeburn  7885:     unless ($outerwidth) { $outerwidth='520px'; }
                   7886:     unless ($width) { $width='500px'; }
                   7887:     unless ($height) { $height='200px'; }
1.1075    raeburn  7888:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7889:     if ($id ne '') {
1.1020    raeburn  7890:         $table_id = " id='table_$id'";
                   7891:         $div_id = " id='div_$id'";
1.1018    raeburn  7892:     }
1.1075    raeburn  7893:     if ($bgcolor ne '') {
                   7894:         $tdcol = "background-color: $bgcolor;";
                   7895:     }
                   7896:     return <<"END";
                   7897: <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>
                   7898: END
1.996     www      7899: }
                   7900: 
                   7901: sub end_scrollbox {
1.1036    www      7902:     return '</div></td></tr></table>';
1.996     www      7903: }
                   7904: 
1.318     albertel 7905: sub simple_error_page {
                   7906:     my ($r,$title,$msg) = @_;
                   7907:     my $page =
                   7908: 	&Apache::loncommon::start_page($title).
1.1097    bisitz   7909: 	'<p class="LC_error">'.&mt($msg).'</p>'.
1.318     albertel 7910: 	&Apache::loncommon::end_page();
                   7911:     if (ref($r)) {
                   7912: 	$r->print($page);
1.327     albertel 7913: 	return;
1.318     albertel 7914:     }
                   7915:     return $page;
                   7916: }
1.347     albertel 7917: 
                   7918: {
1.610     albertel 7919:     my @row_count;
1.961     onken    7920: 
                   7921:     sub start_data_table_count {
                   7922:         unshift(@row_count, 0);
                   7923:         return;
                   7924:     }
                   7925: 
                   7926:     sub end_data_table_count {
                   7927:         shift(@row_count);
                   7928:         return;
                   7929:     }
                   7930: 
1.347     albertel 7931:     sub start_data_table {
1.1018    raeburn  7932: 	my ($add_class,$id) = @_;
1.422     albertel 7933: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  7934:         my $table_id;
                   7935:         if (defined($id)) {
                   7936:             $table_id = ' id="'.$id.'"';
                   7937:         }
1.961     onken    7938: 	&start_data_table_count();
1.1018    raeburn  7939: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 7940:     }
                   7941: 
                   7942:     sub end_data_table {
1.961     onken    7943: 	&end_data_table_count();
1.389     albertel 7944: 	return '</table>'."\n";;
1.347     albertel 7945:     }
                   7946: 
                   7947:     sub start_data_table_row {
1.974     wenzelju 7948: 	my ($add_class, $id) = @_;
1.610     albertel 7949: 	$row_count[0]++;
                   7950: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   7951: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 7952:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7953:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 7954:     }
1.471     banghart 7955:     
                   7956:     sub continue_data_table_row {
1.974     wenzelju 7957: 	my ($add_class, $id) = @_;
1.610     albertel 7958: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 7959: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   7960:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7961:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 7962:     }
1.347     albertel 7963: 
                   7964:     sub end_data_table_row {
1.389     albertel 7965: 	return '</tr>'."\n";;
1.347     albertel 7966:     }
1.367     www      7967: 
1.421     albertel 7968:     sub start_data_table_empty_row {
1.707     bisitz   7969: #	$row_count[0]++;
1.421     albertel 7970: 	return  '<tr class="LC_empty_row" >'."\n";;
                   7971:     }
                   7972: 
                   7973:     sub end_data_table_empty_row {
                   7974: 	return '</tr>'."\n";;
                   7975:     }
                   7976: 
1.367     www      7977:     sub start_data_table_header_row {
1.389     albertel 7978: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      7979:     }
                   7980: 
                   7981:     sub end_data_table_header_row {
1.389     albertel 7982: 	return '</tr>'."\n";;
1.367     www      7983:     }
1.890     droeschl 7984: 
                   7985:     sub data_table_caption {
                   7986:         my $caption = shift;
                   7987:         return "<caption class=\"LC_caption\">$caption</caption>";
                   7988:     }
1.347     albertel 7989: }
                   7990: 
1.548     albertel 7991: =pod
                   7992: 
                   7993: =item * &inhibit_menu_check($arg)
                   7994: 
                   7995: Checks for a inhibitmenu state and generates output to preserve it
                   7996: 
                   7997: Inputs:         $arg - can be any of
                   7998:                      - undef - in which case the return value is a string 
                   7999:                                to add  into arguments list of a uri
                   8000:                      - 'input' - in which case the return value is a HTML
                   8001:                                  <form> <input> field of type hidden to
                   8002:                                  preserve the value
                   8003:                      - a url - in which case the return value is the url with
                   8004:                                the neccesary cgi args added to preserve the
                   8005:                                inhibitmenu state
                   8006:                      - a ref to a url - no return value, but the string is
                   8007:                                         updated to include the neccessary cgi
                   8008:                                         args to preserve the inhibitmenu state
                   8009: 
                   8010: =cut
                   8011: 
                   8012: sub inhibit_menu_check {
                   8013:     my ($arg) = @_;
                   8014:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8015:     if ($arg eq 'input') {
                   8016: 	if ($env{'form.inhibitmenu'}) {
                   8017: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8018: 	} else {
                   8019: 	    return
                   8020: 	}
                   8021:     }
                   8022:     if ($env{'form.inhibitmenu'}) {
                   8023: 	if (ref($arg)) {
                   8024: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8025: 	} elsif ($arg eq '') {
                   8026: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8027: 	} else {
                   8028: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8029: 	}
                   8030:     }
                   8031:     if (!ref($arg)) {
                   8032: 	return $arg;
                   8033:     }
                   8034: }
                   8035: 
1.251     albertel 8036: ###############################################
1.182     matthew  8037: 
                   8038: =pod
                   8039: 
1.549     albertel 8040: =back
                   8041: 
                   8042: =head1 User Information Routines
                   8043: 
                   8044: =over 4
                   8045: 
1.405     albertel 8046: =item * &get_users_function()
1.182     matthew  8047: 
                   8048: Used by &bodytag to determine the current users primary role.
                   8049: Returns either 'student','coordinator','admin', or 'author'.
                   8050: 
                   8051: =cut
                   8052: 
                   8053: ###############################################
                   8054: sub get_users_function {
1.815     tempelho 8055:     my $function = 'norole';
1.818     tempelho 8056:     if ($env{'request.role'}=~/^(st)/) {
                   8057:         $function='student';
                   8058:     }
1.907     raeburn  8059:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8060:         $function='coordinator';
                   8061:     }
1.258     albertel 8062:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8063:         $function='admin';
                   8064:     }
1.826     bisitz   8065:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8066:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8067:         $function='author';
                   8068:     }
                   8069:     return $function;
1.54      www      8070: }
1.99      www      8071: 
                   8072: ###############################################
                   8073: 
1.233     raeburn  8074: =pod
                   8075: 
1.821     raeburn  8076: =item * &show_course()
                   8077: 
                   8078: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8079: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8080: 
                   8081: Inputs:
                   8082: None
                   8083: 
                   8084: Outputs:
                   8085: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8086: 
                   8087: =cut
                   8088: 
                   8089: ###############################################
                   8090: sub show_course {
                   8091:     my $course = !$env{'user.adv'};
                   8092:     if (!$env{'user.adv'}) {
                   8093:         foreach my $env (keys(%env)) {
                   8094:             next if ($env !~ m/^user\.priv\./);
                   8095:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8096:                 $course = 0;
                   8097:                 last;
                   8098:             }
                   8099:         }
                   8100:     }
                   8101:     return $course;
                   8102: }
                   8103: 
                   8104: ###############################################
                   8105: 
                   8106: =pod
                   8107: 
1.542     raeburn  8108: =item * &check_user_status()
1.274     raeburn  8109: 
                   8110: Determines current status of supplied role for a
                   8111: specific user. Roles can be active, previous or future.
                   8112: 
                   8113: Inputs: 
                   8114: user's domain, user's username, course's domain,
1.375     raeburn  8115: course's number, optional section ID.
1.274     raeburn  8116: 
                   8117: Outputs:
                   8118: role status: active, previous or future. 
                   8119: 
                   8120: =cut
                   8121: 
                   8122: sub check_user_status {
1.412     raeburn  8123:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8124:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8125:     my @uroles = keys %userinfo;
                   8126:     my $srchstr;
                   8127:     my $active_chk = 'none';
1.412     raeburn  8128:     my $now = time;
1.274     raeburn  8129:     if (@uroles > 0) {
1.908     raeburn  8130:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8131:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8132:         } else {
1.412     raeburn  8133:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8134:         }
                   8135:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8136:             my $role_end = 0;
                   8137:             my $role_start = 0;
                   8138:             $active_chk = 'active';
1.412     raeburn  8139:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8140:                 $role_end = $1;
                   8141:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8142:                     $role_start = $1;
1.274     raeburn  8143:                 }
                   8144:             }
                   8145:             if ($role_start > 0) {
1.412     raeburn  8146:                 if ($now < $role_start) {
1.274     raeburn  8147:                     $active_chk = 'future';
                   8148:                 }
                   8149:             }
                   8150:             if ($role_end > 0) {
1.412     raeburn  8151:                 if ($now > $role_end) {
1.274     raeburn  8152:                     $active_chk = 'previous';
                   8153:                 }
                   8154:             }
                   8155:         }
                   8156:     }
                   8157:     return $active_chk;
                   8158: }
                   8159: 
                   8160: ###############################################
                   8161: 
                   8162: =pod
                   8163: 
1.405     albertel 8164: =item * &get_sections()
1.233     raeburn  8165: 
                   8166: Determines all the sections for a course including
                   8167: sections with students and sections containing other roles.
1.419     raeburn  8168: Incoming parameters: 
                   8169: 
                   8170: 1. domain
                   8171: 2. course number 
                   8172: 3. reference to array containing roles for which sections should 
                   8173: be gathered (optional).
                   8174: 4. reference to array containing status types for which sections 
                   8175: should be gathered (optional).
                   8176: 
                   8177: If the third argument is undefined, sections are gathered for any role. 
                   8178: If the fourth argument is undefined, sections are gathered for any status.
                   8179: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8180:  
1.374     raeburn  8181: Returns section hash (keys are section IDs, values are
                   8182: number of users in each section), subject to the
1.419     raeburn  8183: optional roles filter, optional status filter 
1.233     raeburn  8184: 
                   8185: =cut
                   8186: 
                   8187: ###############################################
                   8188: sub get_sections {
1.419     raeburn  8189:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8190:     if (!defined($cdom) || !defined($cnum)) {
                   8191:         my $cid =  $env{'request.course.id'};
                   8192: 
                   8193: 	return if (!defined($cid));
                   8194: 
                   8195:         $cdom = $env{'course.'.$cid.'.domain'};
                   8196:         $cnum = $env{'course.'.$cid.'.num'};
                   8197:     }
                   8198: 
                   8199:     my %sectioncount;
1.419     raeburn  8200:     my $now = time;
1.240     albertel 8201: 
1.366     albertel 8202:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 8203: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8204: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8205: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8206:         my $start_index = &Apache::loncoursedata::CL_START();
                   8207:         my $end_index = &Apache::loncoursedata::CL_END();
                   8208:         my $status;
1.366     albertel 8209: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8210: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8211: 				                     $data->[$status_index],
                   8212:                                                      $data->[$start_index],
                   8213:                                                      $data->[$end_index]);
                   8214:             if ($stu_status eq 'Active') {
                   8215:                 $status = 'active';
                   8216:             } elsif ($end < $now) {
                   8217:                 $status = 'previous';
                   8218:             } elsif ($start > $now) {
                   8219:                 $status = 'future';
                   8220:             } 
                   8221: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8222:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8223:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8224: 		    $sectioncount{$section}++;
                   8225:                 }
1.240     albertel 8226: 	    }
                   8227: 	}
                   8228:     }
                   8229:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8230:     foreach my $user (sort(keys(%courseroles))) {
                   8231: 	if ($user !~ /^(\w{2})/) { next; }
                   8232: 	my ($role) = ($user =~ /^(\w{2})/);
                   8233: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8234: 	my ($section,$status);
1.240     albertel 8235: 	if ($role eq 'cr' &&
                   8236: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8237: 	    $section=$1;
                   8238: 	}
                   8239: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8240: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8241:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8242:         if ($end == -1 && $start == -1) {
                   8243:             next; #deleted role
                   8244:         }
                   8245:         if (!defined($possible_status)) { 
                   8246:             $sectioncount{$section}++;
                   8247:         } else {
                   8248:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8249:                 $status = 'active';
                   8250:             } elsif ($end < $now) {
                   8251:                 $status = 'future';
                   8252:             } elsif ($start > $now) {
                   8253:                 $status = 'previous';
                   8254:             }
                   8255:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8256:                 $sectioncount{$section}++;
                   8257:             }
                   8258:         }
1.233     raeburn  8259:     }
1.366     albertel 8260:     return %sectioncount;
1.233     raeburn  8261: }
                   8262: 
1.274     raeburn  8263: ###############################################
1.294     raeburn  8264: 
                   8265: =pod
1.405     albertel 8266: 
                   8267: =item * &get_course_users()
                   8268: 
1.275     raeburn  8269: Retrieves usernames:domains for users in the specified course
                   8270: with specific role(s), and access status. 
                   8271: 
                   8272: Incoming parameters:
1.277     albertel 8273: 1. course domain
                   8274: 2. course number
                   8275: 3. access status: users must have - either active, 
1.275     raeburn  8276: previous, future, or all.
1.277     albertel 8277: 4. reference to array of permissible roles
1.288     raeburn  8278: 5. reference to array of section restrictions (optional)
                   8279: 6. reference to results object (hash of hashes).
                   8280: 7. reference to optional userdata hash
1.609     raeburn  8281: 8. reference to optional statushash
1.630     raeburn  8282: 9. flag if privileged users (except those set to unhide in
                   8283:    course settings) should be excluded    
1.609     raeburn  8284: Keys of top level results hash are roles.
1.275     raeburn  8285: Keys of inner hashes are username:domain, with 
                   8286: values set to access type.
1.288     raeburn  8287: Optional userdata hash returns an array with arguments in the 
                   8288: same order as loncoursedata::get_classlist() for student data.
                   8289: 
1.609     raeburn  8290: Optional statushash returns
                   8291: 
1.288     raeburn  8292: Entries for end, start, section and status are blank because
                   8293: of the possibility of multiple values for non-student roles.
                   8294: 
1.275     raeburn  8295: =cut
1.405     albertel 8296: 
1.275     raeburn  8297: ###############################################
1.405     albertel 8298: 
1.275     raeburn  8299: sub get_course_users {
1.630     raeburn  8300:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8301:     my %idx = ();
1.419     raeburn  8302:     my %seclists;
1.288     raeburn  8303: 
                   8304:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8305:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8306:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8307:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8308:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8309:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8310:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8311:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8312: 
1.290     albertel 8313:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8314:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8315:         my $now = time;
1.277     albertel 8316:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8317:             my $match = 0;
1.412     raeburn  8318:             my $secmatch = 0;
1.419     raeburn  8319:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8320:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8321:             if ($section eq '') {
                   8322:                 $section = 'none';
                   8323:             }
1.291     albertel 8324:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8325:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8326:                     $secmatch = 1;
                   8327:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8328:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8329:                         $secmatch = 1;
                   8330:                     }
                   8331:                 } else {  
1.419     raeburn  8332: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8333: 		        $secmatch = 1;
                   8334:                     }
1.290     albertel 8335: 		}
1.412     raeburn  8336:                 if (!$secmatch) {
                   8337:                     next;
                   8338:                 }
1.419     raeburn  8339:             }
1.275     raeburn  8340:             if (defined($$types{'active'})) {
1.288     raeburn  8341:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8342:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8343:                     $match = 1;
1.275     raeburn  8344:                 }
                   8345:             }
                   8346:             if (defined($$types{'previous'})) {
1.609     raeburn  8347:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8348:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8349:                     $match = 1;
1.275     raeburn  8350:                 }
                   8351:             }
                   8352:             if (defined($$types{'future'})) {
1.609     raeburn  8353:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8354:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8355:                     $match = 1;
1.275     raeburn  8356:                 }
                   8357:             }
1.609     raeburn  8358:             if ($match) {
                   8359:                 push(@{$seclists{$student}},$section);
                   8360:                 if (ref($userdata) eq 'HASH') {
                   8361:                     $$userdata{$student} = $$classlist{$student};
                   8362:                 }
                   8363:                 if (ref($statushash) eq 'HASH') {
                   8364:                     $statushash->{$student}{'st'}{$section} = $status;
                   8365:                 }
1.288     raeburn  8366:             }
1.275     raeburn  8367:         }
                   8368:     }
1.412     raeburn  8369:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8370:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8371:         my $now = time;
1.609     raeburn  8372:         my %displaystatus = ( previous => 'Expired',
                   8373:                               active   => 'Active',
                   8374:                               future   => 'Future',
                   8375:                             );
1.630     raeburn  8376:         my %nothide;
                   8377:         if ($hidepriv) {
                   8378:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8379:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8380:                 if ($user !~ /:/) {
                   8381:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8382:                 } else {
                   8383:                     $nothide{$user} = 1;
                   8384:                 }
                   8385:             }
                   8386:         }
1.439     raeburn  8387:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8388:             my $match = 0;
1.412     raeburn  8389:             my $secmatch = 0;
1.439     raeburn  8390:             my $status;
1.412     raeburn  8391:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8392:             $user =~ s/:$//;
1.439     raeburn  8393:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8394:             if ($end == -1 || $start == -1) {
                   8395:                 next;
                   8396:             }
                   8397:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8398:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8399:                 my ($uname,$udom) = split(/:/,$user);
                   8400:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8401:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8402:                         $secmatch = 1;
                   8403:                     } elsif ($usec eq '') {
1.420     albertel 8404:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8405:                             $secmatch = 1;
                   8406:                         }
                   8407:                     } else {
                   8408:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8409:                             $secmatch = 1;
                   8410:                         }
                   8411:                     }
                   8412:                     if (!$secmatch) {
                   8413:                         next;
                   8414:                     }
1.288     raeburn  8415:                 }
1.419     raeburn  8416:                 if ($usec eq '') {
                   8417:                     $usec = 'none';
                   8418:                 }
1.275     raeburn  8419:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8420:                     if ($hidepriv) {
                   8421:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
                   8422:                             (!$nothide{$uname.':'.$udom})) {
                   8423:                             next;
                   8424:                         }
                   8425:                     }
1.503     raeburn  8426:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8427:                         $status = 'previous';
                   8428:                     } elsif ($start > $now) {
                   8429:                         $status = 'future';
                   8430:                     } else {
                   8431:                         $status = 'active';
                   8432:                     }
1.277     albertel 8433:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8434:                         if ($status eq $type) {
1.420     albertel 8435:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8436:                                 push(@{$$users{$role}{$user}},$type);
                   8437:                             }
1.288     raeburn  8438:                             $match = 1;
                   8439:                         }
                   8440:                     }
1.419     raeburn  8441:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8442:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8443: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8444:                         }
1.420     albertel 8445:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8446:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8447:                         }
1.609     raeburn  8448:                         if (ref($statushash) eq 'HASH') {
                   8449:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8450:                         }
1.275     raeburn  8451:                     }
                   8452:                 }
                   8453:             }
                   8454:         }
1.290     albertel 8455:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8456:             if ((defined($cdom)) && (defined($cnum))) {
                   8457:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8458:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8459:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8460:                     next if ($owner eq '');
                   8461:                     my ($ownername,$ownerdom);
                   8462:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8463:                         $ownername = $1;
                   8464:                         $ownerdom = $2;
                   8465:                     } else {
                   8466:                         $ownername = $owner;
                   8467:                         $ownerdom = $cdom;
                   8468:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8469:                     }
                   8470:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8471:                     if (defined($userdata) && 
1.609     raeburn  8472: 			!exists($$userdata{$owner})) {
                   8473: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8474:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8475:                             push(@{$seclists{$owner}},'none');
                   8476:                         }
                   8477:                         if (ref($statushash) eq 'HASH') {
                   8478:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8479:                         }
1.290     albertel 8480: 		    }
1.279     raeburn  8481:                 }
                   8482:             }
                   8483:         }
1.419     raeburn  8484:         foreach my $user (keys(%seclists)) {
                   8485:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8486:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8487:         }
1.275     raeburn  8488:     }
                   8489:     return;
                   8490: }
                   8491: 
1.288     raeburn  8492: sub get_user_info {
                   8493:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8494:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8495: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8496:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8497:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8498:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8499:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8500:     return;
                   8501: }
1.275     raeburn  8502: 
1.472     raeburn  8503: ###############################################
                   8504: 
                   8505: =pod
                   8506: 
                   8507: =item * &get_user_quota()
                   8508: 
                   8509: Retrieves quota assigned for storage of portfolio files for a user  
                   8510: 
                   8511: Incoming parameters:
                   8512: 1. user's username
                   8513: 2. user's domain
                   8514: 
                   8515: Returns:
1.536     raeburn  8516: 1. Disk quota (in Mb) assigned to student.
                   8517: 2. (Optional) Type of setting: custom or default
                   8518:    (individually assigned or default for user's 
                   8519:    institutional status).
                   8520: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8521:    or student - types as defined in localenroll::inst_usertypes 
                   8522:    for user's domain, which determines default quota for user.
                   8523: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8524: 
                   8525: If a value has been stored in the user's environment, 
1.536     raeburn  8526: it will return that, otherwise it returns the maximal default
                   8527: defined for the user's instituional status(es) in the domain.
1.472     raeburn  8528: 
                   8529: =cut
                   8530: 
                   8531: ###############################################
                   8532: 
                   8533: 
                   8534: sub get_user_quota {
                   8535:     my ($uname,$udom) = @_;
1.536     raeburn  8536:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8537:     if (!defined($udom)) {
                   8538:         $udom = $env{'user.domain'};
                   8539:     }
                   8540:     if (!defined($uname)) {
                   8541:         $uname = $env{'user.name'};
                   8542:     }
                   8543:     if (($udom eq '' || $uname eq '') ||
                   8544:         ($udom eq 'public') && ($uname eq 'public')) {
                   8545:         $quota = 0;
1.536     raeburn  8546:         $quotatype = 'default';
                   8547:         $defquota = 0; 
1.472     raeburn  8548:     } else {
1.536     raeburn  8549:         my $inststatus;
1.472     raeburn  8550:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8551:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  8552:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  8553:         } else {
1.536     raeburn  8554:             my %userenv = 
                   8555:                 &Apache::lonnet::get('environment',['portfolioquota',
                   8556:                                      'inststatus'],$udom,$uname);
1.472     raeburn  8557:             my ($tmp) = keys(%userenv);
                   8558:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8559:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  8560:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  8561:             } else {
                   8562:                 undef(%userenv);
                   8563:             }
                   8564:         }
1.536     raeburn  8565:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  8566:         if ($quota eq '') {
1.536     raeburn  8567:             $quota = $defquota;
                   8568:             $quotatype = 'default';
                   8569:         } else {
                   8570:             $quotatype = 'custom';
1.472     raeburn  8571:         }
                   8572:     }
1.536     raeburn  8573:     if (wantarray) {
                   8574:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8575:     } else {
                   8576:         return $quota;
                   8577:     }
1.472     raeburn  8578: }
                   8579: 
                   8580: ###############################################
                   8581: 
                   8582: =pod
                   8583: 
                   8584: =item * &default_quota()
                   8585: 
1.536     raeburn  8586: Retrieves default quota assigned for storage of user portfolio files,
                   8587: given an (optional) user's institutional status.
1.472     raeburn  8588: 
                   8589: Incoming parameters:
                   8590: 1. domain
1.536     raeburn  8591: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8592:    status types (e.g., faculty, staff, student etc.)
                   8593:    which apply to the user for whom the default is being retrieved.
                   8594:    If the institutional status string in undefined, the domain
                   8595:    default quota will be returned. 
1.472     raeburn  8596: 
                   8597: Returns:
                   8598: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  8599: 2. (Optional) institutional type which determined the value of the
                   8600:    default quota.
1.472     raeburn  8601: 
                   8602: If a value has been stored in the domain's configuration db,
                   8603: it will return that, otherwise it returns 20 (for backwards 
                   8604: compatibility with domains which have not set up a configuration
                   8605: db file; the original statically defined portfolio quota was 20 Mb). 
                   8606: 
1.536     raeburn  8607: If the user's status includes multiple types (e.g., staff and student),
                   8608: the largest default quota which applies to the user determines the
                   8609: default quota returned.
                   8610: 
1.780     raeburn  8611: =back
                   8612: 
1.472     raeburn  8613: =cut
                   8614: 
                   8615: ###############################################
                   8616: 
                   8617: 
                   8618: sub default_quota {
1.536     raeburn  8619:     my ($udom,$inststatus) = @_;
                   8620:     my ($defquota,$settingstatus);
                   8621:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8622:                                             ['quotas'],$udom);
                   8623:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8624:         if ($inststatus ne '') {
1.765     raeburn  8625:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8626:             foreach my $item (@statuses) {
1.711     raeburn  8627:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8628:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
                   8629:                         if ($defquota eq '') {
                   8630:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8631:                             $settingstatus = $item;
                   8632:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
                   8633:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8634:                             $settingstatus = $item;
                   8635:                         }
                   8636:                     }
                   8637:                 } else {
                   8638:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8639:                         if ($defquota eq '') {
                   8640:                             $defquota = $quotahash{'quotas'}{$item};
                   8641:                             $settingstatus = $item;
                   8642:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8643:                             $defquota = $quotahash{'quotas'}{$item};
                   8644:                             $settingstatus = $item;
                   8645:                         }
1.536     raeburn  8646:                     }
                   8647:                 }
                   8648:             }
                   8649:         }
                   8650:         if ($defquota eq '') {
1.711     raeburn  8651:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8652:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
                   8653:             } else {
                   8654:                 $defquota = $quotahash{'quotas'}{'default'};
                   8655:             }
1.536     raeburn  8656:             $settingstatus = 'default';
                   8657:         }
                   8658:     } else {
                   8659:         $settingstatus = 'default';
                   8660:         $defquota = 20;
                   8661:     }
                   8662:     if (wantarray) {
                   8663:         return ($defquota,$settingstatus);
1.472     raeburn  8664:     } else {
1.536     raeburn  8665:         return $defquota;
1.472     raeburn  8666:     }
                   8667: }
                   8668: 
1.384     raeburn  8669: sub get_secgrprole_info {
                   8670:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8671:     my %sections_count = &get_sections($cdom,$cnum);
                   8672:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8673:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8674:     my @groups = sort(keys(%curr_groups));
                   8675:     my $allroles = [];
                   8676:     my $rolehash;
                   8677:     my $accesshash = {
                   8678:                      active => 'Currently has access',
                   8679:                      future => 'Will have future access',
                   8680:                      previous => 'Previously had access',
                   8681:                   };
                   8682:     if ($needroles) {
                   8683:         $rolehash = {'all' => 'all'};
1.385     albertel 8684:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8685: 	if (&Apache::lonnet::error(%user_roles)) {
                   8686: 	    undef(%user_roles);
                   8687: 	}
                   8688:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8689:             my ($role)=split(/\:/,$item,2);
                   8690:             if ($role eq 'cr') { next; }
                   8691:             if ($role =~ /^cr/) {
                   8692:                 $$rolehash{$role} = (split('/',$role))[3];
                   8693:             } else {
                   8694:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8695:             }
                   8696:         }
                   8697:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8698:             push(@{$allroles},$key);
                   8699:         }
                   8700:         push (@{$allroles},'st');
                   8701:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8702:     }
                   8703:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8704: }
                   8705: 
1.555     raeburn  8706: sub user_picker {
1.994     raeburn  8707:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8708:     my $currdom = $dom;
                   8709:     my %curr_selected = (
                   8710:                         srchin => 'dom',
1.580     raeburn  8711:                         srchby => 'lastname',
1.555     raeburn  8712:                       );
                   8713:     my $srchterm;
1.625     raeburn  8714:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  8715:         if ($srch->{'srchby'} ne '') {
                   8716:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   8717:         }
                   8718:         if ($srch->{'srchin'} ne '') {
                   8719:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   8720:         }
                   8721:         if ($srch->{'srchtype'} ne '') {
                   8722:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   8723:         }
                   8724:         if ($srch->{'srchdomain'} ne '') {
                   8725:             $currdom = $srch->{'srchdomain'};
                   8726:         }
                   8727:         $srchterm = $srch->{'srchterm'};
                   8728:     }
                   8729:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  8730:                     'usr'       => 'Search criteria',
1.563     raeburn  8731:                     'doma'      => 'Domain/institution to search',
1.558     albertel 8732:                     'uname'     => 'username',
                   8733:                     'lastname'  => 'last name',
1.555     raeburn  8734:                     'lastfirst' => 'last name, first name',
1.558     albertel 8735:                     'crs'       => 'in this course',
1.576     raeburn  8736:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 8737:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  8738:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 8739:                     'exact'     => 'is',
                   8740:                     'contains'  => 'contains',
1.569     raeburn  8741:                     'begins'    => 'begins with',
1.571     raeburn  8742:                     'youm'      => "You must include some text to search for.",
                   8743:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   8744:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   8745:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   8746:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   8747:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   8748:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   8749:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  8750:                                        );
1.563     raeburn  8751:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   8752:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  8753: 
                   8754:     my @srchins = ('crs','dom','alc','instd');
                   8755: 
                   8756:     foreach my $option (@srchins) {
                   8757:         # FIXME 'alc' option unavailable until 
                   8758:         #       loncreateuser::print_user_query_page()
                   8759:         #       has been completed.
                   8760:         next if ($option eq 'alc');
1.880     raeburn  8761:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  8762:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  8763:         if ($curr_selected{'srchin'} eq $option) {
                   8764:             $srchinsel .= ' 
                   8765:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8766:         } else {
                   8767:             $srchinsel .= '
                   8768:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8769:         }
1.555     raeburn  8770:     }
1.563     raeburn  8771:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  8772: 
                   8773:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  8774:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  8775:         if ($curr_selected{'srchby'} eq $option) {
                   8776:             $srchbysel .= '
                   8777:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8778:         } else {
                   8779:             $srchbysel .= '
                   8780:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8781:          }
                   8782:     }
                   8783:     $srchbysel .= "\n  </select>\n";
                   8784: 
                   8785:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  8786:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  8787:         if ($curr_selected{'srchtype'} eq $option) {
                   8788:             $srchtypesel .= '
                   8789:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8790:         } else {
                   8791:             $srchtypesel .= '
                   8792:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8793:         }
                   8794:     }
                   8795:     $srchtypesel .= "\n  </select>\n";
                   8796: 
1.558     albertel 8797:     my ($newuserscript,$new_user_create);
1.994     raeburn  8798:     my $context_dom = $env{'request.role.domain'};
                   8799:     if ($context eq 'requestcrs') {
                   8800:         if ($env{'form.coursedom'} ne '') { 
                   8801:             $context_dom = $env{'form.coursedom'};
                   8802:         }
                   8803:     }
1.556     raeburn  8804:     if ($forcenewuser) {
1.576     raeburn  8805:         if (ref($srch) eq 'HASH') {
1.994     raeburn  8806:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  8807:                 if ($cancreate) {
                   8808:                     $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>';
                   8809:                 } else {
1.799     bisitz   8810:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  8811:                     my %usertypetext = (
                   8812:                         official   => 'institutional',
                   8813:                         unofficial => 'non-institutional',
                   8814:                     );
1.799     bisitz   8815:                     $new_user_create = '<p class="LC_warning">'
                   8816:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   8817:                                       .' '
                   8818:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   8819:                                           ,'<a href="'.$helplink.'">','</a>')
                   8820:                                       .'</p><br />';
1.627     raeburn  8821:                 }
1.576     raeburn  8822:             }
                   8823:         }
                   8824: 
1.556     raeburn  8825:         $newuserscript = <<"ENDSCRIPT";
                   8826: 
1.570     raeburn  8827: function setSearch(createnew,callingForm) {
1.556     raeburn  8828:     if (createnew == 1) {
1.570     raeburn  8829:         for (var i=0; i<callingForm.srchby.length; i++) {
                   8830:             if (callingForm.srchby.options[i].value == 'uname') {
                   8831:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  8832:             }
                   8833:         }
1.570     raeburn  8834:         for (var i=0; i<callingForm.srchin.length; i++) {
                   8835:             if ( callingForm.srchin.options[i].value == 'dom') {
                   8836: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  8837:             }
                   8838:         }
1.570     raeburn  8839:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   8840:             if (callingForm.srchtype.options[i].value == 'exact') {
                   8841:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  8842:             }
                   8843:         }
1.570     raeburn  8844:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  8845:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  8846:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  8847:             }
                   8848:         }
                   8849:     }
                   8850: }
                   8851: ENDSCRIPT
1.558     albertel 8852: 
1.556     raeburn  8853:     }
                   8854: 
1.555     raeburn  8855:     my $output = <<"END_BLOCK";
1.556     raeburn  8856: <script type="text/javascript">
1.824     bisitz   8857: // <![CDATA[
1.570     raeburn  8858: function validateEntry(callingForm) {
1.558     albertel 8859: 
1.556     raeburn  8860:     var checkok = 1;
1.558     albertel 8861:     var srchin;
1.570     raeburn  8862:     for (var i=0; i<callingForm.srchin.length; i++) {
                   8863: 	if ( callingForm.srchin[i].checked ) {
                   8864: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 8865: 	}
                   8866:     }
                   8867: 
1.570     raeburn  8868:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   8869:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   8870:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   8871:     var srchterm =  callingForm.srchterm.value;
                   8872:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  8873:     var msg = "";
                   8874: 
                   8875:     if (srchterm == "") {
                   8876:         checkok = 0;
1.571     raeburn  8877:         msg += "$lt{'youm'}\\n";
1.556     raeburn  8878:     }
                   8879: 
1.569     raeburn  8880:     if (srchtype== 'begins') {
                   8881:         if (srchterm.length < 2) {
                   8882:             checkok = 0;
1.571     raeburn  8883:             msg += "$lt{'thte'}\\n";
1.569     raeburn  8884:         }
                   8885:     }
                   8886: 
1.556     raeburn  8887:     if (srchtype== 'contains') {
                   8888:         if (srchterm.length < 3) {
                   8889:             checkok = 0;
1.571     raeburn  8890:             msg += "$lt{'thet'}\\n";
1.556     raeburn  8891:         }
                   8892:     }
                   8893:     if (srchin == 'instd') {
                   8894:         if (srchdomain == '') {
                   8895:             checkok = 0;
1.571     raeburn  8896:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  8897:         }
                   8898:     }
                   8899:     if (srchin == 'dom') {
                   8900:         if (srchdomain == '') {
                   8901:             checkok = 0;
1.571     raeburn  8902:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  8903:         }
                   8904:     }
                   8905:     if (srchby == 'lastfirst') {
                   8906:         if (srchterm.indexOf(",") == -1) {
                   8907:             checkok = 0;
1.571     raeburn  8908:             msg += "$lt{'whus'}\\n";
1.556     raeburn  8909:         }
                   8910:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   8911:             checkok = 0;
1.571     raeburn  8912:             msg += "$lt{'whse'}\\n";
1.556     raeburn  8913:         }
                   8914:     }
                   8915:     if (checkok == 0) {
1.571     raeburn  8916:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  8917:         return;
                   8918:     }
                   8919:     if (checkok == 1) {
1.570     raeburn  8920:         callingForm.submit();
1.556     raeburn  8921:     }
                   8922: }
                   8923: 
                   8924: $newuserscript
                   8925: 
1.824     bisitz   8926: // ]]>
1.556     raeburn  8927: </script>
1.558     albertel 8928: 
                   8929: $new_user_create
                   8930: 
1.555     raeburn  8931: END_BLOCK
1.558     albertel 8932: 
1.876     raeburn  8933:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   8934:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   8935:                $domform.
                   8936:                &Apache::lonhtmlcommon::row_closure().
                   8937:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   8938:                $srchbysel.
                   8939:                $srchtypesel. 
                   8940:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   8941:                $srchinsel.
                   8942:                &Apache::lonhtmlcommon::row_closure(1). 
                   8943:                &Apache::lonhtmlcommon::end_pick_box().
                   8944:                '<br />';
1.555     raeburn  8945:     return $output;
                   8946: }
                   8947: 
1.612     raeburn  8948: sub user_rule_check {
1.615     raeburn  8949:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  8950:     my $response;
                   8951:     if (ref($usershash) eq 'HASH') {
                   8952:         foreach my $user (keys(%{$usershash})) {
                   8953:             my ($uname,$udom) = split(/:/,$user);
                   8954:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  8955:             my ($id,$newuser);
1.612     raeburn  8956:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  8957:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  8958:                 $id = $usershash->{$user}->{'id'};
                   8959:             }
                   8960:             my $inst_response;
                   8961:             if (ref($checks) eq 'HASH') {
                   8962:                 if (defined($checks->{'username'})) {
1.615     raeburn  8963:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  8964:                         &Apache::lonnet::get_instuser($udom,$uname);
                   8965:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  8966:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  8967:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   8968:                 }
1.615     raeburn  8969:             } else {
                   8970:                 ($inst_response,%{$inst_results->{$user}}) =
                   8971:                     &Apache::lonnet::get_instuser($udom,$uname);
                   8972:                 return;
1.612     raeburn  8973:             }
1.615     raeburn  8974:             if (!$got_rules->{$udom}) {
1.612     raeburn  8975:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   8976:                                                   ['usercreation'],$udom);
                   8977:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  8978:                     foreach my $item ('username','id') {
1.612     raeburn  8979:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   8980:                             $$curr_rules{$udom}{$item} = 
                   8981:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  8982:                         }
                   8983:                     }
                   8984:                 }
1.615     raeburn  8985:                 $got_rules->{$udom} = 1;  
1.585     raeburn  8986:             }
1.612     raeburn  8987:             foreach my $item (keys(%{$checks})) {
                   8988:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   8989:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   8990:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   8991:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   8992:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   8993:                                 if ($rule_check{$rule}) {
                   8994:                                     $$rulematch{$user}{$item} = $rule;
                   8995:                                     if ($inst_response eq 'ok') {
1.615     raeburn  8996:                                         if (ref($inst_results) eq 'HASH') {
                   8997:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   8998:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   8999:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9000:                                                 }
1.612     raeburn  9001:                                             }
                   9002:                                         }
1.615     raeburn  9003:                                     }
                   9004:                                     last;
1.585     raeburn  9005:                                 }
                   9006:                             }
                   9007:                         }
                   9008:                     }
                   9009:                 }
                   9010:             }
                   9011:         }
                   9012:     }
1.612     raeburn  9013:     return;
                   9014: }
                   9015: 
                   9016: sub user_rule_formats {
                   9017:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9018:     my %text = ( 
                   9019:                  'username' => 'Usernames',
                   9020:                  'id'       => 'IDs',
                   9021:                );
                   9022:     my $output;
                   9023:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9024:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9025:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9026:             $output = '<br />'.
                   9027:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9028:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9029:                       ' <ul>';
1.612     raeburn  9030:             foreach my $rule (@{$ruleorder}) {
                   9031:                 if (ref($curr_rules) eq 'ARRAY') {
                   9032:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9033:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9034:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9035:                                         $rules->{$rule}{'desc'}.'</li>';
                   9036:                         }
                   9037:                     }
                   9038:                 }
                   9039:             }
                   9040:             $output .= '</ul>';
                   9041:         }
                   9042:     }
                   9043:     return $output;
                   9044: }
                   9045: 
                   9046: sub instrule_disallow_msg {
1.615     raeburn  9047:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9048:     my $response;
                   9049:     my %text = (
                   9050:                   item   => 'username',
                   9051:                   items  => 'usernames',
                   9052:                   match  => 'matches',
                   9053:                   do     => 'does',
                   9054:                   action => 'a username',
                   9055:                   one    => 'one',
                   9056:                );
                   9057:     if ($count > 1) {
                   9058:         $text{'item'} = 'usernames';
                   9059:         $text{'match'} ='match';
                   9060:         $text{'do'} = 'do';
                   9061:         $text{'action'} = 'usernames',
                   9062:         $text{'one'} = 'ones';
                   9063:     }
                   9064:     if ($checkitem eq 'id') {
                   9065:         $text{'items'} = 'IDs';
                   9066:         $text{'item'} = 'ID';
                   9067:         $text{'action'} = 'an ID';
1.615     raeburn  9068:         if ($count > 1) {
                   9069:             $text{'item'} = 'IDs';
                   9070:             $text{'action'} = 'IDs';
                   9071:         }
1.612     raeburn  9072:     }
1.674     bisitz   9073:     $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  9074:     if ($mode eq 'upload') {
                   9075:         if ($checkitem eq 'username') {
                   9076:             $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'}.");
                   9077:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9078:             $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  9079:         }
1.669     raeburn  9080:     } elsif ($mode eq 'selfcreate') {
                   9081:         if ($checkitem eq 'id') {
                   9082:             $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.");
                   9083:         }
1.615     raeburn  9084:     } else {
                   9085:         if ($checkitem eq 'username') {
                   9086:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9087:         } elsif ($checkitem eq 'id') {
                   9088:             $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.");
                   9089:         }
1.612     raeburn  9090:     }
                   9091:     return $response;
1.585     raeburn  9092: }
                   9093: 
1.624     raeburn  9094: sub personal_data_fieldtitles {
                   9095:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9096:                         id => 'Student/Employee ID',
                   9097:                         permanentemail => 'E-mail address',
                   9098:                         lastname => 'Last Name',
                   9099:                         firstname => 'First Name',
                   9100:                         middlename => 'Middle Name',
                   9101:                         generation => 'Generation',
                   9102:                         gen => 'Generation',
1.765     raeburn  9103:                         inststatus => 'Affiliation',
1.624     raeburn  9104:                    );
                   9105:     return %fieldtitles;
                   9106: }
                   9107: 
1.642     raeburn  9108: sub sorted_inst_types {
                   9109:     my ($dom) = @_;
                   9110:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9111:     my $othertitle = &mt('All users');
                   9112:     if ($env{'request.course.id'}) {
1.668     raeburn  9113:         $othertitle  = &mt('Any users');
1.642     raeburn  9114:     }
                   9115:     my @types;
                   9116:     if (ref($order) eq 'ARRAY') {
                   9117:         @types = @{$order};
                   9118:     }
                   9119:     if (@types == 0) {
                   9120:         if (ref($usertypes) eq 'HASH') {
                   9121:             @types = sort(keys(%{$usertypes}));
                   9122:         }
                   9123:     }
                   9124:     if (keys(%{$usertypes}) > 0) {
                   9125:         $othertitle = &mt('Other users');
                   9126:     }
                   9127:     return ($othertitle,$usertypes,\@types);
                   9128: }
                   9129: 
1.645     raeburn  9130: sub get_institutional_codes {
                   9131:     my ($settings,$allcourses,$LC_code) = @_;
                   9132: # Get complete list of course sections to update
                   9133:     my @currsections = ();
                   9134:     my @currxlists = ();
                   9135:     my $coursecode = $$settings{'internal.coursecode'};
                   9136: 
                   9137:     if ($$settings{'internal.sectionnums'} ne '') {
                   9138:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9139:     }
                   9140: 
                   9141:     if ($$settings{'internal.crosslistings'} ne '') {
                   9142:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9143:     }
                   9144: 
                   9145:     if (@currxlists > 0) {
                   9146:         foreach (@currxlists) {
                   9147:             if (m/^([^:]+):(\w*)$/) {
                   9148:                 unless (grep/^$1$/,@{$allcourses}) {
                   9149:                     push @{$allcourses},$1;
                   9150:                     $$LC_code{$1} = $2;
                   9151:                 }
                   9152:             }
                   9153:         }
                   9154:     }
                   9155:  
                   9156:     if (@currsections > 0) {
                   9157:         foreach (@currsections) {
                   9158:             if (m/^(\w+):(\w*)$/) {
                   9159:                 my $sec = $coursecode.$1;
                   9160:                 my $lc_sec = $2;
                   9161:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9162:                     push @{$allcourses},$sec;
                   9163:                     $$LC_code{$sec} = $lc_sec;
                   9164:                 }
                   9165:             }
                   9166:         }
                   9167:     }
                   9168:     return;
                   9169: }
                   9170: 
1.971     raeburn  9171: sub get_standard_codeitems {
                   9172:     return ('Year','Semester','Department','Number','Section');
                   9173: }
                   9174: 
1.112     bowersj2 9175: =pod
                   9176: 
1.780     raeburn  9177: =head1 Slot Helpers
                   9178: 
                   9179: =over 4
                   9180: 
                   9181: =item * sorted_slots()
                   9182: 
1.1040    raeburn  9183: Sorts an array of slot names in order of an optional sort key,
                   9184: default sort is by slot start time (earliest first). 
1.780     raeburn  9185: 
                   9186: Inputs:
                   9187: 
                   9188: =over 4
                   9189: 
                   9190: slotsarr  - Reference to array of unsorted slot names.
                   9191: 
                   9192: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9193: 
1.1040    raeburn  9194: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9195: 
1.549     albertel 9196: =back
                   9197: 
1.780     raeburn  9198: Returns:
                   9199: 
                   9200: =over 4
                   9201: 
1.1040    raeburn  9202: sorted   - An array of slot names sorted by a specified sort key 
                   9203:            (default sort key is start time of the slot).
1.780     raeburn  9204: 
                   9205: =back
                   9206: 
                   9207: =cut
                   9208: 
                   9209: 
                   9210: sub sorted_slots {
1.1040    raeburn  9211:     my ($slotsarr,$slots,$sortkey) = @_;
                   9212:     if ($sortkey eq '') {
                   9213:         $sortkey = 'starttime';
                   9214:     }
1.780     raeburn  9215:     my @sorted;
                   9216:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9217:         @sorted =
                   9218:             sort {
                   9219:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9220:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9221:                      }
                   9222:                      if (ref($slots->{$a})) { return -1;}
                   9223:                      if (ref($slots->{$b})) { return 1;}
                   9224:                      return 0;
                   9225:                  } @{$slotsarr};
                   9226:     }
                   9227:     return @sorted;
                   9228: }
                   9229: 
1.1040    raeburn  9230: =pod
                   9231: 
                   9232: =item * get_future_slots()
                   9233: 
                   9234: Inputs:
                   9235: 
                   9236: =over 4
                   9237: 
                   9238: cnum - course number
                   9239: 
                   9240: cdom - course domain
                   9241: 
                   9242: now - current UNIX time
                   9243: 
                   9244: symb - optional symb
                   9245: 
                   9246: =back
                   9247: 
                   9248: Returns:
                   9249: 
                   9250: =over 4
                   9251: 
                   9252: sorted_reservable - ref to array of student_schedulable slots currently 
                   9253:                     reservable, ordered by end date of reservation period.
                   9254: 
                   9255: reservable_now - ref to hash of student_schedulable slots currently
                   9256:                  reservable.
                   9257: 
                   9258:     Keys in inner hash are:
                   9259:     (a) symb: either blank or symb to which slot use is restricted.
                   9260:     (b) endreserve: end date of reservation period. 
                   9261: 
                   9262: sorted_future - ref to array of student_schedulable slots reservable in
                   9263:                 the future, ordered by start date of reservation period.
                   9264: 
                   9265: future_reservable - ref to hash of student_schedulable slots reservable
                   9266:                     in the future.
                   9267: 
                   9268:     Keys in inner hash are:
                   9269:     (a) symb: either blank or symb to which slot use is restricted.
                   9270:     (b) startreserve:  start date of reservation period.
                   9271: 
                   9272: =back
                   9273: 
                   9274: =cut
                   9275: 
                   9276: sub get_future_slots {
                   9277:     my ($cnum,$cdom,$now,$symb) = @_;
                   9278:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9279:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9280:     foreach my $slot (keys(%slots)) {
                   9281:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9282:         if ($symb) {
                   9283:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9284:                      ($slots{$slot}->{'symb'} ne $symb));
                   9285:         }
                   9286:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9287:             ($slots{$slot}->{'endtime'} > $now)) {
                   9288:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9289:                 my $userallowed = 0;
                   9290:                 if ($slots{$slot}->{'allowedsections'}) {
                   9291:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9292:                     if (!defined($env{'request.role.sec'})
                   9293:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9294:                         $userallowed=1;
                   9295:                     } else {
                   9296:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9297:                             $userallowed=1;
                   9298:                         }
                   9299:                     }
                   9300:                     unless ($userallowed) {
                   9301:                         if (defined($env{'request.course.groups'})) {
                   9302:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9303:                             foreach my $group (@groups) {
                   9304:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9305:                                     $userallowed=1;
                   9306:                                     last;
                   9307:                                 }
                   9308:                             }
                   9309:                         }
                   9310:                     }
                   9311:                 }
                   9312:                 if ($slots{$slot}->{'allowedusers'}) {
                   9313:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9314:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9315:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9316:                         $userallowed = 1;
                   9317:                     }
                   9318:                 }
                   9319:                 next unless($userallowed);
                   9320:             }
                   9321:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9322:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9323:             my $symb = $slots{$slot}->{'symb'};
                   9324:             if (($startreserve < $now) &&
                   9325:                 (!$endreserve || $endreserve > $now)) {
                   9326:                 my $lastres = $endreserve;
                   9327:                 if (!$lastres) {
                   9328:                     $lastres = $slots{$slot}->{'starttime'};
                   9329:                 }
                   9330:                 $reservable_now{$slot} = {
                   9331:                                            symb       => $symb,
                   9332:                                            endreserve => $lastres
                   9333:                                          };
                   9334:             } elsif (($startreserve > $now) &&
                   9335:                      (!$endreserve || $endreserve > $startreserve)) {
                   9336:                 $future_reservable{$slot} = {
                   9337:                                               symb         => $symb,
                   9338:                                               startreserve => $startreserve
                   9339:                                             };
                   9340:             }
                   9341:         }
                   9342:     }
                   9343:     my @unsorted_reservable = keys(%reservable_now);
                   9344:     if (@unsorted_reservable > 0) {
                   9345:         @sorted_reservable = 
                   9346:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9347:     }
                   9348:     my @unsorted_future = keys(%future_reservable);
                   9349:     if (@unsorted_future > 0) {
                   9350:         @sorted_future =
                   9351:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9352:     }
                   9353:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9354: }
1.780     raeburn  9355: 
                   9356: =pod
                   9357: 
1.1057    foxr     9358: =back
                   9359: 
1.549     albertel 9360: =head1 HTTP Helpers
                   9361: 
                   9362: =over 4
                   9363: 
1.648     raeburn  9364: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9365: 
1.258     albertel 9366: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9367: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9368: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9369: 
                   9370: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9371: $possible_names is an ref to an array of form element names.  As an example:
                   9372: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9373: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9374: 
                   9375: =cut
1.1       albertel 9376: 
1.6       albertel 9377: sub get_unprocessed_cgi {
1.25      albertel 9378:   my ($query,$possible_names)= @_;
1.26      matthew  9379:   # $Apache::lonxml::debug=1;
1.356     albertel 9380:   foreach my $pair (split(/&/,$query)) {
                   9381:     my ($name, $value) = split(/=/,$pair);
1.369     www      9382:     $name = &unescape($name);
1.25      albertel 9383:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9384:       $value =~ tr/+/ /;
                   9385:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9386:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9387:     }
1.16      harris41 9388:   }
1.6       albertel 9389: }
                   9390: 
1.112     bowersj2 9391: =pod
                   9392: 
1.648     raeburn  9393: =item * &cacheheader() 
1.112     bowersj2 9394: 
                   9395: returns cache-controlling header code
                   9396: 
                   9397: =cut
                   9398: 
1.7       albertel 9399: sub cacheheader {
1.258     albertel 9400:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9401:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9402:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9403:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9404:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9405:     return $output;
1.7       albertel 9406: }
                   9407: 
1.112     bowersj2 9408: =pod
                   9409: 
1.648     raeburn  9410: =item * &no_cache($r) 
1.112     bowersj2 9411: 
                   9412: specifies header code to not have cache
                   9413: 
                   9414: =cut
                   9415: 
1.9       albertel 9416: sub no_cache {
1.216     albertel 9417:     my ($r) = @_;
                   9418:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9419: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9420:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9421:     $r->no_cache(1);
                   9422:     $r->header_out("Expires" => $date);
                   9423:     $r->header_out("Pragma" => "no-cache");
1.123     www      9424: }
                   9425: 
                   9426: sub content_type {
1.181     albertel 9427:     my ($r,$type,$charset) = @_;
1.299     foxr     9428:     if ($r) {
                   9429: 	#  Note that printout.pl calls this with undef for $r.
                   9430: 	&no_cache($r);
                   9431:     }
1.258     albertel 9432:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9433:     unless ($charset) {
                   9434: 	$charset=&Apache::lonlocal::current_encoding;
                   9435:     }
                   9436:     if ($charset) { $type.='; charset='.$charset; }
                   9437:     if ($r) {
                   9438: 	$r->content_type($type);
                   9439:     } else {
                   9440: 	print("Content-type: $type\n\n");
                   9441:     }
1.9       albertel 9442: }
1.25      albertel 9443: 
1.112     bowersj2 9444: =pod
                   9445: 
1.648     raeburn  9446: =item * &add_to_env($name,$value) 
1.112     bowersj2 9447: 
1.258     albertel 9448: adds $name to the %env hash with value
1.112     bowersj2 9449: $value, if $name already exists, the entry is converted to an array
                   9450: reference and $value is added to the array.
                   9451: 
                   9452: =cut
                   9453: 
1.25      albertel 9454: sub add_to_env {
                   9455:   my ($name,$value)=@_;
1.258     albertel 9456:   if (defined($env{$name})) {
                   9457:     if (ref($env{$name})) {
1.25      albertel 9458:       #already have multiple values
1.258     albertel 9459:       push(@{ $env{$name} },$value);
1.25      albertel 9460:     } else {
                   9461:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9462:       my $first=$env{$name};
                   9463:       undef($env{$name});
                   9464:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9465:     }
                   9466:   } else {
1.258     albertel 9467:     $env{$name}=$value;
1.25      albertel 9468:   }
1.31      albertel 9469: }
1.149     albertel 9470: 
                   9471: =pod
                   9472: 
1.648     raeburn  9473: =item * &get_env_multiple($name) 
1.149     albertel 9474: 
1.258     albertel 9475: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9476: values may be defined and end up as an array ref.
                   9477: 
                   9478: returns an array of values
                   9479: 
                   9480: =cut
                   9481: 
                   9482: sub get_env_multiple {
                   9483:     my ($name) = @_;
                   9484:     my @values;
1.258     albertel 9485:     if (defined($env{$name})) {
1.149     albertel 9486:         # exists is it an array
1.258     albertel 9487:         if (ref($env{$name})) {
                   9488:             @values=@{ $env{$name} };
1.149     albertel 9489:         } else {
1.258     albertel 9490:             $values[0]=$env{$name};
1.149     albertel 9491:         }
                   9492:     }
                   9493:     return(@values);
                   9494: }
                   9495: 
1.660     raeburn  9496: sub ask_for_embedded_content {
                   9497:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9498:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  9499:         %currsubfile,%unused,$rem);
1.1071    raeburn  9500:     my $counter = 0;
                   9501:     my $numnew = 0;
1.987     raeburn  9502:     my $numremref = 0;
                   9503:     my $numinvalid = 0;
                   9504:     my $numpathchg = 0;
                   9505:     my $numexisting = 0;
1.1071    raeburn  9506:     my $numunused = 0;
                   9507:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
                   9508:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
                   9509:     my $heading = &mt('Upload embedded files');
                   9510:     my $buttontext = &mt('Upload');
                   9511: 
1.1085    raeburn  9512:     my $navmap;
                   9513:     if ($env{'request.course.id'}) {
                   9514:         $navmap = Apache::lonnavmaps::navmap->new();
                   9515:     }
1.984     raeburn  9516:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9517:         my $current_path='/';
                   9518:         if ($env{'form.currentpath'}) {
                   9519:             $current_path = $env{'form.currentpath'};
                   9520:         }
                   9521:         if ($actionurl eq '/adm/coursegrp_portfolio') {
                   9522:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9523:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9524:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9525:         } else {
                   9526:             $udom = $env{'user.domain'};
                   9527:             $uname = $env{'user.name'};
                   9528:             $url = '/userfiles/portfolio';
                   9529:         }
1.987     raeburn  9530:         $toplevel = $url.'/';
1.984     raeburn  9531:         $url .= $current_path;
                   9532:         $getpropath = 1;
1.987     raeburn  9533:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9534:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9535:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9536:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9537:         $toplevel = $url;
1.984     raeburn  9538:         if ($rest ne '') {
1.987     raeburn  9539:             $url .= $rest;
                   9540:         }
                   9541:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9542:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9543:             $url = $args->{'docs_url'};
                   9544:             $toplevel = $url;
1.1084    raeburn  9545:             if ($args->{'context'} eq 'paste') {
                   9546:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9547:                 ($path) = 
                   9548:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9549:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9550:                 $fileloc =~ s{^/}{};
                   9551:             }
1.1071    raeburn  9552:         }
1.1084    raeburn  9553:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  9554:         if ($env{'request.course.id'} ne '') {
                   9555:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9556:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
                   9557:             if (ref($args) eq 'HASH') {
                   9558:                 $url = $args->{'docs_url'};
                   9559:                 $title = $args->{'docs_title'};
                   9560:                 $toplevel = "/$url";
1.1085    raeburn  9561:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1071    raeburn  9562:                 ($path) =  
                   9563:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9564:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9565:                 $fileloc =~ s{^/}{};
                   9566:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9567:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9568:             }
1.987     raeburn  9569:         }
                   9570:     }
                   9571:     my $now = time();
                   9572:     foreach my $embed_file (keys(%{$allfiles})) {
                   9573:         my $absolutepath;
                   9574:         if ($embed_file =~ m{^\w+://}) {
                   9575:             $newfiles{$embed_file} = 1;
                   9576:             $mapping{$embed_file} = $embed_file;
                   9577:         } else {
                   9578:             if ($embed_file =~ m{^/}) {
                   9579:                 $absolutepath = $embed_file;
                   9580:                 $embed_file =~ s{^(/+)}{};
                   9581:             }
                   9582:             if ($embed_file =~ m{/}) {
                   9583:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
                   9584:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9585:                 my $item = $fname;
                   9586:                 if ($path ne '') {
                   9587:                     $item = $path.'/'.$fname;
                   9588:                     $subdependencies{$path}{$fname} = 1;
                   9589:                 } else {
                   9590:                     $dependencies{$item} = 1;
                   9591:                 }
                   9592:                 if ($absolutepath) {
                   9593:                     $mapping{$item} = $absolutepath;
                   9594:                 } else {
                   9595:                     $mapping{$item} = $embed_file;
                   9596:                 }
                   9597:             } else {
                   9598:                 $dependencies{$embed_file} = 1;
                   9599:                 if ($absolutepath) {
                   9600:                     $mapping{$embed_file} = $absolutepath;
                   9601:                 } else {
                   9602:                     $mapping{$embed_file} = $embed_file;
                   9603:                 }
                   9604:             }
1.984     raeburn  9605:         }
                   9606:     }
1.1071    raeburn  9607:     my $dirptr = 16384;
1.984     raeburn  9608:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9609:         $currsubfile{$path} = {};
1.984     raeburn  9610:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9611:             my ($sublistref,$listerror) =
                   9612:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9613:             if (ref($sublistref) eq 'ARRAY') {
                   9614:                 foreach my $line (@{$sublistref}) {
                   9615:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9616:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9617:                 }
1.984     raeburn  9618:             }
1.987     raeburn  9619:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9620:             if (opendir(my $dir,$url.'/'.$path)) {
                   9621:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9622:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9623:             }
1.1084    raeburn  9624:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9625:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9626:                   ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9627:             if ($env{'request.course.id'} ne '') {
                   9628:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9629:                 if ($dir ne '') {
                   9630:                     my ($sublistref,$listerror) =
                   9631:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9632:                     if (ref($sublistref) eq 'ARRAY') {
                   9633:                         foreach my $line (@{$sublistref}) {
                   9634:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9635:                                 undef,$mtime)=split(/\&/,$line,12);
                   9636:                             unless (($testdir&$dirptr) ||
                   9637:                                     ($file_name =~ /^\.\.?$/)) {
                   9638:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9639:                             }
                   9640:                         }
                   9641:                     }
                   9642:                 }
1.984     raeburn  9643:             }
                   9644:         }
                   9645:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9646:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9647:                 my $item = $path.'/'.$file;
                   9648:                 unless ($mapping{$item} eq $item) {
                   9649:                     $pathchanges{$item} = 1;
                   9650:                 }
                   9651:                 $existing{$item} = 1;
                   9652:                 $numexisting ++;
                   9653:             } else {
                   9654:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9655:             }
                   9656:         }
1.1071    raeburn  9657:         if ($actionurl eq '/adm/dependencies') {
                   9658:             foreach my $path (keys(%currsubfile)) {
                   9659:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9660:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9661:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  9662:                              next if (($rem ne '') &&
                   9663:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9664:                                        (ref($navmap) &&
                   9665:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9666:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9667:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9668:                              $unused{$path.'/'.$file} = 1; 
                   9669:                          }
                   9670:                     }
                   9671:                 }
                   9672:             }
                   9673:         }
1.984     raeburn  9674:     }
1.987     raeburn  9675:     my %currfile;
1.984     raeburn  9676:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9677:         my ($dirlistref,$listerror) =
                   9678:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9679:         if (ref($dirlistref) eq 'ARRAY') {
                   9680:             foreach my $line (@{$dirlistref}) {
                   9681:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   9682:                 $currfile{$file_name} = 1;
                   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)) {
1.987     raeburn  9687:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  9688:             map {$currfile{$_} = 1;} @dir_list;
                   9689:         }
1.1084    raeburn  9690:     } elsif (($actionurl eq '/adm/dependencies') ||
                   9691:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9692:               ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9693:         if ($env{'request.course.id'} ne '') {
                   9694:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9695:             if ($dir ne '') {
                   9696:                 my ($dirlistref,$listerror) =
                   9697:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   9698:                 if (ref($dirlistref) eq 'ARRAY') {
                   9699:                     foreach my $line (@{$dirlistref}) {
                   9700:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   9701:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   9702:                         unless (($testdir&$dirptr) ||
                   9703:                                 ($file_name =~ /^\.\.?$/)) {
                   9704:                             $currfile{$file_name} = [$size,$mtime];
                   9705:                         }
                   9706:                     }
                   9707:                 }
                   9708:             }
                   9709:         }
1.984     raeburn  9710:     }
                   9711:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  9712:         if (exists($currfile{$file})) {
1.987     raeburn  9713:             unless ($mapping{$file} eq $file) {
                   9714:                 $pathchanges{$file} = 1;
                   9715:             }
                   9716:             $existing{$file} = 1;
                   9717:             $numexisting ++;
                   9718:         } else {
1.984     raeburn  9719:             $newfiles{$file} = 1;
                   9720:         }
                   9721:     }
1.1071    raeburn  9722:     foreach my $file (keys(%currfile)) {
                   9723:         unless (($file eq $filename) ||
                   9724:                 ($file eq $filename.'.bak') ||
                   9725:                 ($dependencies{$file})) {
1.1085    raeburn  9726:             if ($actionurl eq '/adm/dependencies') {
                   9727:                 next if (($rem ne '') &&
                   9728:                          (($env{"httpref.$rem".$file} ne '') ||
                   9729:                           (ref($navmap) &&
                   9730:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   9731:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9732:                             ($navmap->getResourceByUrl($rem.$1)))))));
                   9733:             }
1.1071    raeburn  9734:             $unused{$file} = 1;
                   9735:         }
                   9736:     }
1.1084    raeburn  9737:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9738:         ($args->{'context'} eq 'paste')) {
                   9739:         $counter = scalar(keys(%existing));
                   9740:         $numpathchg = scalar(keys(%pathchanges));
                   9741:         return ($output,$counter,$numpathchg,\%existing); 
                   9742:     }
1.984     raeburn  9743:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  9744:         if ($actionurl eq '/adm/dependencies') {
                   9745:             next if ($embed_file =~ m{^\w+://});
                   9746:         }
1.660     raeburn  9747:         $upload_output .= &start_data_table_row().
1.1071    raeburn  9748:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
                   9749:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  9750:         unless ($mapping{$embed_file} eq $embed_file) {
                   9751:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
                   9752:         }
                   9753:         $upload_output .= '</td><td>';
1.1071    raeburn  9754:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.660     raeburn  9755:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
1.987     raeburn  9756:             $numremref++;
1.660     raeburn  9757:         } elsif ($args->{'error_on_invalid_names'}
                   9758:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.987     raeburn  9759:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
                   9760:             $numinvalid++;
1.660     raeburn  9761:         } else {
1.1071    raeburn  9762:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  9763:                                                      $embed_file,\%mapping,
1.1071    raeburn  9764:                                                      $allfiles,$codebase,'upload');
                   9765:             $counter ++;
                   9766:             $numnew ++;
1.987     raeburn  9767:         }
                   9768:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   9769:     }
                   9770:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  9771:         if ($actionurl eq '/adm/dependencies') {
                   9772:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   9773:             $modify_output .= &start_data_table_row().
                   9774:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   9775:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   9776:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   9777:                               '<td>'.$size.'</td>'.
                   9778:                               '<td>'.$mtime.'</td>'.
                   9779:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   9780:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   9781:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   9782:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   9783:                               &embedded_file_element('upload_embedded',$counter,
                   9784:                                                      $embed_file,\%mapping,
                   9785:                                                      $allfiles,$codebase,'modify').
                   9786:                               '</div></td>'.
                   9787:                               &end_data_table_row()."\n";
                   9788:             $counter ++;
                   9789:         } else {
                   9790:             $upload_output .= &start_data_table_row().
                   9791:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
                   9792:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
                   9793:                               &Apache::loncommon::end_data_table_row()."\n";
                   9794:         }
                   9795:     }
                   9796:     my $delidx = $counter;
                   9797:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   9798:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   9799:         $delete_output .= &start_data_table_row().
                   9800:                           '<td><img src="'.&icon($oldfile).'" />'.
                   9801:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   9802:                           '<td>'.$size.'</td>'.
                   9803:                           '<td>'.$mtime.'</td>'.
                   9804:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   9805:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   9806:                           &embedded_file_element('upload_embedded',$delidx,
                   9807:                                                  $oldfile,\%mapping,$allfiles,
                   9808:                                                  $codebase,'delete').'</td>'.
                   9809:                           &end_data_table_row()."\n"; 
                   9810:         $numunused ++;
                   9811:         $delidx ++;
1.987     raeburn  9812:     }
                   9813:     if ($upload_output) {
                   9814:         $upload_output = &start_data_table().
                   9815:                          $upload_output.
                   9816:                          &end_data_table()."\n";
                   9817:     }
1.1071    raeburn  9818:     if ($modify_output) {
                   9819:         $modify_output = &start_data_table().
                   9820:                          &start_data_table_header_row().
                   9821:                          '<th>'.&mt('File').'</th>'.
                   9822:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9823:                          '<th>'.&mt('Modified').'</th>'.
                   9824:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   9825:                          &end_data_table_header_row().
                   9826:                          $modify_output.
                   9827:                          &end_data_table()."\n";
                   9828:     }
                   9829:     if ($delete_output) {
                   9830:         $delete_output = &start_data_table().
                   9831:                          &start_data_table_header_row().
                   9832:                          '<th>'.&mt('File').'</th>'.
                   9833:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9834:                          '<th>'.&mt('Modified').'</th>'.
                   9835:                          '<th>'.&mt('Delete?').'</th>'.
                   9836:                          &end_data_table_header_row().
                   9837:                          $delete_output.
                   9838:                          &end_data_table()."\n";
                   9839:     }
1.987     raeburn  9840:     my $applies = 0;
                   9841:     if ($numremref) {
                   9842:         $applies ++;
                   9843:     }
                   9844:     if ($numinvalid) {
                   9845:         $applies ++;
                   9846:     }
                   9847:     if ($numexisting) {
                   9848:         $applies ++;
                   9849:     }
1.1071    raeburn  9850:     if ($counter || $numunused) {
1.987     raeburn  9851:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   9852:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  9853:                   $state.'<h3>'.$heading.'</h3>'; 
                   9854:         if ($actionurl eq '/adm/dependencies') {
                   9855:             if ($numnew) {
                   9856:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   9857:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   9858:                            $upload_output.'<br />'."\n";
                   9859:             }
                   9860:             if ($numexisting) {
                   9861:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   9862:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   9863:                            $modify_output.'<br />'."\n";
                   9864:                            $buttontext = &mt('Save changes');
                   9865:             }
                   9866:             if ($numunused) {
                   9867:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   9868:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   9869:                            $delete_output.'<br />'."\n";
                   9870:                            $buttontext = &mt('Save changes');
                   9871:             }
                   9872:         } else {
                   9873:             $output .= $upload_output.'<br />'."\n";
                   9874:         }
                   9875:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   9876:                    $counter.'" />'."\n";
                   9877:         if ($actionurl eq '/adm/dependencies') { 
                   9878:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   9879:                        $numnew.'" />'."\n";
                   9880:         } elsif ($actionurl eq '') {
1.987     raeburn  9881:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   9882:         }
                   9883:     } elsif ($applies) {
                   9884:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   9885:         if ($applies > 1) {
                   9886:             $output .=  
                   9887:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
                   9888:             if ($numremref) {
                   9889:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   9890:             }
                   9891:             if ($numinvalid) {
                   9892:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   9893:             }
                   9894:             if ($numexisting) {
                   9895:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   9896:             }
                   9897:             $output .= '</ul><br />';
                   9898:         } elsif ($numremref) {
                   9899:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   9900:         } elsif ($numinvalid) {
                   9901:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   9902:         } elsif ($numexisting) {
                   9903:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   9904:         }
                   9905:         $output .= $upload_output.'<br />';
                   9906:     }
                   9907:     my ($pathchange_output,$chgcount);
1.1071    raeburn  9908:     $chgcount = $counter;
1.987     raeburn  9909:     if (keys(%pathchanges) > 0) {
                   9910:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  9911:             if ($counter) {
1.987     raeburn  9912:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   9913:                                                   $embed_file,\%mapping,
1.1071    raeburn  9914:                                                   $allfiles,$codebase,'change');
1.987     raeburn  9915:             } else {
                   9916:                 $pathchange_output .= 
                   9917:                     &start_data_table_row().
                   9918:                     '<td><input type ="checkbox" name="namechange" value="'.
                   9919:                     $chgcount.'" checked="checked" /></td>'.
                   9920:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   9921:                     '<td>'.$embed_file.
                   9922:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  9923:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  9924:                     '</td>'.&end_data_table_row();
1.660     raeburn  9925:             }
1.987     raeburn  9926:             $numpathchg ++;
                   9927:             $chgcount ++;
1.660     raeburn  9928:         }
                   9929:     }
1.1071    raeburn  9930:     if ($counter) {
1.987     raeburn  9931:         if ($numpathchg) {
                   9932:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   9933:                        $numpathchg.'" />'."\n";
                   9934:         }
                   9935:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   9936:             ($actionurl eq '/adm/imsimport')) {
                   9937:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   9938:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   9939:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  9940:         } elsif ($actionurl eq '/adm/dependencies') {
                   9941:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  9942:         }
1.1071    raeburn  9943:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  9944:     } elsif ($numpathchg) {
                   9945:         my %pathchange = ();
                   9946:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   9947:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9948:             $output .= '<p>'.&mt('or').'</p>'; 
                   9949:         } 
                   9950:     }
1.1071    raeburn  9951:     return ($output,$counter,$numpathchg);
1.987     raeburn  9952: }
                   9953: 
                   9954: sub embedded_file_element {
1.1071    raeburn  9955:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  9956:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   9957:                    (ref($codebase) eq 'HASH'));
                   9958:     my $output;
1.1071    raeburn  9959:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  9960:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   9961:     }
                   9962:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   9963:                &escape($embed_file).'" />';
                   9964:     unless (($context eq 'upload_embedded') && 
                   9965:             ($mapping->{$embed_file} eq $embed_file)) {
                   9966:         $output .='
                   9967:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   9968:     }
                   9969:     my $attrib;
                   9970:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   9971:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   9972:     }
                   9973:     $output .=
                   9974:         "\n\t\t".
                   9975:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   9976:         $attrib.'" />';
                   9977:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   9978:         $output .=
                   9979:             "\n\t\t".
                   9980:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   9981:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  9982:     }
1.987     raeburn  9983:     return $output;
1.660     raeburn  9984: }
                   9985: 
1.1071    raeburn  9986: sub get_dependency_details {
                   9987:     my ($currfile,$currsubfile,$embed_file) = @_;
                   9988:     my ($size,$mtime,$showsize,$showmtime);
                   9989:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   9990:         if ($embed_file =~ m{/}) {
                   9991:             my ($path,$fname) = split(/\//,$embed_file);
                   9992:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   9993:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   9994:             }
                   9995:         } else {
                   9996:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   9997:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   9998:             }
                   9999:         }
                   10000:         $showsize = $size/1024.0;
                   10001:         $showsize = sprintf("%.1f",$showsize);
                   10002:         if ($mtime > 0) {
                   10003:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10004:         }
                   10005:     }
                   10006:     return ($showsize,$showmtime);
                   10007: }
                   10008: 
                   10009: sub ask_embedded_js {
                   10010:     return <<"END";
                   10011: <script type="text/javascript"">
                   10012: // <![CDATA[
                   10013: function toggleBrowse(counter) {
                   10014:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10015:     var fileid = document.getElementById('embedded_item_'+counter);
                   10016:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10017:     if (chkboxid.checked == true) {
                   10018:         uploaddivid.style.display='block';
                   10019:     } else {
                   10020:         uploaddivid.style.display='none';
                   10021:         fileid.value = '';
                   10022:     }
                   10023: }
                   10024: // ]]>
                   10025: </script>
                   10026: 
                   10027: END
                   10028: }
                   10029: 
1.661     raeburn  10030: sub upload_embedded {
                   10031:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10032:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10033:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10034:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10035:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10036:         my $orig_uploaded_filename =
                   10037:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10038:         foreach my $type ('orig','ref','attrib','codebase') {
                   10039:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10040:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10041:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10042:             }
                   10043:         }
1.661     raeburn  10044:         my ($path,$fname) =
                   10045:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10046:         # no path, whole string is fname
                   10047:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10048:         $fname = &Apache::lonnet::clean_filename($fname);
                   10049:         # See if there is anything left
                   10050:         next if ($fname eq '');
                   10051: 
                   10052:         # Check if file already exists as a file or directory.
                   10053:         my ($state,$msg);
                   10054:         if ($context eq 'portfolio') {
                   10055:             my $port_path = $dirpath;
                   10056:             if ($group ne '') {
                   10057:                 $port_path = "groups/$group/$port_path";
                   10058:             }
1.987     raeburn  10059:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10060:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10061:                                               $dir_root,$port_path,$disk_quota,
                   10062:                                               $current_disk_usage,$uname,$udom);
                   10063:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10064:                 || $state eq 'file_locked') {
1.661     raeburn  10065:                 $output .= $msg;
                   10066:                 next;
                   10067:             }
                   10068:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10069:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10070:             if ($state eq 'exists') {
                   10071:                 $output .= $msg;
                   10072:                 next;
                   10073:             }
                   10074:         }
                   10075:         # Check if extension is valid
                   10076:         if (($fname =~ /\.(\w+)$/) &&
                   10077:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.987     raeburn  10078:             $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  10079:             next;
                   10080:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10081:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10082:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10083:             next;
                   10084:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.987     raeburn  10085:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10086:             next;
                   10087:         }
                   10088:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   10089:         if ($context eq 'portfolio') {
1.984     raeburn  10090:             my $result;
                   10091:             if ($state eq 'existingfile') {
                   10092:                 $result=
                   10093:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.987     raeburn  10094:                                                     $dirpath.$env{'form.currentpath'}.$path);
1.661     raeburn  10095:             } else {
1.984     raeburn  10096:                 $result=
                   10097:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10098:                                                     $dirpath.
                   10099:                                                     $env{'form.currentpath'}.$path);
1.984     raeburn  10100:                 if ($result !~ m|^/uploaded/|) {
                   10101:                     $output .= '<span class="LC_error">'
                   10102:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10103:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10104:                                .'</span><br />';
                   10105:                     next;
                   10106:                 } else {
1.987     raeburn  10107:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10108:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10109:                 }
1.661     raeburn  10110:             }
1.987     raeburn  10111:         } elsif ($context eq 'coursedoc') {
                   10112:             my $result =
                   10113:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
                   10114:                                                 $dirpath.'/'.$path);
                   10115:             if ($result !~ m|^/uploaded/|) {
                   10116:                 $output .= '<span class="LC_error">'
                   10117:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10118:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10119:                            .'</span><br />';
                   10120:                     next;
                   10121:             } else {
                   10122:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10123:                            $path.$fname.'</span>').'<br />';
                   10124:             }
1.661     raeburn  10125:         } else {
                   10126: # Save the file
                   10127:             my $target = $env{'form.embedded_item_'.$i};
                   10128:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10129:             my $dest = $fullpath.$fname;
                   10130:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10131:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10132:             my $count;
                   10133:             my $filepath = $dir_root;
1.1027    raeburn  10134:             foreach my $subdir (@parts) {
                   10135:                 $filepath .= "/$subdir";
                   10136:                 if (!-e $filepath) {
1.661     raeburn  10137:                     mkdir($filepath,0770);
                   10138:                 }
                   10139:             }
                   10140:             my $fh;
                   10141:             if (!open($fh,'>'.$dest)) {
                   10142:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10143:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10144:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10145:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10146:                            '</span><br />';
                   10147:             } else {
                   10148:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10149:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10150:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10151:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10152:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10153:                               '</span><br />';
                   10154:                 } else {
1.987     raeburn  10155:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10156:                                $url.'</span>').'<br />';
                   10157:                     unless ($context eq 'testbank') {
                   10158:                         $footer .= &mt('View embedded file: [_1]',
                   10159:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10160:                     }
                   10161:                 }
                   10162:                 close($fh);
                   10163:             }
                   10164:         }
                   10165:         if ($env{'form.embedded_ref_'.$i}) {
                   10166:             $pathchange{$i} = 1;
                   10167:         }
                   10168:     }
                   10169:     if ($output) {
                   10170:         $output = '<p>'.$output.'</p>';
                   10171:     }
                   10172:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10173:     $returnflag = 'ok';
1.1071    raeburn  10174:     my $numpathchgs = scalar(keys(%pathchange));
                   10175:     if ($numpathchgs > 0) {
1.987     raeburn  10176:         if ($context eq 'portfolio') {
                   10177:             $output .= '<p>'.&mt('or').'</p>';
                   10178:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10179:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10180:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10181:             $returnflag = 'modify_orightml';
                   10182:         }
                   10183:     }
1.1071    raeburn  10184:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10185: }
                   10186: 
                   10187: sub modify_html_form {
                   10188:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10189:     my $end = 0;
                   10190:     my $modifyform;
                   10191:     if ($context eq 'upload_embedded') {
                   10192:         return unless (ref($pathchange) eq 'HASH');
                   10193:         if ($env{'form.number_embedded_items'}) {
                   10194:             $end += $env{'form.number_embedded_items'};
                   10195:         }
                   10196:         if ($env{'form.number_pathchange_items'}) {
                   10197:             $end += $env{'form.number_pathchange_items'};
                   10198:         }
                   10199:         if ($end) {
                   10200:             for (my $i=0; $i<$end; $i++) {
                   10201:                 if ($i < $env{'form.number_embedded_items'}) {
                   10202:                     next unless($pathchange->{$i});
                   10203:                 }
                   10204:                 $modifyform .=
                   10205:                     &start_data_table_row().
                   10206:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10207:                     'checked="checked" /></td>'.
                   10208:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10209:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10210:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10211:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10212:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10213:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10214:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10215:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10216:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10217:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10218:                     &end_data_table_row();
1.1071    raeburn  10219:             }
1.987     raeburn  10220:         }
                   10221:     } else {
                   10222:         $modifyform = $pathchgtable;
                   10223:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10224:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10225:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10226:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10227:         }
                   10228:     }
                   10229:     if ($modifyform) {
1.1071    raeburn  10230:         if ($actionurl eq '/adm/dependencies') {
                   10231:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10232:         }
1.987     raeburn  10233:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10234:                '<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".
                   10235:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10236:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10237:                '</ol></p>'."\n".'<p>'.
                   10238:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10239:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10240:                &start_data_table()."\n".
                   10241:                &start_data_table_header_row().
                   10242:                '<th>'.&mt('Change?').'</th>'.
                   10243:                '<th>'.&mt('Current reference').'</th>'.
                   10244:                '<th>'.&mt('Required reference').'</th>'.
                   10245:                &end_data_table_header_row()."\n".
                   10246:                $modifyform.
                   10247:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10248:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10249:                '</form>'."\n";
                   10250:     }
                   10251:     return;
                   10252: }
                   10253: 
                   10254: sub modify_html_refs {
                   10255:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
                   10256:     my $container;
                   10257:     if ($context eq 'portfolio') {
                   10258:         $container = $env{'form.container'};
                   10259:     } elsif ($context eq 'coursedoc') {
                   10260:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10261:     } elsif ($context eq 'manage_dependencies') {
                   10262:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10263:         $container = "/$container";
1.987     raeburn  10264:     } else {
1.1027    raeburn  10265:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10266:     }
                   10267:     my (%allfiles,%codebase,$output,$content);
                   10268:     my @changes = &get_env_multiple('form.namechange');
1.1071    raeburn  10269:     unless (@changes > 0) {
                   10270:         if (wantarray) {
                   10271:             return ('',0,0); 
                   10272:         } else {
                   10273:             return;
                   10274:         }
                   10275:     }
                   10276:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10277:         ($context eq 'manage_dependencies')) {
                   10278:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10279:             if (wantarray) {
                   10280:                 return ('',0,0);
                   10281:             } else {
                   10282:                 return;
                   10283:             }
                   10284:         } 
1.987     raeburn  10285:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10286:         if ($content eq '-1') {
                   10287:             if (wantarray) {
                   10288:                 return ('',0,0);
                   10289:             } else {
                   10290:                 return;
                   10291:             }
                   10292:         }
1.987     raeburn  10293:     } else {
1.1071    raeburn  10294:         unless ($container =~ /^\Q$dir_root\E/) {
                   10295:             if (wantarray) {
                   10296:                 return ('',0,0);
                   10297:             } else {
                   10298:                 return;
                   10299:             }
                   10300:         } 
1.987     raeburn  10301:         if (open(my $fh,"<$container")) {
                   10302:             $content = join('', <$fh>);
                   10303:             close($fh);
                   10304:         } else {
1.1071    raeburn  10305:             if (wantarray) {
                   10306:                 return ('',0,0);
                   10307:             } else {
                   10308:                 return;
                   10309:             }
1.987     raeburn  10310:         }
                   10311:     }
                   10312:     my ($count,$codebasecount) = (0,0);
                   10313:     my $mm = new File::MMagic;
                   10314:     my $mime_type = $mm->checktype_contents($content);
                   10315:     if ($mime_type eq 'text/html') {
                   10316:         my $parse_result = 
                   10317:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10318:                                                     \%codebase,\$content);
                   10319:         if ($parse_result eq 'ok') {
                   10320:             foreach my $i (@changes) {
                   10321:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10322:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10323:                 if ($allfiles{$ref}) {
                   10324:                     my $newname =  $orig;
                   10325:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10326:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10327:                     if ($attrib_regexp =~ /:/) {
                   10328:                         $attrib_regexp =~ s/\:/|/g;
                   10329:                     }
                   10330:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10331:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10332:                         $count += $numchg;
                   10333:                     }
                   10334:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10335:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10336:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10337:                         $codebasecount ++;
                   10338:                     }
                   10339:                 }
                   10340:             }
                   10341:             if ($count || $codebasecount) {
                   10342:                 my $saveresult;
1.1071    raeburn  10343:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10344:                     ($context eq 'manage_dependencies')) {
1.987     raeburn  10345:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10346:                     if ($url eq $container) {
                   10347:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10348:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10349:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10350:                                             $fname.'</span>').'</p>';
1.987     raeburn  10351:                     } else {
                   10352:                          $output = '<p class="LC_error">'.
                   10353:                                    &mt('Error: update failed for: [_1].',
                   10354:                                    '<span class="LC_filename">'.
                   10355:                                    $container.'</span>').'</p>';
                   10356:                     }
                   10357:                 } else {
                   10358:                     if (open(my $fh,">$container")) {
                   10359:                         print $fh $content;
                   10360:                         close($fh);
                   10361:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10362:                                   $count,'<span class="LC_filename">'.
                   10363:                                   $container.'</span>').'</p>';
1.661     raeburn  10364:                     } else {
1.987     raeburn  10365:                          $output = '<p class="LC_error">'.
                   10366:                                    &mt('Error: could not update [_1].',
                   10367:                                    '<span class="LC_filename">'.
                   10368:                                    $container.'</span>').'</p>';
1.661     raeburn  10369:                     }
                   10370:                 }
                   10371:             }
1.987     raeburn  10372:         } else {
                   10373:             &logthis('Failed to parse '.$container.
                   10374:                      ' to modify references: '.$parse_result);
1.661     raeburn  10375:         }
                   10376:     }
1.1071    raeburn  10377:     if (wantarray) {
                   10378:         return ($output,$count,$codebasecount);
                   10379:     } else {
                   10380:         return $output;
                   10381:     }
1.661     raeburn  10382: }
                   10383: 
                   10384: sub check_for_existing {
                   10385:     my ($path,$fname,$element) = @_;
                   10386:     my ($state,$msg);
                   10387:     if (-d $path.'/'.$fname) {
                   10388:         $state = 'exists';
                   10389:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10390:     } elsif (-e $path.'/'.$fname) {
                   10391:         $state = 'exists';
                   10392:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10393:     }
                   10394:     if ($state eq 'exists') {
                   10395:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10396:     }
                   10397:     return ($state,$msg);
                   10398: }
                   10399: 
                   10400: sub check_for_upload {
                   10401:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10402:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10403:     my $filesize = length($env{'form.'.$element});
                   10404:     if (!$filesize) {
                   10405:         my $msg = '<span class="LC_error">'.
                   10406:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10407:                       '<span class="LC_filename">'.$fname.'</span>',
                   10408:                       $filesize).'<br />'.
1.1007    raeburn  10409:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10410:                   '</span>';
                   10411:         return ('zero_bytes',$msg);
                   10412:     }
                   10413:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10414:     my $getpropath = 1;
1.1021    raeburn  10415:     my ($dirlistref,$listerror) =
                   10416:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10417:     my $found_file = 0;
                   10418:     my $locked_file = 0;
1.991     raeburn  10419:     my @lockers;
                   10420:     my $navmap;
                   10421:     if ($env{'request.course.id'}) {
                   10422:         $navmap = Apache::lonnavmaps::navmap->new();
                   10423:     }
1.1021    raeburn  10424:     if (ref($dirlistref) eq 'ARRAY') {
                   10425:         foreach my $line (@{$dirlistref}) {
                   10426:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10427:             if ($file_name eq $fname){
                   10428:                 $file_name = $path.$file_name;
                   10429:                 if ($group ne '') {
                   10430:                     $file_name = $group.$file_name;
                   10431:                 }
                   10432:                 $found_file = 1;
                   10433:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10434:                     foreach my $lock (@lockers) {
                   10435:                         if (ref($lock) eq 'ARRAY') {
                   10436:                             my ($symb,$crsid) = @{$lock};
                   10437:                             if ($crsid eq $env{'request.course.id'}) {
                   10438:                                 if (ref($navmap)) {
                   10439:                                     my $res = $navmap->getBySymb($symb);
                   10440:                                     foreach my $part (@{$res->parts()}) { 
                   10441:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10442:                                         unless (($slot_status == $res->RESERVED) ||
                   10443:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10444:                                             $locked_file = 1;
                   10445:                                         }
1.991     raeburn  10446:                                     }
1.1021    raeburn  10447:                                 } else {
                   10448:                                     $locked_file = 1;
1.991     raeburn  10449:                                 }
                   10450:                             } else {
                   10451:                                 $locked_file = 1;
                   10452:                             }
                   10453:                         }
1.1021    raeburn  10454:                    }
                   10455:                 } else {
                   10456:                     my @info = split(/\&/,$rest);
                   10457:                     my $currsize = $info[6]/1000;
                   10458:                     if ($currsize < $filesize) {
                   10459:                         my $extra = $filesize - $currsize;
                   10460:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10461:                             my $msg = '<span class="LC_error">'.
                   10462:                                       &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.',
                   10463:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10464:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10465:                                                    $disk_quota,$current_disk_usage);
                   10466:                             return ('will_exceed_quota',$msg);
                   10467:                         }
1.984     raeburn  10468:                     }
                   10469:                 }
1.661     raeburn  10470:             }
                   10471:         }
                   10472:     }
                   10473:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10474:         my $msg = '<span class="LC_error">'.
                   10475:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10476:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10477:         return ('will_exceed_quota',$msg);
                   10478:     } elsif ($found_file) {
                   10479:         if ($locked_file) {
                   10480:             my $msg = '<span class="LC_error">';
                   10481:             $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>');
                   10482:             $msg .= '</span><br />';
                   10483:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10484:             return ('file_locked',$msg);
                   10485:         } else {
                   10486:             my $msg = '<span class="LC_error">';
1.984     raeburn  10487:             $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  10488:             $msg .= '</span>';
1.984     raeburn  10489:             return ('existingfile',$msg);
1.661     raeburn  10490:         }
                   10491:     }
                   10492: }
                   10493: 
1.987     raeburn  10494: sub check_for_traversal {
                   10495:     my ($path,$url,$toplevel) = @_;
                   10496:     my @parts=split(/\//,$path);
                   10497:     my $cleanpath;
                   10498:     my $fullpath = $url;
                   10499:     for (my $i=0;$i<@parts;$i++) {
                   10500:         next if ($parts[$i] eq '.');
                   10501:         if ($parts[$i] eq '..') {
                   10502:             $fullpath =~ s{([^/]+/)$}{};
                   10503:         } else {
                   10504:             $fullpath .= $parts[$i].'/';
                   10505:         }
                   10506:     }
                   10507:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10508:         $cleanpath = $1;
                   10509:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10510:         my $curr_toprel = $1;
                   10511:         my @parts = split(/\//,$curr_toprel);
                   10512:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10513:         my @urlparts = split(/\//,$url_toprel);
                   10514:         my $doubledots;
                   10515:         my $startdiff = -1;
                   10516:         for (my $i=0; $i<@urlparts; $i++) {
                   10517:             if ($startdiff == -1) {
                   10518:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10519:                     $startdiff = $i;
                   10520:                     $doubledots .= '../';
                   10521:                 }
                   10522:             } else {
                   10523:                 $doubledots .= '../';
                   10524:             }
                   10525:         }
                   10526:         if ($startdiff > -1) {
                   10527:             $cleanpath = $doubledots;
                   10528:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10529:                 $cleanpath .= $parts[$i].'/';
                   10530:             }
                   10531:         }
                   10532:     }
                   10533:     $cleanpath =~ s{(/)$}{};
                   10534:     return $cleanpath;
                   10535: }
1.31      albertel 10536: 
1.1053    raeburn  10537: sub is_archive_file {
                   10538:     my ($mimetype) = @_;
                   10539:     if (($mimetype eq 'application/octet-stream') ||
                   10540:         ($mimetype eq 'application/x-stuffit') ||
                   10541:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10542:         return 1;
                   10543:     }
                   10544:     return;
                   10545: }
                   10546: 
                   10547: sub decompress_form {
1.1065    raeburn  10548:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10549:     my %lt = &Apache::lonlocal::texthash (
                   10550:         this => 'This file is an archive file.',
1.1067    raeburn  10551:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10552:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10553:         youm => 'You may wish to extract its contents.',
                   10554:         extr => 'Extract contents',
1.1067    raeburn  10555:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10556:         proa => 'Process automatically?',
1.1053    raeburn  10557:         yes  => 'Yes',
                   10558:         no   => 'No',
1.1067    raeburn  10559:         fold => 'Title for folder containing movie',
                   10560:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10561:     );
1.1065    raeburn  10562:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10563:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10564:     my $info = &list_archive_contents($fileloc,\@paths);
                   10565:     if (@paths) {
                   10566:         foreach my $path (@paths) {
                   10567:             $path =~ s{^/}{};
1.1067    raeburn  10568:             if ($path =~ m{^([^/]+)/$}) {
                   10569:                 $topdir = $1;
                   10570:             }
1.1065    raeburn  10571:             if ($path =~ m{^([^/]+)/}) {
                   10572:                 $toplevel{$1} = $path;
                   10573:             } else {
                   10574:                 $toplevel{$path} = $path;
                   10575:             }
                   10576:         }
                   10577:     }
1.1067    raeburn  10578:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
                   10579:         my @camtasia = ("$topdir/","$topdir/index.html",
                   10580:                         "$topdir/media/",
                   10581:                         "$topdir/media/$topdir.mp4",
                   10582:                         "$topdir/media/FirstFrame.png",
                   10583:                         "$topdir/media/player.swf",
                   10584:                         "$topdir/media/swfobject.js",
                   10585:                         "$topdir/media/expressInstall.swf");
                   10586:         my @diffs = &compare_arrays(\@paths,\@camtasia);
                   10587:         if (@diffs == 0) {
                   10588:             $is_camtasia = 1;
                   10589:         }
                   10590:     }
                   10591:     my $output;
                   10592:     if ($is_camtasia) {
                   10593:         $output = <<"ENDCAM";
                   10594: <script type="text/javascript" language="Javascript">
                   10595: // <![CDATA[
                   10596: 
                   10597: function camtasiaToggle() {
                   10598:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   10599:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
                   10600:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
                   10601: 
                   10602:                 document.getElementById('camtasia_titles').style.display='block';
                   10603:             } else {
                   10604:                 document.getElementById('camtasia_titles').style.display='none';
                   10605:             }
                   10606:         }
                   10607:     }
                   10608:     return;
                   10609: }
                   10610: 
                   10611: // ]]>
                   10612: </script>
                   10613: <p>$lt{'camt'}</p>
                   10614: ENDCAM
1.1065    raeburn  10615:     } else {
1.1067    raeburn  10616:         $output = '<p>'.$lt{'this'};
                   10617:         if ($info eq '') {
                   10618:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   10619:         } else {
                   10620:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   10621:                        '<div><pre>'.$info.'</pre></div>';
                   10622:         }
1.1065    raeburn  10623:     }
1.1067    raeburn  10624:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  10625:     my $duplicates;
                   10626:     my $num = 0;
                   10627:     if (ref($dirlist) eq 'ARRAY') {
                   10628:         foreach my $item (@{$dirlist}) {
                   10629:             if (ref($item) eq 'ARRAY') {
                   10630:                 if (exists($toplevel{$item->[0]})) {
                   10631:                     $duplicates .= 
                   10632:                         &start_data_table_row().
                   10633:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10634:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   10635:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10636:                         'value="1" />'.&mt('Yes').'</label>'.
                   10637:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   10638:                         '<td>'.$item->[0].'</td>';
                   10639:                     if ($item->[2]) {
                   10640:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   10641:                     } else {
                   10642:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   10643:                     }
                   10644:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   10645:                                    '<td>'.
                   10646:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   10647:                                    '</td>'.
                   10648:                                    &end_data_table_row();
                   10649:                     $num ++;
                   10650:                 }
                   10651:             }
                   10652:         }
                   10653:     }
                   10654:     my $itemcount;
                   10655:     if (@paths > 0) {
                   10656:         $itemcount = scalar(@paths);
                   10657:     } else {
                   10658:         $itemcount = 1;
                   10659:     }
1.1067    raeburn  10660:     if ($is_camtasia) {
                   10661:         $output .= $lt{'auto'}.'<br />'.
                   10662:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
                   10663:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
                   10664:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   10665:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   10666:                    $lt{'no'}.'</label></span><br />'.
                   10667:                    '<div id="camtasia_titles" style="display:block">'.
                   10668:                    &Apache::lonhtmlcommon::start_pick_box().
                   10669:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   10670:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   10671:                    &Apache::lonhtmlcommon::row_closure().
                   10672:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   10673:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   10674:                    &Apache::lonhtmlcommon::row_closure(1).
                   10675:                    &Apache::lonhtmlcommon::end_pick_box().
                   10676:                    '</div>';
                   10677:     }
1.1065    raeburn  10678:     $output .= 
                   10679:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  10680:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   10681:         "\n";
1.1065    raeburn  10682:     if ($duplicates ne '') {
                   10683:         $output .= '<p><span class="LC_warning">'.
                   10684:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   10685:                    &start_data_table().
                   10686:                    &start_data_table_header_row().
                   10687:                    '<th>'.&mt('Overwrite?').'</th>'.
                   10688:                    '<th>'.&mt('Name').'</th>'.
                   10689:                    '<th>'.&mt('Type').'</th>'.
                   10690:                    '<th>'.&mt('Size').'</th>'.
                   10691:                    '<th>'.&mt('Last modified').'</th>'.
                   10692:                    &end_data_table_header_row().
                   10693:                    $duplicates.
                   10694:                    &end_data_table().
                   10695:                    '</p>';
                   10696:     }
1.1067    raeburn  10697:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  10698:     if (ref($hiddenelements) eq 'HASH') {
                   10699:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   10700:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   10701:         }
                   10702:     }
                   10703:     $output .= <<"END";
1.1067    raeburn  10704: <br />
1.1053    raeburn  10705: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   10706: </form>
                   10707: $noextract
                   10708: END
                   10709:     return $output;
                   10710: }
                   10711: 
1.1065    raeburn  10712: sub decompression_utility {
                   10713:     my ($program) = @_;
                   10714:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   10715:     my $location;
                   10716:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   10717:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   10718:                          '/usr/sbin/') {
                   10719:             if (-x $dir.$program) {
                   10720:                 $location = $dir.$program;
                   10721:                 last;
                   10722:             }
                   10723:         }
                   10724:     }
                   10725:     return $location;
                   10726: }
                   10727: 
                   10728: sub list_archive_contents {
                   10729:     my ($file,$pathsref) = @_;
                   10730:     my (@cmd,$output);
                   10731:     my $needsregexp;
                   10732:     if ($file =~ /\.zip$/) {
                   10733:         @cmd = (&decompression_utility('unzip'),"-l");
                   10734:         $needsregexp = 1;
                   10735:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   10736:              ($file =~ /\.tgz$/)) {
                   10737:         @cmd = (&decompression_utility('tar'),"-ztf");
                   10738:     } elsif ($file =~ /\.tar\.bz2$/) {
                   10739:         @cmd = (&decompression_utility('tar'),"-jtf");
                   10740:     } elsif ($file =~ m|\.tar$|) {
                   10741:         @cmd = (&decompression_utility('tar'),"-tf");
                   10742:     }
                   10743:     if (@cmd) {
                   10744:         undef($!);
                   10745:         undef($@);
                   10746:         if (open(my $fh,"-|", @cmd, $file)) {
                   10747:             while (my $line = <$fh>) {
                   10748:                 $output .= $line;
                   10749:                 chomp($line);
                   10750:                 my $item;
                   10751:                 if ($needsregexp) {
                   10752:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   10753:                 } else {
                   10754:                     $item = $line;
                   10755:                 }
                   10756:                 if ($item ne '') {
                   10757:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   10758:                         push(@{$pathsref},$item);
                   10759:                     } 
                   10760:                 }
                   10761:             }
                   10762:             close($fh);
                   10763:         }
                   10764:     }
                   10765:     return $output;
                   10766: }
                   10767: 
1.1053    raeburn  10768: sub decompress_uploaded_file {
                   10769:     my ($file,$dir) = @_;
                   10770:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   10771:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   10772:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   10773:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   10774:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   10775:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   10776:     my $decompressed = $env{'cgi.decompressed'};
                   10777:     &Apache::lonnet::delenv('cgi.file');
                   10778:     &Apache::lonnet::delenv('cgi.dir');
                   10779:     &Apache::lonnet::delenv('cgi.decompressed');
                   10780:     return ($decompressed,$result);
                   10781: }
                   10782: 
1.1055    raeburn  10783: sub process_decompression {
                   10784:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   10785:     my ($dir,$error,$warning,$output);
                   10786:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
                   10787:         $error = &mt('File name not a supported archive file type.').
                   10788:                  '<br />'.&mt('File name should end with one of: [_1].',
                   10789:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   10790:     } else {
                   10791:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   10792:         if ($docuhome eq 'no_host') {
                   10793:             $error = &mt('Could not determine home server for course.');
                   10794:         } else {
                   10795:             my @ids=&Apache::lonnet::current_machine_ids();
                   10796:             my $currdir = "$dir_root/$destination";
                   10797:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   10798:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   10799:                        "$dir_root/$destination";
                   10800:             } else {
                   10801:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   10802:                        "$dir_root/$docudom/$docuname/$destination";
                   10803:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   10804:                     $error = &mt('Archive file not found.');
                   10805:                 }
                   10806:             }
1.1065    raeburn  10807:             my (@to_overwrite,@to_skip);
                   10808:             if ($env{'form.archive_overwrite_total'} > 0) {
                   10809:                 my $total = $env{'form.archive_overwrite_total'};
                   10810:                 for (my $i=0; $i<$total; $i++) {
                   10811:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   10812:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   10813:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   10814:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   10815:                     }
                   10816:                 }
                   10817:             }
                   10818:             my $numskip = scalar(@to_skip);
                   10819:             if (($numskip > 0) && 
                   10820:                 ($numskip == $env{'form.archive_itemcount'})) {
                   10821:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   10822:             } elsif ($dir eq '') {
1.1055    raeburn  10823:                 $error = &mt('Directory containing archive file unavailable.');
                   10824:             } elsif (!$error) {
1.1065    raeburn  10825:                 my ($decompressed,$display);
                   10826:                 if ($numskip > 0) {
                   10827:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   10828:                     mkdir("$dir/$tempdir",0755);
                   10829:                     system("mv $dir/$file $dir/$tempdir/$file");
                   10830:                     ($decompressed,$display) = 
                   10831:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   10832:                     foreach my $item (@to_skip) {
                   10833:                         if (($item ne '') && ($item !~ /\.\./)) {
                   10834:                             if (-f "$dir/$tempdir/$item") { 
                   10835:                                 unlink("$dir/$tempdir/$item");
                   10836:                             } elsif (-d "$dir/$tempdir/$item") {
                   10837:                                 system("rm -rf $dir/$tempdir/$item");
                   10838:                             }
                   10839:                         }
                   10840:                     }
                   10841:                     system("mv $dir/$tempdir/* $dir");
                   10842:                     rmdir("$dir/$tempdir");   
                   10843:                 } else {
                   10844:                     ($decompressed,$display) = 
                   10845:                         &decompress_uploaded_file($file,$dir);
                   10846:                 }
1.1055    raeburn  10847:                 if ($decompressed eq 'ok') {
1.1065    raeburn  10848:                     $output = '<p class="LC_info">'.
                   10849:                               &mt('Files extracted successfully from archive.').
                   10850:                               '</p>'."\n";
1.1055    raeburn  10851:                     my ($warning,$result,@contents);
                   10852:                     my ($newdirlistref,$newlisterror) =
                   10853:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   10854:                                                  $docuname,1);
                   10855:                     my (%is_dir,%changes,@newitems);
                   10856:                     my $dirptr = 16384;
1.1065    raeburn  10857:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  10858:                         foreach my $dir_line (@{$newdirlistref}) {
                   10859:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  10860:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   10861:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  10862:                                 push(@newitems,$item);
                   10863:                                 if ($dirptr&$testdir) {
                   10864:                                     $is_dir{$item} = 1;
                   10865:                                 }
                   10866:                                 $changes{$item} = 1;
                   10867:                             }
                   10868:                         }
                   10869:                     }
                   10870:                     if (keys(%changes) > 0) {
                   10871:                         foreach my $item (sort(@newitems)) {
                   10872:                             if ($changes{$item}) {
                   10873:                                 push(@contents,$item);
                   10874:                             }
                   10875:                         }
                   10876:                     }
                   10877:                     if (@contents > 0) {
1.1067    raeburn  10878:                         my $wantform;
                   10879:                         unless ($env{'form.autoextract_camtasia'}) {
                   10880:                             $wantform = 1;
                   10881:                         }
1.1056    raeburn  10882:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  10883:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   10884:                                                                 $currdir,\%is_dir,
                   10885:                                                                 \%children,\%parent,
1.1056    raeburn  10886:                                                                 \@contents,\%dirorder,
                   10887:                                                                 \%titles,$wantform);
1.1055    raeburn  10888:                         if ($datatable ne '') {
                   10889:                             $output .= &archive_options_form('decompressed',$datatable,
                   10890:                                                              $count,$hiddenelem);
1.1065    raeburn  10891:                             my $startcount = 6;
1.1055    raeburn  10892:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  10893:                                                            \%titles,\%children);
1.1055    raeburn  10894:                         }
1.1067    raeburn  10895:                         if ($env{'form.autoextract_camtasia'}) {
                   10896:                             my %displayed;
                   10897:                             my $total = 1;
                   10898:                             $env{'form.archive_directory'} = [];
                   10899:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   10900:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   10901:                                 $path =~ s{/$}{};
                   10902:                                 my $item;
                   10903:                                 if ($path ne '') {
                   10904:                                     $item = "$path/$titles{$i}";
                   10905:                                 } else {
                   10906:                                     $item = $titles{$i};
                   10907:                                 }
                   10908:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   10909:                                 if ($item eq $contents[0]) {
                   10910:                                     push(@{$env{'form.archive_directory'}},$i);
                   10911:                                     $env{'form.archive_'.$i} = 'display';
                   10912:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   10913:                                     $displayed{'folder'} = $i;
                   10914:                                 } elsif ($item eq "$contents[0]/index.html") {
                   10915:                                     $env{'form.archive_'.$i} = 'display';
                   10916:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   10917:                                     $displayed{'web'} = $i;
                   10918:                                 } else {
                   10919:                                     if ($item eq "$contents[0]/media") {
                   10920:                                         push(@{$env{'form.archive_directory'}},$i);
                   10921:                                     }
                   10922:                                     $env{'form.archive_'.$i} = 'dependency';
                   10923:                                 }
                   10924:                                 $total ++;
                   10925:                             }
                   10926:                             for (my $i=1; $i<$total; $i++) {
                   10927:                                 next if ($i == $displayed{'web'});
                   10928:                                 next if ($i == $displayed{'folder'});
                   10929:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   10930:                             }
                   10931:                             $env{'form.phase'} = 'decompress_cleanup';
                   10932:                             $env{'form.archivedelete'} = 1;
                   10933:                             $env{'form.archive_count'} = $total-1;
                   10934:                             $output .=
                   10935:                                 &process_extracted_files('coursedocs',$docudom,
                   10936:                                                          $docuname,$destination,
                   10937:                                                          $dir_root,$hiddenelem);
                   10938:                         }
1.1055    raeburn  10939:                     } else {
                   10940:                         $warning = &mt('No new items extracted from archive file.');
                   10941:                     }
                   10942:                 } else {
                   10943:                     $output = $display;
                   10944:                     $error = &mt('An error occurred during extraction from the archive file.');
                   10945:                 }
                   10946:             }
                   10947:         }
                   10948:     }
                   10949:     if ($error) {
                   10950:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   10951:                    $error.'</p>'."\n";
                   10952:     }
                   10953:     if ($warning) {
                   10954:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   10955:     }
                   10956:     return $output;
                   10957: }
                   10958: 
                   10959: sub get_extracted {
1.1056    raeburn  10960:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   10961:         $titles,$wantform) = @_;
1.1055    raeburn  10962:     my $count = 0;
                   10963:     my $depth = 0;
                   10964:     my $datatable;
1.1056    raeburn  10965:     my @hierarchy;
1.1055    raeburn  10966:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  10967:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   10968:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  10969:     foreach my $item (@{$contents}) {
                   10970:         $count ++;
1.1056    raeburn  10971:         @{$dirorder->{$count}} = @hierarchy;
                   10972:         $titles->{$count} = $item;
1.1055    raeburn  10973:         &archive_hierarchy($depth,$count,$parent,$children);
                   10974:         if ($wantform) {
                   10975:             $datatable .= &archive_row($is_dir->{$item},$item,
                   10976:                                        $currdir,$depth,$count);
                   10977:         }
                   10978:         if ($is_dir->{$item}) {
                   10979:             $depth ++;
1.1056    raeburn  10980:             push(@hierarchy,$count);
                   10981:             $parent->{$depth} = $count;
1.1055    raeburn  10982:             $datatable .=
                   10983:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  10984:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   10985:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  10986:             $depth --;
1.1056    raeburn  10987:             pop(@hierarchy);
1.1055    raeburn  10988:         }
                   10989:     }
                   10990:     return ($count,$datatable);
                   10991: }
                   10992: 
                   10993: sub recurse_extracted_archive {
1.1056    raeburn  10994:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   10995:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  10996:     my $result='';
1.1056    raeburn  10997:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   10998:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   10999:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11000:         return $result;
                   11001:     }
                   11002:     my $dirptr = 16384;
                   11003:     my ($newdirlistref,$newlisterror) =
                   11004:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11005:     if (ref($newdirlistref) eq 'ARRAY') {
                   11006:         foreach my $dir_line (@{$newdirlistref}) {
                   11007:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11008:             unless ($item =~ /^\.+$/) {
                   11009:                 $$count ++;
1.1056    raeburn  11010:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11011:                 $titles->{$$count} = $item;
1.1055    raeburn  11012:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11013: 
1.1055    raeburn  11014:                 my $is_dir;
                   11015:                 if ($dirptr&$testdir) {
                   11016:                     $is_dir = 1;
                   11017:                 }
                   11018:                 if ($wantform) {
                   11019:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11020:                 }
                   11021:                 if ($is_dir) {
                   11022:                     $$depth ++;
1.1056    raeburn  11023:                     push(@{$hierarchy},$$count);
                   11024:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11025:                     $result .=
                   11026:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11027:                                                    $docuname,$depth,$count,
1.1056    raeburn  11028:                                                    $hierarchy,$dirorder,$children,
                   11029:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11030:                     $$depth --;
1.1056    raeburn  11031:                     pop(@{$hierarchy});
1.1055    raeburn  11032:                 }
                   11033:             }
                   11034:         }
                   11035:     }
                   11036:     return $result;
                   11037: }
                   11038: 
                   11039: sub archive_hierarchy {
                   11040:     my ($depth,$count,$parent,$children) =@_;
                   11041:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11042:         if (exists($parent->{$depth})) {
                   11043:              $children->{$parent->{$depth}} .= $count.':';
                   11044:         }
                   11045:     }
                   11046:     return;
                   11047: }
                   11048: 
                   11049: sub archive_row {
                   11050:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11051:     my ($name) = ($item =~ m{([^/]+)$});
                   11052:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11053:                                        'display'    => 'Add as file',
1.1055    raeburn  11054:                                        'dependency' => 'Include as dependency',
                   11055:                                        'discard'    => 'Discard',
                   11056:                                       );
                   11057:     if ($is_dir) {
1.1059    raeburn  11058:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11059:     }
1.1056    raeburn  11060:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11061:     my $offset = 0;
1.1055    raeburn  11062:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11063:         $offset ++;
1.1065    raeburn  11064:         if ($action ne 'display') {
                   11065:             $offset ++;
                   11066:         }  
1.1055    raeburn  11067:         $output .= '<td><span class="LC_nobreak">'.
                   11068:                    '<label><input type="radio" name="archive_'.$count.
                   11069:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11070:         my $text = $choices{$action};
                   11071:         if ($is_dir) {
                   11072:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11073:             if ($action eq 'display') {
1.1059    raeburn  11074:                 $text = &mt('Add as folder');
1.1055    raeburn  11075:             }
1.1056    raeburn  11076:         } else {
                   11077:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11078: 
                   11079:         }
                   11080:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11081:         if ($action eq 'dependency') {
                   11082:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11083:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11084:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11085:                        '<option value=""></option>'."\n".
                   11086:                        '</select>'."\n".
                   11087:                        '</div>';
1.1059    raeburn  11088:         } elsif ($action eq 'display') {
                   11089:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11090:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11091:                        '</div>';
1.1055    raeburn  11092:         }
1.1056    raeburn  11093:         $output .= '</td>';
1.1055    raeburn  11094:     }
                   11095:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11096:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11097:     for (my $i=0; $i<$depth; $i++) {
                   11098:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11099:     }
                   11100:     if ($is_dir) {
                   11101:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11102:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11103:     } else {
                   11104:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11105:     }
                   11106:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11107:                &end_data_table_row();
                   11108:     return $output;
                   11109: }
                   11110: 
                   11111: sub archive_options_form {
1.1065    raeburn  11112:     my ($form,$display,$count,$hiddenelem) = @_;
                   11113:     my %lt = &Apache::lonlocal::texthash(
                   11114:                perm => 'Permanently remove archive file?',
                   11115:                hows => 'How should each extracted item be incorporated in the course?',
                   11116:                cont => 'Content actions for all',
                   11117:                addf => 'Add as folder/file',
                   11118:                incd => 'Include as dependency for a displayed file',
                   11119:                disc => 'Discard',
                   11120:                no   => 'No',
                   11121:                yes  => 'Yes',
                   11122:                save => 'Save',
                   11123:     );
                   11124:     my $output = <<"END";
                   11125: <form name="$form" method="post" action="">
                   11126: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11127: <label>
                   11128:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11129: </label>
                   11130: &nbsp;
                   11131: <label>
                   11132:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11133: </span>
                   11134: </p>
                   11135: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11136: <br />$lt{'hows'}
                   11137: <div class="LC_columnSection">
                   11138:   <fieldset>
                   11139:     <legend>$lt{'cont'}</legend>
                   11140:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11141:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11142:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11143:   </fieldset>
                   11144: </div>
                   11145: END
                   11146:     return $output.
1.1055    raeburn  11147:            &start_data_table()."\n".
1.1065    raeburn  11148:            $display."\n".
1.1055    raeburn  11149:            &end_data_table()."\n".
                   11150:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11151:            $hiddenelem.
1.1065    raeburn  11152:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11153:            '</form>';
                   11154: }
                   11155: 
                   11156: sub archive_javascript {
1.1056    raeburn  11157:     my ($startcount,$numitems,$titles,$children) = @_;
                   11158:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11159:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11160:     my $scripttag = <<START;
                   11161: <script type="text/javascript">
                   11162: // <![CDATA[
                   11163: 
                   11164: function checkAll(form,prefix) {
                   11165:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11166:     for (var i=0; i < form.elements.length; i++) {
                   11167:         var id = form.elements[i].id;
                   11168:         if ((id != '') && (id != undefined)) {
                   11169:             if (idstr.test(id)) {
                   11170:                 if (form.elements[i].type == 'radio') {
                   11171:                     form.elements[i].checked = true;
1.1056    raeburn  11172:                     var nostart = i-$startcount;
1.1059    raeburn  11173:                     var offset = nostart%7;
                   11174:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11175:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11176:                 }
                   11177:             }
                   11178:         }
                   11179:     }
                   11180: }
                   11181: 
                   11182: function propagateCheck(form,count) {
                   11183:     if (count > 0) {
1.1059    raeburn  11184:         var startelement = $startcount + ((count-1) * 7);
                   11185:         for (var j=1; j<6; j++) {
                   11186:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11187:                 var item = startelement + j; 
                   11188:                 if (form.elements[item].type == 'radio') {
                   11189:                     if (form.elements[item].checked) {
                   11190:                         containerCheck(form,count,j);
                   11191:                         break;
                   11192:                     }
1.1055    raeburn  11193:                 }
                   11194:             }
                   11195:         }
                   11196:     }
                   11197: }
                   11198: 
                   11199: numitems = $numitems
1.1056    raeburn  11200: var titles = new Array(numitems);
                   11201: var parents = new Array(numitems);
1.1055    raeburn  11202: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11203:     parents[i] = new Array;
1.1055    raeburn  11204: }
1.1059    raeburn  11205: var maintitle = '$maintitle';
1.1055    raeburn  11206: 
                   11207: START
                   11208: 
1.1056    raeburn  11209:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11210:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11211:         for (my $i=0; $i<@contents; $i ++) {
                   11212:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11213:         }
                   11214:     }
                   11215: 
1.1056    raeburn  11216:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11217:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11218:     }
                   11219: 
1.1055    raeburn  11220:     $scripttag .= <<END;
                   11221: 
                   11222: function containerCheck(form,count,offset) {
                   11223:     if (count > 0) {
1.1056    raeburn  11224:         dependencyCheck(form,count,offset);
1.1059    raeburn  11225:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11226:         form.elements[item].checked = true;
                   11227:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11228:             if (parents[count].length > 0) {
                   11229:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11230:                     containerCheck(form,parents[count][j],offset);
                   11231:                 }
                   11232:             }
                   11233:         }
                   11234:     }
                   11235: }
                   11236: 
                   11237: function dependencyCheck(form,count,offset) {
                   11238:     if (count > 0) {
1.1059    raeburn  11239:         var chosen = (offset+$startcount)+7*(count-1);
                   11240:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11241:         var currtype = form.elements[depitem].type;
                   11242:         if (form.elements[chosen].value == 'dependency') {
                   11243:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11244:             form.elements[depitem].options.length = 0;
                   11245:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  11246:             for (var i=1; i<=numitems; i++) {
                   11247:                 if (i == count) {
                   11248:                     continue;
                   11249:                 }
1.1059    raeburn  11250:                 var startelement = $startcount + (i-1) * 7;
                   11251:                 for (var j=1; j<6; j++) {
                   11252:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11253:                         var item = startelement + j;
                   11254:                         if (form.elements[item].type == 'radio') {
                   11255:                             if (form.elements[item].checked) {
                   11256:                                 if (form.elements[item].value == 'display') {
                   11257:                                     var n = form.elements[depitem].options.length;
                   11258:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11259:                                 }
                   11260:                             }
                   11261:                         }
                   11262:                     }
                   11263:                 }
                   11264:             }
                   11265:         } else {
                   11266:             document.getElementById('arc_depon_'+count).style.display='none';
                   11267:             form.elements[depitem].options.length = 0;
                   11268:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11269:         }
1.1059    raeburn  11270:         titleCheck(form,count,offset);
1.1056    raeburn  11271:     }
                   11272: }
                   11273: 
                   11274: function propagateSelect(form,count,offset) {
                   11275:     if (count > 0) {
1.1065    raeburn  11276:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11277:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11278:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11279:             if (parents[count].length > 0) {
                   11280:                 for (var j=0; j<parents[count].length; j++) {
                   11281:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11282:                 }
                   11283:             }
                   11284:         }
                   11285:     }
                   11286: }
1.1056    raeburn  11287: 
                   11288: function containerSelect(form,count,offset,picked) {
                   11289:     if (count > 0) {
1.1065    raeburn  11290:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11291:         if (form.elements[item].type == 'radio') {
                   11292:             if (form.elements[item].value == 'dependency') {
                   11293:                 if (form.elements[item+1].type == 'select-one') {
                   11294:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11295:                         if (form.elements[item+1].options[i].value == picked) {
                   11296:                             form.elements[item+1].selectedIndex = i;
                   11297:                             break;
                   11298:                         }
                   11299:                     }
                   11300:                 }
                   11301:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11302:                     if (parents[count].length > 0) {
                   11303:                         for (var j=0; j<parents[count].length; j++) {
                   11304:                             containerSelect(form,parents[count][j],offset,picked);
                   11305:                         }
                   11306:                     }
                   11307:                 }
                   11308:             }
                   11309:         }
                   11310:     }
                   11311: }
                   11312: 
1.1059    raeburn  11313: function titleCheck(form,count,offset) {
                   11314:     if (count > 0) {
                   11315:         var chosen = (offset+$startcount)+7*(count-1);
                   11316:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11317:         var currtype = form.elements[depitem].type;
                   11318:         if (form.elements[chosen].value == 'display') {
                   11319:             document.getElementById('arc_title_'+count).style.display='block';
                   11320:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11321:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11322:             }
                   11323:         } else {
                   11324:             document.getElementById('arc_title_'+count).style.display='none';
                   11325:             if (currtype == 'text') { 
                   11326:                 document.getElementById('archive_title_'+count).value='';
                   11327:             }
                   11328:         }
                   11329:     }
                   11330:     return;
                   11331: }
                   11332: 
1.1055    raeburn  11333: // ]]>
                   11334: </script>
                   11335: END
                   11336:     return $scripttag;
                   11337: }
                   11338: 
                   11339: sub process_extracted_files {
1.1067    raeburn  11340:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11341:     my $numitems = $env{'form.archive_count'};
                   11342:     return unless ($numitems);
                   11343:     my @ids=&Apache::lonnet::current_machine_ids();
                   11344:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11345:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11346:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11347:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11348:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11349:         $pathtocheck = "$dir_root/$destination";
                   11350:         $dir = $dir_root;
                   11351:         $ishome = 1;
                   11352:     } else {
                   11353:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11354:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11355:         $dir = "$dir_root/$docudom/$docuname";    
                   11356:     }
                   11357:     my $currdir = "$dir_root/$destination";
                   11358:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11359:     if ($env{'form.folderpath'}) {
                   11360:         my @items = split('&',$env{'form.folderpath'});
                   11361:         $folders{'0'} = $items[-2];
1.1099    raeburn  11362:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11363:             $containers{'0'}='page';
                   11364:         } else {  
                   11365:             $containers{'0'}='sequence';
                   11366:         }
1.1055    raeburn  11367:     }
                   11368:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11369:     if ($numitems) {
                   11370:         for (my $i=1; $i<=$numitems; $i++) {
                   11371:             my $path = $env{'form.archive_content_'.$i};
                   11372:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11373:                 my $item = $1;
                   11374:                 $toplevelitems{$item} = $i;
                   11375:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11376:                     $is_dir{$item} = 1;
                   11377:                 }
                   11378:             }
                   11379:         }
                   11380:     }
1.1067    raeburn  11381:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11382:     if (keys(%toplevelitems) > 0) {
                   11383:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11384:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11385:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11386:     }
1.1066    raeburn  11387:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11388:     if ($numitems) {
                   11389:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  11390:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11391:             my $path = $env{'form.archive_content_'.$i};
                   11392:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11393:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11394:                     if ($prefix ne '' && $path ne '') {
                   11395:                         if (-e $prefix.$path) {
1.1066    raeburn  11396:                             if ((@archdirs > 0) && 
                   11397:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11398:                                 $todeletedir{$prefix.$path} = 1;
                   11399:                             } else {
                   11400:                                 $todelete{$prefix.$path} = 1;
                   11401:                             }
1.1055    raeburn  11402:                         }
                   11403:                     }
                   11404:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11405:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11406:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11407:                     $docstitle = $env{'form.archive_title_'.$i};
                   11408:                     if ($docstitle eq '') {
                   11409:                         $docstitle = $title;
                   11410:                     }
1.1055    raeburn  11411:                     $outer = 0;
1.1056    raeburn  11412:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11413:                         if (@{$dirorder{$i}} > 0) {
                   11414:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11415:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11416:                                     $outer = $item;
                   11417:                                     last;
                   11418:                                 }
                   11419:                             }
                   11420:                         }
                   11421:                     }
                   11422:                     my ($errtext,$fatal) = 
                   11423:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11424:                                                '/'.$folders{$outer}.'.'.
                   11425:                                                $containers{$outer});
                   11426:                     next if ($fatal);
                   11427:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11428:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11429:                             $mapinner{$i} = time;
1.1055    raeburn  11430:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11431:                             $containers{$i} = 'sequence';
                   11432:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11433:                                       $folders{$i}.'.'.$containers{$i};
                   11434:                             my $newidx = &LONCAPA::map::getresidx();
                   11435:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11436:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11437:                             push(@LONCAPA::map::order,$newidx);
                   11438:                             my ($outtext,$errtext) =
                   11439:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11440:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11441:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11442:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11443:                             unless ($errtext) {
                   11444:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11445:                             }
1.1055    raeburn  11446:                         }
                   11447:                     } else {
                   11448:                         if ($context eq 'coursedocs') {
                   11449:                             my $newidx=&LONCAPA::map::getresidx();
                   11450:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11451:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11452:                                       $title;
                   11453:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11454:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11455:                             }
                   11456:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11457:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11458:                             }
                   11459:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11460:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11461:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11462:                                 unless ($ishome) {
                   11463:                                     my $fetch = "$newdest{$i}/$title";
                   11464:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11465:                                     $prompttofetch{$fetch} = 1;
                   11466:                                 }
1.1055    raeburn  11467:                             }
                   11468:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11469:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11470:                             push(@LONCAPA::map::order, $newidx);
                   11471:                             my ($outtext,$errtext)=
                   11472:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11473:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11474:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11475:                             unless ($errtext) {
                   11476:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11477:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11478:                                 }
                   11479:                             }
1.1055    raeburn  11480:                         }
                   11481:                     }
1.1086    raeburn  11482:                 }
                   11483:             } else {
                   11484:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11485:             }
                   11486:         }
                   11487:         for (my $i=1; $i<=$numitems; $i++) {
                   11488:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11489:             my $path = $env{'form.archive_content_'.$i};
                   11490:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11491:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11492:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11493:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11494:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11495:                         my ($itemidx,$fullpath,$relpath);
                   11496:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11497:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11498:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  11499:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11500:                                     $itemidx = $j;
1.1056    raeburn  11501:                                 }
                   11502:                             }
1.1086    raeburn  11503:                         }
                   11504:                         if ($itemidx eq '') {
                   11505:                             $itemidx =  0;
                   11506:                         } 
                   11507:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11508:                             if ($mapinner{$referrer{$i}}) {
                   11509:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11510:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11511:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11512:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11513:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11514:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11515:                                             if (!-e $fullpath) {
                   11516:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11517:                                             }
                   11518:                                         }
1.1086    raeburn  11519:                                     } else {
                   11520:                                         last;
1.1056    raeburn  11521:                                     }
1.1086    raeburn  11522:                                 }
                   11523:                             }
                   11524:                         } elsif ($newdest{$referrer{$i}}) {
                   11525:                             $fullpath = $newdest{$referrer{$i}};
                   11526:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11527:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11528:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11529:                                     last;
                   11530:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11531:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11532:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11533:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11534:                                         if (!-e $fullpath) {
                   11535:                                             mkdir($fullpath,0755);
1.1056    raeburn  11536:                                         }
                   11537:                                     }
1.1086    raeburn  11538:                                 } else {
                   11539:                                     last;
1.1056    raeburn  11540:                                 }
1.1055    raeburn  11541:                             }
                   11542:                         }
1.1086    raeburn  11543:                         if ($fullpath ne '') {
                   11544:                             if (-e "$prefix$path") {
                   11545:                                 system("mv $prefix$path $fullpath/$title");
                   11546:                             }
                   11547:                             if (-e "$fullpath/$title") {
                   11548:                                 my $showpath;
                   11549:                                 if ($relpath ne '') {
                   11550:                                     $showpath = "$relpath/$title";
                   11551:                                 } else {
                   11552:                                     $showpath = "/$title";
                   11553:                                 } 
                   11554:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   11555:                             } 
                   11556:                             unless ($ishome) {
                   11557:                                 my $fetch = "$fullpath/$title";
                   11558:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   11559:                                 $prompttofetch{$fetch} = 1;
                   11560:                             }
                   11561:                         }
1.1055    raeburn  11562:                     }
1.1086    raeburn  11563:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   11564:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   11565:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  11566:                 }
                   11567:             } else {
                   11568:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11569:             }
                   11570:         }
                   11571:         if (keys(%todelete)) {
                   11572:             foreach my $key (keys(%todelete)) {
                   11573:                 unlink($key);
1.1066    raeburn  11574:             }
                   11575:         }
                   11576:         if (keys(%todeletedir)) {
                   11577:             foreach my $key (keys(%todeletedir)) {
                   11578:                 rmdir($key);
                   11579:             }
                   11580:         }
                   11581:         foreach my $dir (sort(keys(%is_dir))) {
                   11582:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   11583:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  11584:             }
                   11585:         }
1.1067    raeburn  11586:         if ($result ne '') {
                   11587:             $output .= '<ul>'."\n".
                   11588:                        $result."\n".
                   11589:                        '</ul>';
                   11590:         }
                   11591:         unless ($ishome) {
                   11592:             my $replicationfail;
                   11593:             foreach my $item (keys(%prompttofetch)) {
                   11594:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   11595:                 unless ($fetchresult eq 'ok') {
                   11596:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   11597:                 }
                   11598:             }
                   11599:             if ($replicationfail) {
                   11600:                 $output .= '<p class="LC_error">'.
                   11601:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   11602:                            $replicationfail.
                   11603:                            '</ul></p>';
                   11604:             }
                   11605:         }
1.1055    raeburn  11606:     } else {
                   11607:         $warning = &mt('No items found in archive.');
                   11608:     }
                   11609:     if ($error) {
                   11610:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11611:                    $error.'</p>'."\n";
                   11612:     }
                   11613:     if ($warning) {
                   11614:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11615:     }
                   11616:     return $output;
                   11617: }
                   11618: 
1.1066    raeburn  11619: sub cleanup_empty_dirs {
                   11620:     my ($path) = @_;
                   11621:     if (($path ne '') && (-d $path)) {
                   11622:         if (opendir(my $dirh,$path)) {
                   11623:             my @dircontents = grep(!/^\./,readdir($dirh));
                   11624:             my $numitems = 0;
                   11625:             foreach my $item (@dircontents) {
                   11626:                 if (-d "$path/$item") {
                   11627:                     &recurse_dirs("$path/$item");
                   11628:                     if (-e "$path/$item") {
                   11629:                         $numitems ++;
                   11630:                     }
                   11631:                 } else {
                   11632:                     $numitems ++;
                   11633:                 }
                   11634:             }
                   11635:             if ($numitems == 0) {
                   11636:                 rmdir($path);
                   11637:             }
                   11638:             closedir($dirh);
                   11639:         }
                   11640:     }
                   11641:     return;
                   11642: }
                   11643: 
1.41      ng       11644: =pod
1.45      matthew  11645: 
1.1068    raeburn  11646: =item &get_folder_hierarchy()
                   11647: 
                   11648: Provides hierarchy of names of folders/sub-folders containing the current
                   11649: item,
                   11650: 
                   11651: Inputs: 3
                   11652:      - $navmap - navmaps object
                   11653: 
                   11654:      - $map - url for map (either the trigger itself, or map containing
                   11655:                            the resource, which is the trigger).
                   11656: 
                   11657:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   11658: 
                   11659: Outputs: 1 @pathitems - array of folder/subfolder names.
                   11660: 
                   11661: =cut
                   11662: 
                   11663: sub get_folder_hierarchy {
                   11664:     my ($navmap,$map,$showitem) = @_;
                   11665:     my @pathitems;
                   11666:     if (ref($navmap)) {
                   11667:         my $mapres = $navmap->getResourceByUrl($map);
                   11668:         if (ref($mapres)) {
                   11669:             my $pcslist = $mapres->map_hierarchy();
                   11670:             if ($pcslist ne '') {
                   11671:                 my @pcs = split(/,/,$pcslist);
                   11672:                 foreach my $pc (@pcs) {
                   11673:                     if ($pc == 1) {
                   11674:                         push(@pathitems,&mt('Main Course Documents'));
                   11675:                     } else {
                   11676:                         my $res = $navmap->getByMapPc($pc);
                   11677:                         if (ref($res)) {
                   11678:                             my $title = $res->compTitle();
                   11679:                             $title =~ s/\W+/_/g;
                   11680:                             if ($title ne '') {
                   11681:                                 push(@pathitems,$title);
                   11682:                             }
                   11683:                         }
                   11684:                     }
                   11685:                 }
                   11686:             }
1.1071    raeburn  11687:             if ($showitem) {
                   11688:                 if ($mapres->{ID} eq '0.0') {
                   11689:                     push(@pathitems,&mt('Main Course Documents'));
                   11690:                 } else {
                   11691:                     my $maptitle = $mapres->compTitle();
                   11692:                     $maptitle =~ s/\W+/_/g;
                   11693:                     if ($maptitle ne '') {
                   11694:                         push(@pathitems,$maptitle);
                   11695:                     }
1.1068    raeburn  11696:                 }
                   11697:             }
                   11698:         }
                   11699:     }
                   11700:     return @pathitems;
                   11701: }
                   11702: 
                   11703: =pod
                   11704: 
1.1015    raeburn  11705: =item * &get_turnedin_filepath()
                   11706: 
                   11707: Determines path in a user's portfolio file for storage of files uploaded
                   11708: to a specific essayresponse or dropbox item.
                   11709: 
                   11710: Inputs: 3 required + 1 optional.
                   11711: $symb is symb for resource, $uname and $udom are for current user (required).
                   11712: $caller is optional (can be "submission", if routine is called when storing
                   11713: an upoaded file when "Submit Answer" button was pressed).
                   11714: 
                   11715: Returns array containing $path and $multiresp. 
                   11716: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   11717: than one file upload item.  Callers of routine should append partid as a 
                   11718: subdirectory to $path in cases where $multiresp is 1.
                   11719: 
                   11720: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   11721: 
                   11722: =cut
                   11723: 
                   11724: sub get_turnedin_filepath {
                   11725:     my ($symb,$uname,$udom,$caller) = @_;
                   11726:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   11727:     my $turnindir;
                   11728:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   11729:     $turnindir = $userhash{'turnindir'};
                   11730:     my ($path,$multiresp);
                   11731:     if ($turnindir eq '') {
                   11732:         if ($caller eq 'submission') {
                   11733:             $turnindir = &mt('turned in');
                   11734:             $turnindir =~ s/\W+/_/g;
                   11735:             my %newhash = (
                   11736:                             'turnindir' => $turnindir,
                   11737:                           );
                   11738:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   11739:         }
                   11740:     }
                   11741:     if ($turnindir ne '') {
                   11742:         $path = '/'.$turnindir.'/';
                   11743:         my ($multipart,$turnin,@pathitems);
                   11744:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11745:         if (defined($navmap)) {
                   11746:             my $mapres = $navmap->getResourceByUrl($map);
                   11747:             if (ref($mapres)) {
                   11748:                 my $pcslist = $mapres->map_hierarchy();
                   11749:                 if ($pcslist ne '') {
                   11750:                     foreach my $pc (split(/,/,$pcslist)) {
                   11751:                         my $res = $navmap->getByMapPc($pc);
                   11752:                         if (ref($res)) {
                   11753:                             my $title = $res->compTitle();
                   11754:                             $title =~ s/\W+/_/g;
                   11755:                             if ($title ne '') {
                   11756:                                 push(@pathitems,$title);
                   11757:                             }
                   11758:                         }
                   11759:                     }
                   11760:                 }
                   11761:                 my $maptitle = $mapres->compTitle();
                   11762:                 $maptitle =~ s/\W+/_/g;
                   11763:                 if ($maptitle ne '') {
                   11764:                     push(@pathitems,$maptitle);
                   11765:                 }
                   11766:                 unless ($env{'request.state'} eq 'construct') {
                   11767:                     my $res = $navmap->getBySymb($symb);
                   11768:                     if (ref($res)) {
                   11769:                         my $partlist = $res->parts();
                   11770:                         my $totaluploads = 0;
                   11771:                         if (ref($partlist) eq 'ARRAY') {
                   11772:                             foreach my $part (@{$partlist}) {
                   11773:                                 my @types = $res->responseType($part);
                   11774:                                 my @ids = $res->responseIds($part);
                   11775:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   11776:                                     if ($types[$i] eq 'essay') {
                   11777:                                         my $partid = $part.'_'.$ids[$i];
                   11778:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   11779:                                             $totaluploads ++;
                   11780:                                         }
                   11781:                                     }
                   11782:                                 }
                   11783:                             }
                   11784:                             if ($totaluploads > 1) {
                   11785:                                 $multiresp = 1;
                   11786:                             }
                   11787:                         }
                   11788:                     }
                   11789:                 }
                   11790:             } else {
                   11791:                 return;
                   11792:             }
                   11793:         } else {
                   11794:             return;
                   11795:         }
                   11796:         my $restitle=&Apache::lonnet::gettitle($symb);
                   11797:         $restitle =~ s/\W+/_/g;
                   11798:         if ($restitle eq '') {
                   11799:             $restitle = ($resurl =~ m{/[^/]+$});
                   11800:             if ($restitle eq '') {
                   11801:                 $restitle = time;
                   11802:             }
                   11803:         }
                   11804:         push(@pathitems,$restitle);
                   11805:         $path .= join('/',@pathitems);
                   11806:     }
                   11807:     return ($path,$multiresp);
                   11808: }
                   11809: 
                   11810: =pod
                   11811: 
1.464     albertel 11812: =back
1.41      ng       11813: 
1.112     bowersj2 11814: =head1 CSV Upload/Handling functions
1.38      albertel 11815: 
1.41      ng       11816: =over 4
                   11817: 
1.648     raeburn  11818: =item * &upfile_store($r)
1.41      ng       11819: 
                   11820: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 11821: needs $env{'form.upfile'}
1.41      ng       11822: returns $datatoken to be put into hidden field
                   11823: 
                   11824: =cut
1.31      albertel 11825: 
                   11826: sub upfile_store {
                   11827:     my $r=shift;
1.258     albertel 11828:     $env{'form.upfile'}=~s/\r/\n/gs;
                   11829:     $env{'form.upfile'}=~s/\f/\n/gs;
                   11830:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   11831:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 11832: 
1.258     albertel 11833:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   11834: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 11835:     {
1.158     raeburn  11836:         my $datafile = $r->dir_config('lonDaemons').
                   11837:                            '/tmp/'.$datatoken.'.tmp';
                   11838:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 11839:             print $fh $env{'form.upfile'};
1.158     raeburn  11840:             close($fh);
                   11841:         }
1.31      albertel 11842:     }
                   11843:     return $datatoken;
                   11844: }
                   11845: 
1.56      matthew  11846: =pod
                   11847: 
1.648     raeburn  11848: =item * &load_tmp_file($r)
1.41      ng       11849: 
                   11850: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 11851: needs $env{'form.datatoken'},
                   11852: sets $env{'form.upfile'} to the contents of the file
1.41      ng       11853: 
                   11854: =cut
1.31      albertel 11855: 
                   11856: sub load_tmp_file {
                   11857:     my $r=shift;
                   11858:     my @studentdata=();
                   11859:     {
1.158     raeburn  11860:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 11861:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  11862:         if ( open(my $fh,"<$studentfile") ) {
                   11863:             @studentdata=<$fh>;
                   11864:             close($fh);
                   11865:         }
1.31      albertel 11866:     }
1.258     albertel 11867:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 11868: }
                   11869: 
1.56      matthew  11870: =pod
                   11871: 
1.648     raeburn  11872: =item * &upfile_record_sep()
1.41      ng       11873: 
                   11874: Separate uploaded file into records
                   11875: returns array of records,
1.258     albertel 11876: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       11877: 
                   11878: =cut
1.31      albertel 11879: 
                   11880: sub upfile_record_sep {
1.258     albertel 11881:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 11882:     } else {
1.248     albertel 11883: 	my @records;
1.258     albertel 11884: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 11885: 	    if ($line=~/^\s*$/) { next; }
                   11886: 	    push(@records,$line);
                   11887: 	}
                   11888: 	return @records;
1.31      albertel 11889:     }
                   11890: }
                   11891: 
1.56      matthew  11892: =pod
                   11893: 
1.648     raeburn  11894: =item * &record_sep($record)
1.41      ng       11895: 
1.258     albertel 11896: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       11897: 
                   11898: =cut
                   11899: 
1.263     www      11900: sub takeleft {
                   11901:     my $index=shift;
                   11902:     return substr('0000'.$index,-4,4);
                   11903: }
                   11904: 
1.31      albertel 11905: sub record_sep {
                   11906:     my $record=shift;
                   11907:     my %components=();
1.258     albertel 11908:     if ($env{'form.upfiletype'} eq 'xml') {
                   11909:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 11910:         my $i=0;
1.356     albertel 11911:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 11912:             $field=~s/^(\"|\')//;
                   11913:             $field=~s/(\"|\')$//;
1.263     www      11914:             $components{&takeleft($i)}=$field;
1.31      albertel 11915:             $i++;
                   11916:         }
1.258     albertel 11917:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 11918:         my $i=0;
1.356     albertel 11919:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 11920:             $field=~s/^(\"|\')//;
                   11921:             $field=~s/(\"|\')$//;
1.263     www      11922:             $components{&takeleft($i)}=$field;
1.31      albertel 11923:             $i++;
                   11924:         }
                   11925:     } else {
1.561     www      11926:         my $separator=',';
1.480     banghart 11927:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      11928:             $separator=';';
1.480     banghart 11929:         }
1.31      albertel 11930:         my $i=0;
1.561     www      11931: # the character we are looking for to indicate the end of a quote or a record 
                   11932:         my $looking_for=$separator;
                   11933: # do not add the characters to the fields
                   11934:         my $ignore=0;
                   11935: # we just encountered a separator (or the beginning of the record)
                   11936:         my $just_found_separator=1;
                   11937: # store the field we are working on here
                   11938:         my $field='';
                   11939: # work our way through all characters in record
                   11940:         foreach my $character ($record=~/(.)/g) {
                   11941:             if ($character eq $looking_for) {
                   11942:                if ($character ne $separator) {
                   11943: # Found the end of a quote, again looking for separator
                   11944:                   $looking_for=$separator;
                   11945:                   $ignore=1;
                   11946:                } else {
                   11947: # Found a separator, store away what we got
                   11948:                   $components{&takeleft($i)}=$field;
                   11949: 	          $i++;
                   11950:                   $just_found_separator=1;
                   11951:                   $ignore=0;
                   11952:                   $field='';
                   11953:                }
                   11954:                next;
                   11955:             }
                   11956: # single or double quotation marks after a separator indicate beginning of a quote
                   11957: # we are now looking for the end of the quote and need to ignore separators
                   11958:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   11959:                $looking_for=$character;
                   11960:                next;
                   11961:             }
                   11962: # ignore would be true after we reached the end of a quote
                   11963:             if ($ignore) { next; }
                   11964:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   11965:             $field.=$character;
                   11966:             $just_found_separator=0; 
1.31      albertel 11967:         }
1.561     www      11968: # catch the very last entry, since we never encountered the separator
                   11969:         $components{&takeleft($i)}=$field;
1.31      albertel 11970:     }
                   11971:     return %components;
                   11972: }
                   11973: 
1.144     matthew  11974: ######################################################
                   11975: ######################################################
                   11976: 
1.56      matthew  11977: =pod
                   11978: 
1.648     raeburn  11979: =item * &upfile_select_html()
1.41      ng       11980: 
1.144     matthew  11981: Return HTML code to select a file from the users machine and specify 
                   11982: the file type.
1.41      ng       11983: 
                   11984: =cut
                   11985: 
1.144     matthew  11986: ######################################################
                   11987: ######################################################
1.31      albertel 11988: sub upfile_select_html {
1.144     matthew  11989:     my %Types = (
                   11990:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 11991:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  11992:                  space => &mt('Space separated'),
                   11993:                  tab   => &mt('Tabulator separated'),
                   11994: #                 xml   => &mt('HTML/XML'),
                   11995:                  );
                   11996:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  11997:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  11998:     foreach my $type (sort(keys(%Types))) {
                   11999:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12000:     }
                   12001:     $Str .= "</select>\n";
                   12002:     return $Str;
1.31      albertel 12003: }
                   12004: 
1.301     albertel 12005: sub get_samples {
                   12006:     my ($records,$toget) = @_;
                   12007:     my @samples=({});
                   12008:     my $got=0;
                   12009:     foreach my $rec (@$records) {
                   12010: 	my %temp = &record_sep($rec);
                   12011: 	if (! grep(/\S/, values(%temp))) { next; }
                   12012: 	if (%temp) {
                   12013: 	    $samples[$got]=\%temp;
                   12014: 	    $got++;
                   12015: 	    if ($got == $toget) { last; }
                   12016: 	}
                   12017:     }
                   12018:     return \@samples;
                   12019: }
                   12020: 
1.144     matthew  12021: ######################################################
                   12022: ######################################################
                   12023: 
1.56      matthew  12024: =pod
                   12025: 
1.648     raeburn  12026: =item * &csv_print_samples($r,$records)
1.41      ng       12027: 
                   12028: Prints a table of sample values from each column uploaded $r is an
                   12029: Apache Request ref, $records is an arrayref from
                   12030: &Apache::loncommon::upfile_record_sep
                   12031: 
                   12032: =cut
                   12033: 
1.144     matthew  12034: ######################################################
                   12035: ######################################################
1.31      albertel 12036: sub csv_print_samples {
                   12037:     my ($r,$records) = @_;
1.662     bisitz   12038:     my $samples = &get_samples($records,5);
1.301     albertel 12039: 
1.594     raeburn  12040:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12041:               &start_data_table_header_row());
1.356     albertel 12042:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12043:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12044:     $r->print(&end_data_table_header_row());
1.301     albertel 12045:     foreach my $hash (@$samples) {
1.594     raeburn  12046: 	$r->print(&start_data_table_row());
1.356     albertel 12047: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12048: 	    $r->print('<td>');
1.356     albertel 12049: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12050: 	    $r->print('</td>');
                   12051: 	}
1.594     raeburn  12052: 	$r->print(&end_data_table_row());
1.31      albertel 12053:     }
1.594     raeburn  12054:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12055: }
                   12056: 
1.144     matthew  12057: ######################################################
                   12058: ######################################################
                   12059: 
1.56      matthew  12060: =pod
                   12061: 
1.648     raeburn  12062: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12063: 
                   12064: Prints a table to create associations between values and table columns.
1.144     matthew  12065: 
1.41      ng       12066: $r is an Apache Request ref,
                   12067: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12068: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12069: 
                   12070: =cut
                   12071: 
1.144     matthew  12072: ######################################################
                   12073: ######################################################
1.31      albertel 12074: sub csv_print_select_table {
                   12075:     my ($r,$records,$d) = @_;
1.301     albertel 12076:     my $i=0;
                   12077:     my $samples = &get_samples($records,1);
1.144     matthew  12078:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12079: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12080:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12081:               '<th>'.&mt('Column').'</th>'.
                   12082:               &end_data_table_header_row()."\n");
1.356     albertel 12083:     foreach my $array_ref (@$d) {
                   12084: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12085: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12086: 
1.875     bisitz   12087: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12088: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12089: 	$r->print('<option value="none"></option>');
1.356     albertel 12090: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12091: 	    $r->print('<option value="'.$sample.'"'.
                   12092:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12093:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12094: 	}
1.594     raeburn  12095: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12096: 	$i++;
                   12097:     }
1.594     raeburn  12098:     $r->print(&end_data_table());
1.31      albertel 12099:     $i--;
                   12100:     return $i;
                   12101: }
1.56      matthew  12102: 
1.144     matthew  12103: ######################################################
                   12104: ######################################################
                   12105: 
1.56      matthew  12106: =pod
1.31      albertel 12107: 
1.648     raeburn  12108: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12109: 
                   12110: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12111: 
                   12112: $r is an Apache Request ref,
                   12113: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12114: $d is an array of 2 element arrays (internal name, displayed name)
                   12115: 
                   12116: =cut
                   12117: 
1.144     matthew  12118: ######################################################
                   12119: ######################################################
1.31      albertel 12120: sub csv_samples_select_table {
                   12121:     my ($r,$records,$d) = @_;
                   12122:     my $i=0;
1.144     matthew  12123:     #
1.662     bisitz   12124:     my $max_samples = 5;
                   12125:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12126:     $r->print(&start_data_table().
                   12127:               &start_data_table_header_row().'<th>'.
                   12128:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12129:               &end_data_table_header_row());
1.301     albertel 12130: 
                   12131:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12132: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12133: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12134: 	foreach my $option (@$d) {
                   12135: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12136: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12137:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12138:                       $display.'</option>');
1.31      albertel 12139: 	}
                   12140: 	$r->print('</select></td><td>');
1.662     bisitz   12141: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12142: 	    if (defined($samples->[$line]{$key})) { 
                   12143: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12144: 	    }
                   12145: 	}
1.594     raeburn  12146: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12147: 	$i++;
                   12148:     }
1.594     raeburn  12149:     $r->print(&end_data_table());
1.31      albertel 12150:     $i--;
                   12151:     return($i);
1.115     matthew  12152: }
                   12153: 
1.144     matthew  12154: ######################################################
                   12155: ######################################################
                   12156: 
1.115     matthew  12157: =pod
                   12158: 
1.648     raeburn  12159: =item * &clean_excel_name($name)
1.115     matthew  12160: 
                   12161: Returns a replacement for $name which does not contain any illegal characters.
                   12162: 
                   12163: =cut
                   12164: 
1.144     matthew  12165: ######################################################
                   12166: ######################################################
1.115     matthew  12167: sub clean_excel_name {
                   12168:     my ($name) = @_;
                   12169:     $name =~ s/[:\*\?\/\\]//g;
                   12170:     if (length($name) > 31) {
                   12171:         $name = substr($name,0,31);
                   12172:     }
                   12173:     return $name;
1.25      albertel 12174: }
1.84      albertel 12175: 
1.85      albertel 12176: =pod
                   12177: 
1.648     raeburn  12178: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12179: 
                   12180: Returns either 1 or undef
                   12181: 
                   12182: 1 if the part is to be hidden, undef if it is to be shown
                   12183: 
                   12184: Arguments are:
                   12185: 
                   12186: $id the id of the part to be checked
                   12187: $symb, optional the symb of the resource to check
                   12188: $udom, optional the domain of the user to check for
                   12189: $uname, optional the username of the user to check for
                   12190: 
                   12191: =cut
1.84      albertel 12192: 
                   12193: sub check_if_partid_hidden {
                   12194:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12195:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12196: 					 $symb,$udom,$uname);
1.141     albertel 12197:     my $truth=1;
                   12198:     #if the string starts with !, then the list is the list to show not hide
                   12199:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12200:     my @hiddenlist=split(/,/,$hiddenparts);
                   12201:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12202: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12203:     }
1.141     albertel 12204:     return !$truth;
1.84      albertel 12205: }
1.127     matthew  12206: 
1.138     matthew  12207: 
                   12208: ############################################################
                   12209: ############################################################
                   12210: 
                   12211: =pod
                   12212: 
1.157     matthew  12213: =back 
                   12214: 
1.138     matthew  12215: =head1 cgi-bin script and graphing routines
                   12216: 
1.157     matthew  12217: =over 4
                   12218: 
1.648     raeburn  12219: =item * &get_cgi_id()
1.138     matthew  12220: 
                   12221: Inputs: none
                   12222: 
                   12223: Returns an id which can be used to pass environment variables
                   12224: to various cgi-bin scripts.  These environment variables will
                   12225: be removed from the users environment after a given time by
                   12226: the routine &Apache::lonnet::transfer_profile_to_env.
                   12227: 
                   12228: =cut
                   12229: 
                   12230: ############################################################
                   12231: ############################################################
1.152     albertel 12232: my $uniq=0;
1.136     matthew  12233: sub get_cgi_id {
1.154     albertel 12234:     $uniq=($uniq+1)%100000;
1.280     albertel 12235:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12236: }
                   12237: 
1.127     matthew  12238: ############################################################
                   12239: ############################################################
                   12240: 
                   12241: =pod
                   12242: 
1.648     raeburn  12243: =item * &DrawBarGraph()
1.127     matthew  12244: 
1.138     matthew  12245: Facilitates the plotting of data in a (stacked) bar graph.
                   12246: Puts plot definition data into the users environment in order for 
                   12247: graph.png to plot it.  Returns an <img> tag for the plot.
                   12248: The bars on the plot are labeled '1','2',...,'n'.
                   12249: 
                   12250: Inputs:
                   12251: 
                   12252: =over 4
                   12253: 
                   12254: =item $Title: string, the title of the plot
                   12255: 
                   12256: =item $xlabel: string, text describing the X-axis of the plot
                   12257: 
                   12258: =item $ylabel: string, text describing the Y-axis of the plot
                   12259: 
                   12260: =item $Max: scalar, the maximum Y value to use in the plot
                   12261: If $Max is < any data point, the graph will not be rendered.
                   12262: 
1.140     matthew  12263: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12264: they are plotted.  If undefined, default values will be used.
                   12265: 
1.178     matthew  12266: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12267: 
1.138     matthew  12268: =item @Values: An array of array references.  Each array reference holds data
                   12269: to be plotted in a stacked bar chart.
                   12270: 
1.239     matthew  12271: =item If the final element of @Values is a hash reference the key/value
                   12272: pairs will be added to the graph definition.
                   12273: 
1.138     matthew  12274: =back
                   12275: 
                   12276: Returns:
                   12277: 
                   12278: An <img> tag which references graph.png and the appropriate identifying
                   12279: information for the plot.
                   12280: 
1.127     matthew  12281: =cut
                   12282: 
                   12283: ############################################################
                   12284: ############################################################
1.134     matthew  12285: sub DrawBarGraph {
1.178     matthew  12286:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12287:     #
                   12288:     if (! defined($colors)) {
                   12289:         $colors = ['#33ff00', 
                   12290:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12291:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12292:                   ]; 
                   12293:     }
1.228     matthew  12294:     my $extra_settings = {};
                   12295:     if (ref($Values[-1]) eq 'HASH') {
                   12296:         $extra_settings = pop(@Values);
                   12297:     }
1.127     matthew  12298:     #
1.136     matthew  12299:     my $identifier = &get_cgi_id();
                   12300:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12301:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12302:         return '';
                   12303:     }
1.225     matthew  12304:     #
                   12305:     my @Labels;
                   12306:     if (defined($labels)) {
                   12307:         @Labels = @$labels;
                   12308:     } else {
                   12309:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12310:             push (@Labels,$i+1);
                   12311:         }
                   12312:     }
                   12313:     #
1.129     matthew  12314:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12315:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12316:     my %ValuesHash;
                   12317:     my $NumSets=1;
                   12318:     foreach my $array (@Values) {
                   12319:         next if (! ref($array));
1.136     matthew  12320:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12321:             join(',',@$array);
1.129     matthew  12322:     }
1.127     matthew  12323:     #
1.136     matthew  12324:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12325:     if ($NumBars < 3) {
                   12326:         $width = 120+$NumBars*32;
1.220     matthew  12327:         $xskip = 1;
1.225     matthew  12328:         $bar_width = 30;
                   12329:     } elsif ($NumBars < 5) {
                   12330:         $width = 120+$NumBars*20;
                   12331:         $xskip = 1;
                   12332:         $bar_width = 20;
1.220     matthew  12333:     } elsif ($NumBars < 10) {
1.136     matthew  12334:         $width = 120+$NumBars*15;
                   12335:         $xskip = 1;
                   12336:         $bar_width = 15;
                   12337:     } elsif ($NumBars <= 25) {
                   12338:         $width = 120+$NumBars*11;
                   12339:         $xskip = 5;
                   12340:         $bar_width = 8;
                   12341:     } elsif ($NumBars <= 50) {
                   12342:         $width = 120+$NumBars*8;
                   12343:         $xskip = 5;
                   12344:         $bar_width = 4;
                   12345:     } else {
                   12346:         $width = 120+$NumBars*8;
                   12347:         $xskip = 5;
                   12348:         $bar_width = 4;
                   12349:     }
                   12350:     #
1.137     matthew  12351:     $Max = 1 if ($Max < 1);
                   12352:     if ( int($Max) < $Max ) {
                   12353:         $Max++;
                   12354:         $Max = int($Max);
                   12355:     }
1.127     matthew  12356:     $Title  = '' if (! defined($Title));
                   12357:     $xlabel = '' if (! defined($xlabel));
                   12358:     $ylabel = '' if (! defined($ylabel));
1.369     www      12359:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12360:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12361:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12362:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12363:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12364:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12365:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12366:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12367:     $ValuesHash{$id.'.height'}   = $height;
                   12368:     $ValuesHash{$id.'.width'}    = $width;
                   12369:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12370:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12371:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12372:     #
1.228     matthew  12373:     # Deal with other parameters
                   12374:     while (my ($key,$value) = each(%$extra_settings)) {
                   12375:         $ValuesHash{$id.'.'.$key} = $value;
                   12376:     }
                   12377:     #
1.646     raeburn  12378:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12379:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12380: }
                   12381: 
                   12382: ############################################################
                   12383: ############################################################
                   12384: 
                   12385: =pod
                   12386: 
1.648     raeburn  12387: =item * &DrawXYGraph()
1.137     matthew  12388: 
1.138     matthew  12389: Facilitates the plotting of data in an XY graph.
                   12390: Puts plot definition data into the users environment in order for 
                   12391: graph.png to plot it.  Returns an <img> tag for the plot.
                   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: 
                   12406: =item $colors: Array ref containing the hex color codes for the data to be 
                   12407: plotted in.  If undefined, default values will be used.
                   12408: 
                   12409: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12410: 
                   12411: =item $Ydata: Array ref containing Array refs.  
1.185     www      12412: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12413: 
                   12414: =item %Values: hash indicating or overriding any default values which are 
                   12415: passed to graph.png.  
                   12416: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12417: 
                   12418: =back
                   12419: 
                   12420: Returns:
                   12421: 
                   12422: An <img> tag which references graph.png and the appropriate identifying
                   12423: information for the plot.
                   12424: 
1.137     matthew  12425: =cut
                   12426: 
                   12427: ############################################################
                   12428: ############################################################
                   12429: sub DrawXYGraph {
                   12430:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12431:     #
                   12432:     # Create the identifier for the graph
                   12433:     my $identifier = &get_cgi_id();
                   12434:     my $id = 'cgi.'.$identifier;
                   12435:     #
                   12436:     $Title  = '' if (! defined($Title));
                   12437:     $xlabel = '' if (! defined($xlabel));
                   12438:     $ylabel = '' if (! defined($ylabel));
                   12439:     my %ValuesHash = 
                   12440:         (
1.369     www      12441:          $id.'.title'  => &escape($Title),
                   12442:          $id.'.xlabel' => &escape($xlabel),
                   12443:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12444:          $id.'.y_max_value'=> $Max,
                   12445:          $id.'.labels'     => join(',',@$Xlabels),
                   12446:          $id.'.PlotType'   => 'XY',
                   12447:          );
                   12448:     #
                   12449:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12450:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12451:     }
                   12452:     #
                   12453:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12454:         return '';
                   12455:     }
                   12456:     my $NumSets=1;
1.138     matthew  12457:     foreach my $array (@{$Ydata}){
1.137     matthew  12458:         next if (! ref($array));
                   12459:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12460:     }
1.138     matthew  12461:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12462:     #
                   12463:     # Deal with other parameters
                   12464:     while (my ($key,$value) = each(%Values)) {
                   12465:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12466:     }
                   12467:     #
1.646     raeburn  12468:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12469:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12470: }
                   12471: 
                   12472: ############################################################
                   12473: ############################################################
                   12474: 
                   12475: =pod
                   12476: 
1.648     raeburn  12477: =item * &DrawXYYGraph()
1.138     matthew  12478: 
                   12479: Facilitates the plotting of data in an XY graph with two Y axes.
                   12480: Puts plot definition data into the users environment in order for 
                   12481: graph.png to plot it.  Returns an <img> tag for the plot.
                   12482: 
                   12483: Inputs:
                   12484: 
                   12485: =over 4
                   12486: 
                   12487: =item $Title: string, the title of the plot
                   12488: 
                   12489: =item $xlabel: string, text describing the X-axis of the plot
                   12490: 
                   12491: =item $ylabel: string, text describing the Y-axis of the plot
                   12492: 
                   12493: =item $colors: Array ref containing the hex color codes for the data to be 
                   12494: plotted in.  If undefined, default values will be used.
                   12495: 
                   12496: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12497: 
                   12498: =item $Ydata1: The first data set
                   12499: 
                   12500: =item $Min1: The minimum value of the left Y-axis
                   12501: 
                   12502: =item $Max1: The maximum value of the left Y-axis
                   12503: 
                   12504: =item $Ydata2: The second data set
                   12505: 
                   12506: =item $Min2: The minimum value of the right Y-axis
                   12507: 
                   12508: =item $Max2: The maximum value of the left Y-axis
                   12509: 
                   12510: =item %Values: hash indicating or overriding any default values which are 
                   12511: passed to graph.png.  
                   12512: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12513: 
                   12514: =back
                   12515: 
                   12516: Returns:
                   12517: 
                   12518: An <img> tag which references graph.png and the appropriate identifying
                   12519: information for the plot.
1.136     matthew  12520: 
                   12521: =cut
                   12522: 
                   12523: ############################################################
                   12524: ############################################################
1.137     matthew  12525: sub DrawXYYGraph {
                   12526:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12527:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12528:     #
                   12529:     # Create the identifier for the graph
                   12530:     my $identifier = &get_cgi_id();
                   12531:     my $id = 'cgi.'.$identifier;
                   12532:     #
                   12533:     $Title  = '' if (! defined($Title));
                   12534:     $xlabel = '' if (! defined($xlabel));
                   12535:     $ylabel = '' if (! defined($ylabel));
                   12536:     my %ValuesHash = 
                   12537:         (
1.369     www      12538:          $id.'.title'  => &escape($Title),
                   12539:          $id.'.xlabel' => &escape($xlabel),
                   12540:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  12541:          $id.'.labels' => join(',',@$Xlabels),
                   12542:          $id.'.PlotType' => 'XY',
                   12543:          $id.'.NumSets' => 2,
1.137     matthew  12544:          $id.'.two_axes' => 1,
                   12545:          $id.'.y1_max_value' => $Max1,
                   12546:          $id.'.y1_min_value' => $Min1,
                   12547:          $id.'.y2_max_value' => $Max2,
                   12548:          $id.'.y2_min_value' => $Min2,
1.136     matthew  12549:          );
                   12550:     #
1.137     matthew  12551:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12552:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12553:     }
                   12554:     #
                   12555:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   12556:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  12557:         return '';
                   12558:     }
                   12559:     my $NumSets=1;
1.137     matthew  12560:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  12561:         next if (! ref($array));
                   12562:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  12563:     }
                   12564:     #
                   12565:     # Deal with other parameters
                   12566:     while (my ($key,$value) = each(%Values)) {
                   12567:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  12568:     }
                   12569:     #
1.646     raeburn  12570:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 12571:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  12572: }
                   12573: 
                   12574: ############################################################
                   12575: ############################################################
                   12576: 
                   12577: =pod
                   12578: 
1.157     matthew  12579: =back 
                   12580: 
1.139     matthew  12581: =head1 Statistics helper routines?  
                   12582: 
                   12583: Bad place for them but what the hell.
                   12584: 
1.157     matthew  12585: =over 4
                   12586: 
1.648     raeburn  12587: =item * &chartlink()
1.139     matthew  12588: 
                   12589: Returns a link to the chart for a specific student.  
                   12590: 
                   12591: Inputs:
                   12592: 
                   12593: =over 4
                   12594: 
                   12595: =item $linktext: The text of the link
                   12596: 
                   12597: =item $sname: The students username
                   12598: 
                   12599: =item $sdomain: The students domain
                   12600: 
                   12601: =back
                   12602: 
1.157     matthew  12603: =back
                   12604: 
1.139     matthew  12605: =cut
                   12606: 
                   12607: ############################################################
                   12608: ############################################################
                   12609: sub chartlink {
                   12610:     my ($linktext, $sname, $sdomain) = @_;
                   12611:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      12612:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 12613:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  12614:        '">'.$linktext.'</a>';
1.153     matthew  12615: }
                   12616: 
                   12617: #######################################################
                   12618: #######################################################
                   12619: 
                   12620: =pod
                   12621: 
                   12622: =head1 Course Environment Routines
1.157     matthew  12623: 
                   12624: =over 4
1.153     matthew  12625: 
1.648     raeburn  12626: =item * &restore_course_settings()
1.153     matthew  12627: 
1.648     raeburn  12628: =item * &store_course_settings()
1.153     matthew  12629: 
                   12630: Restores/Store indicated form parameters from the course environment.
                   12631: Will not overwrite existing values of the form parameters.
                   12632: 
                   12633: Inputs: 
                   12634: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   12635: 
                   12636: a hash ref describing the data to be stored.  For example:
                   12637:    
                   12638: %Save_Parameters = ('Status' => 'scalar',
                   12639:     'chartoutputmode' => 'scalar',
                   12640:     'chartoutputdata' => 'scalar',
                   12641:     'Section' => 'array',
1.373     raeburn  12642:     'Group' => 'array',
1.153     matthew  12643:     'StudentData' => 'array',
                   12644:     'Maps' => 'array');
                   12645: 
                   12646: Returns: both routines return nothing
                   12647: 
1.631     raeburn  12648: =back
                   12649: 
1.153     matthew  12650: =cut
                   12651: 
                   12652: #######################################################
                   12653: #######################################################
                   12654: sub store_course_settings {
1.496     albertel 12655:     return &store_settings($env{'request.course.id'},@_);
                   12656: }
                   12657: 
                   12658: sub store_settings {
1.153     matthew  12659:     # save to the environment
                   12660:     # appenv the same items, just to be safe
1.300     albertel 12661:     my $udom  = $env{'user.domain'};
                   12662:     my $uname = $env{'user.name'};
1.496     albertel 12663:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12664:     my %SaveHash;
                   12665:     my %AppHash;
                   12666:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 12667:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 12668:         my $envname = 'environment.'.$basename;
1.258     albertel 12669:         if (exists($env{'form.'.$setting})) {
1.153     matthew  12670:             # Save this value away
                   12671:             if ($type eq 'scalar' &&
1.258     albertel 12672:                 (! exists($env{$envname}) || 
                   12673:                  $env{$envname} ne $env{'form.'.$setting})) {
                   12674:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   12675:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  12676:             } elsif ($type eq 'array') {
                   12677:                 my $stored_form;
1.258     albertel 12678:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  12679:                     $stored_form = join(',',
                   12680:                                         map {
1.369     www      12681:                                             &escape($_);
1.258     albertel 12682:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  12683:                 } else {
                   12684:                     $stored_form = 
1.369     www      12685:                         &escape($env{'form.'.$setting});
1.153     matthew  12686:                 }
                   12687:                 # Determine if the array contents are the same.
1.258     albertel 12688:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  12689:                     $SaveHash{$basename} = $stored_form;
                   12690:                     $AppHash{$envname}   = $stored_form;
                   12691:                 }
                   12692:             }
                   12693:         }
                   12694:     }
                   12695:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 12696:                                           $udom,$uname);
1.153     matthew  12697:     if ($put_result !~ /^(ok|delayed)/) {
                   12698:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   12699:                                  'got error:'.$put_result);
                   12700:     }
                   12701:     # Make sure these settings stick around in this session, too
1.646     raeburn  12702:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  12703:     return;
                   12704: }
                   12705: 
                   12706: sub restore_course_settings {
1.499     albertel 12707:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 12708: }
                   12709: 
                   12710: sub restore_settings {
                   12711:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12712:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 12713:         next if (exists($env{'form.'.$setting}));
1.496     albertel 12714:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  12715:             '.'.$setting;
1.258     albertel 12716:         if (exists($env{$envname})) {
1.153     matthew  12717:             if ($type eq 'scalar') {
1.258     albertel 12718:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  12719:             } elsif ($type eq 'array') {
1.258     albertel 12720:                 $env{'form.'.$setting} = [ 
1.153     matthew  12721:                                            map { 
1.369     www      12722:                                                &unescape($_); 
1.258     albertel 12723:                                            } split(',',$env{$envname})
1.153     matthew  12724:                                            ];
                   12725:             }
                   12726:         }
                   12727:     }
1.127     matthew  12728: }
                   12729: 
1.618     raeburn  12730: #######################################################
                   12731: #######################################################
                   12732: 
                   12733: =pod
                   12734: 
                   12735: =head1 Domain E-mail Routines  
                   12736: 
                   12737: =over 4
                   12738: 
1.648     raeburn  12739: =item * &build_recipient_list()
1.618     raeburn  12740: 
1.884     raeburn  12741: Build recipient lists for five types of e-mail:
1.766     raeburn  12742: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.884     raeburn  12743: (d) Help requests, (e) Course requests needing approval,  generated by
                   12744: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
                   12745: loncoursequeueadmin.pm respectively.
1.618     raeburn  12746: 
                   12747: Inputs:
1.619     raeburn  12748: defmail (scalar - email address of default recipient), 
1.618     raeburn  12749: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  12750: defdom (domain for which to retrieve configuration settings),
                   12751: origmail (scalar - email address of recipient from loncapa.conf, 
                   12752: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  12753: 
1.655     raeburn  12754: Returns: comma separated list of addresses to which to send e-mail.
                   12755: 
                   12756: =back
1.618     raeburn  12757: 
                   12758: =cut
                   12759: 
                   12760: ############################################################
                   12761: ############################################################
                   12762: sub build_recipient_list {
1.619     raeburn  12763:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  12764:     my @recipients;
                   12765:     my $otheremails;
                   12766:     my %domconfig =
                   12767:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   12768:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  12769:         if (exists($domconfig{'contacts'}{$mailing})) {
                   12770:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   12771:                 my @contacts = ('adminemail','supportemail');
                   12772:                 foreach my $item (@contacts) {
                   12773:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   12774:                         my $addr = $domconfig{'contacts'}{$item}; 
                   12775:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12776:                             push(@recipients,$addr);
                   12777:                         }
1.619     raeburn  12778:                     }
1.766     raeburn  12779:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  12780:                 }
                   12781:             }
1.766     raeburn  12782:         } elsif ($origmail ne '') {
                   12783:             push(@recipients,$origmail);
1.618     raeburn  12784:         }
1.619     raeburn  12785:     } elsif ($origmail ne '') {
                   12786:         push(@recipients,$origmail);
1.618     raeburn  12787:     }
1.688     raeburn  12788:     if (defined($defmail)) {
                   12789:         if ($defmail ne '') {
                   12790:             push(@recipients,$defmail);
                   12791:         }
1.618     raeburn  12792:     }
                   12793:     if ($otheremails) {
1.619     raeburn  12794:         my @others;
                   12795:         if ($otheremails =~ /,/) {
                   12796:             @others = split(/,/,$otheremails);
1.618     raeburn  12797:         } else {
1.619     raeburn  12798:             push(@others,$otheremails);
                   12799:         }
                   12800:         foreach my $addr (@others) {
                   12801:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12802:                 push(@recipients,$addr);
                   12803:             }
1.618     raeburn  12804:         }
                   12805:     }
1.619     raeburn  12806:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  12807:     return $recipientlist;
                   12808: }
                   12809: 
1.127     matthew  12810: ############################################################
                   12811: ############################################################
1.154     albertel 12812: 
1.655     raeburn  12813: =pod
                   12814: 
                   12815: =head1 Course Catalog Routines
                   12816: 
                   12817: =over 4
                   12818: 
                   12819: =item * &gather_categories()
                   12820: 
                   12821: Converts category definitions - keys of categories hash stored in  
                   12822: coursecategories in configuration.db on the primary library server in a 
                   12823: domain - to an array.  Also generates javascript and idx hash used to 
                   12824: generate Domain Coordinator interface for editing Course Categories.
                   12825: 
                   12826: Inputs:
1.663     raeburn  12827: 
1.655     raeburn  12828: categories (reference to hash of category definitions).
1.663     raeburn  12829: 
1.655     raeburn  12830: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12831:       categories and subcategories).
1.663     raeburn  12832: 
1.655     raeburn  12833: idx (reference to hash of counters used in Domain Coordinator interface for 
                   12834:       editing Course Categories).
1.663     raeburn  12835: 
1.655     raeburn  12836: jsarray (reference to array of categories used to create Javascript arrays for
                   12837:          Domain Coordinator interface for editing Course Categories).
                   12838: 
                   12839: Returns: nothing
                   12840: 
                   12841: Side effects: populates cats, idx and jsarray. 
                   12842: 
                   12843: =cut
                   12844: 
                   12845: sub gather_categories {
                   12846:     my ($categories,$cats,$idx,$jsarray) = @_;
                   12847:     my %counters;
                   12848:     my $num = 0;
                   12849:     foreach my $item (keys(%{$categories})) {
                   12850:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   12851:         if ($container eq '' && $depth == 0) {
                   12852:             $cats->[$depth][$categories->{$item}] = $cat;
                   12853:         } else {
                   12854:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   12855:         }
                   12856:         my ($escitem,$tail) = split(/:/,$item,2);
                   12857:         if ($counters{$tail} eq '') {
                   12858:             $counters{$tail} = $num;
                   12859:             $num ++;
                   12860:         }
                   12861:         if (ref($idx) eq 'HASH') {
                   12862:             $idx->{$item} = $counters{$tail};
                   12863:         }
                   12864:         if (ref($jsarray) eq 'ARRAY') {
                   12865:             push(@{$jsarray->[$counters{$tail}]},$item);
                   12866:         }
                   12867:     }
                   12868:     return;
                   12869: }
                   12870: 
                   12871: =pod
                   12872: 
                   12873: =item * &extract_categories()
                   12874: 
                   12875: Used to generate breadcrumb trails for course categories.
                   12876: 
                   12877: Inputs:
1.663     raeburn  12878: 
1.655     raeburn  12879: categories (reference to hash of category definitions).
1.663     raeburn  12880: 
1.655     raeburn  12881: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12882:       categories and subcategories).
1.663     raeburn  12883: 
1.655     raeburn  12884: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  12885: 
1.655     raeburn  12886: allitems (reference to hash - key is category key 
                   12887:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12888: 
1.655     raeburn  12889: idx (reference to hash of counters used in Domain Coordinator interface for
                   12890:       editing Course Categories).
1.663     raeburn  12891: 
1.655     raeburn  12892: jsarray (reference to array of categories used to create Javascript arrays for
                   12893:          Domain Coordinator interface for editing Course Categories).
                   12894: 
1.665     raeburn  12895: subcats (reference to hash of arrays containing all subcategories within each 
                   12896:          category, -recursive)
                   12897: 
1.655     raeburn  12898: Returns: nothing
                   12899: 
                   12900: Side effects: populates trails and allitems hash references.
                   12901: 
                   12902: =cut
                   12903: 
                   12904: sub extract_categories {
1.665     raeburn  12905:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  12906:     if (ref($categories) eq 'HASH') {
                   12907:         &gather_categories($categories,$cats,$idx,$jsarray);
                   12908:         if (ref($cats->[0]) eq 'ARRAY') {
                   12909:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   12910:                 my $name = $cats->[0][$i];
                   12911:                 my $item = &escape($name).'::0';
                   12912:                 my $trailstr;
                   12913:                 if ($name eq 'instcode') {
                   12914:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  12915:                 } elsif ($name eq 'communities') {
                   12916:                     $trailstr = &mt('Communities');
1.655     raeburn  12917:                 } else {
                   12918:                     $trailstr = $name;
                   12919:                 }
                   12920:                 if ($allitems->{$item} eq '') {
                   12921:                     push(@{$trails},$trailstr);
                   12922:                     $allitems->{$item} = scalar(@{$trails})-1;
                   12923:                 }
                   12924:                 my @parents = ($name);
                   12925:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   12926:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   12927:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  12928:                         if (ref($subcats) eq 'HASH') {
                   12929:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   12930:                         }
                   12931:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   12932:                     }
                   12933:                 } else {
                   12934:                     if (ref($subcats) eq 'HASH') {
                   12935:                         $subcats->{$item} = [];
1.655     raeburn  12936:                     }
                   12937:                 }
                   12938:             }
                   12939:         }
                   12940:     }
                   12941:     return;
                   12942: }
                   12943: 
                   12944: =pod
                   12945: 
                   12946: =item *&recurse_categories()
                   12947: 
                   12948: Recursively used to generate breadcrumb trails for course categories.
                   12949: 
                   12950: Inputs:
1.663     raeburn  12951: 
1.655     raeburn  12952: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12953:       categories and subcategories).
1.663     raeburn  12954: 
1.655     raeburn  12955: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  12956: 
                   12957: category (current course category, for which breadcrumb trail is being generated).
                   12958: 
                   12959: trails (reference to array of breadcrumb trails for each category).
                   12960: 
1.655     raeburn  12961: allitems (reference to hash - key is category key
                   12962:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12963: 
1.655     raeburn  12964: parents (array containing containers directories for current category, 
                   12965:          back to top level). 
                   12966: 
                   12967: Returns: nothing
                   12968: 
                   12969: Side effects: populates trails and allitems hash references
                   12970: 
                   12971: =cut
                   12972: 
                   12973: sub recurse_categories {
1.665     raeburn  12974:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  12975:     my $shallower = $depth - 1;
                   12976:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   12977:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   12978:             my $name = $cats->[$depth]{$category}[$k];
                   12979:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   12980:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   12981:             if ($allitems->{$item} eq '') {
                   12982:                 push(@{$trails},$trailstr);
                   12983:                 $allitems->{$item} = scalar(@{$trails})-1;
                   12984:             }
                   12985:             my $deeper = $depth+1;
                   12986:             push(@{$parents},$category);
1.665     raeburn  12987:             if (ref($subcats) eq 'HASH') {
                   12988:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   12989:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   12990:                     my $higher;
                   12991:                     if ($j > 0) {
                   12992:                         $higher = &escape($parents->[$j]).':'.
                   12993:                                   &escape($parents->[$j-1]).':'.$j;
                   12994:                     } else {
                   12995:                         $higher = &escape($parents->[$j]).'::'.$j;
                   12996:                     }
                   12997:                     push(@{$subcats->{$higher}},$subcat);
                   12998:                 }
                   12999:             }
                   13000:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13001:                                 $subcats);
1.655     raeburn  13002:             pop(@{$parents});
                   13003:         }
                   13004:     } else {
                   13005:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13006:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13007:         if ($allitems->{$item} eq '') {
                   13008:             push(@{$trails},$trailstr);
                   13009:             $allitems->{$item} = scalar(@{$trails})-1;
                   13010:         }
                   13011:     }
                   13012:     return;
                   13013: }
                   13014: 
1.663     raeburn  13015: =pod
                   13016: 
                   13017: =item *&assign_categories_table()
                   13018: 
                   13019: Create a datatable for display of hierarchical categories in a domain,
                   13020: with checkboxes to allow a course to be categorized. 
                   13021: 
                   13022: Inputs:
                   13023: 
                   13024: cathash - reference to hash of categories defined for the domain (from
                   13025:           configuration.db)
                   13026: 
                   13027: currcat - scalar with an & separated list of categories assigned to a course. 
                   13028: 
1.919     raeburn  13029: type    - scalar contains course type (Course or Community).
                   13030: 
1.663     raeburn  13031: Returns: $output (markup to be displayed) 
                   13032: 
                   13033: =cut
                   13034: 
                   13035: sub assign_categories_table {
1.919     raeburn  13036:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13037:     my $output;
                   13038:     if (ref($cathash) eq 'HASH') {
                   13039:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13040:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13041:         $maxdepth = scalar(@cats);
                   13042:         if (@cats > 0) {
                   13043:             my $itemcount = 0;
                   13044:             if (ref($cats[0]) eq 'ARRAY') {
                   13045:                 my @currcategories;
                   13046:                 if ($currcat ne '') {
                   13047:                     @currcategories = split('&',$currcat);
                   13048:                 }
1.919     raeburn  13049:                 my $table;
1.663     raeburn  13050:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13051:                     my $parent = $cats[0][$i];
1.919     raeburn  13052:                     next if ($parent eq 'instcode');
                   13053:                     if ($type eq 'Community') {
                   13054:                         next unless ($parent eq 'communities');
                   13055:                     } else {
                   13056:                         next if ($parent eq 'communities');
                   13057:                     }
1.663     raeburn  13058:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13059:                     my $item = &escape($parent).'::0';
                   13060:                     my $checked = '';
                   13061:                     if (@currcategories > 0) {
                   13062:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13063:                             $checked = ' checked="checked"';
1.663     raeburn  13064:                         }
                   13065:                     }
1.919     raeburn  13066:                     my $parent_title = $parent;
                   13067:                     if ($parent eq 'communities') {
                   13068:                         $parent_title = &mt('Communities');
                   13069:                     }
                   13070:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13071:                               '<input type="checkbox" name="usecategory" value="'.
                   13072:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13073:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13074:                     my $depth = 1;
                   13075:                     push(@path,$parent);
1.919     raeburn  13076:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13077:                     pop(@path);
1.919     raeburn  13078:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13079:                     $itemcount ++;
                   13080:                 }
1.919     raeburn  13081:                 if ($itemcount) {
                   13082:                     $output = &Apache::loncommon::start_data_table().
                   13083:                               $table.
                   13084:                               &Apache::loncommon::end_data_table();
                   13085:                 }
1.663     raeburn  13086:             }
                   13087:         }
                   13088:     }
                   13089:     return $output;
                   13090: }
                   13091: 
                   13092: =pod
                   13093: 
                   13094: =item *&assign_category_rows()
                   13095: 
                   13096: Create a datatable row for display of nested categories in a domain,
                   13097: with checkboxes to allow a course to be categorized,called recursively.
                   13098: 
                   13099: Inputs:
                   13100: 
                   13101: itemcount - track row number for alternating colors
                   13102: 
                   13103: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13104:       categories and subcategories.
                   13105: 
                   13106: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13107: 
                   13108: parent - parent of current category item
                   13109: 
                   13110: path - Array containing all categories back up through the hierarchy from the
                   13111:        current category to the top level.
                   13112: 
                   13113: currcategories - reference to array of current categories assigned to the course
                   13114: 
                   13115: Returns: $output (markup to be displayed).
                   13116: 
                   13117: =cut
                   13118: 
                   13119: sub assign_category_rows {
                   13120:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13121:     my ($text,$name,$item,$chgstr);
                   13122:     if (ref($cats) eq 'ARRAY') {
                   13123:         my $maxdepth = scalar(@{$cats});
                   13124:         if (ref($cats->[$depth]) eq 'HASH') {
                   13125:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13126:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13127:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13128:                 $text .= '<td><table class="LC_datatable">';
                   13129:                 for (my $j=0; $j<$numchildren; $j++) {
                   13130:                     $name = $cats->[$depth]{$parent}[$j];
                   13131:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13132:                     my $deeper = $depth+1;
                   13133:                     my $checked = '';
                   13134:                     if (ref($currcategories) eq 'ARRAY') {
                   13135:                         if (@{$currcategories} > 0) {
                   13136:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13137:                                 $checked = ' checked="checked"';
1.663     raeburn  13138:                             }
                   13139:                         }
                   13140:                     }
1.664     raeburn  13141:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13142:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13143:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13144:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13145:                              '</td><td>';
1.663     raeburn  13146:                     if (ref($path) eq 'ARRAY') {
                   13147:                         push(@{$path},$name);
                   13148:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13149:                         pop(@{$path});
                   13150:                     }
                   13151:                     $text .= '</td></tr>';
                   13152:                 }
                   13153:                 $text .= '</table></td>';
                   13154:             }
                   13155:         }
                   13156:     }
                   13157:     return $text;
                   13158: }
                   13159: 
1.655     raeburn  13160: ############################################################
                   13161: ############################################################
                   13162: 
                   13163: 
1.443     albertel 13164: sub commit_customrole {
1.664     raeburn  13165:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13166:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13167:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13168:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13169:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13170:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13171:                  '</b><br />';
                   13172:     return $output;
                   13173: }
                   13174: 
                   13175: sub commit_standardrole {
1.541     raeburn  13176:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
                   13177:     my ($output,$logmsg,$linefeed);
                   13178:     if ($context eq 'auto') {
                   13179:         $linefeed = "\n";
                   13180:     } else {
                   13181:         $linefeed = "<br />\n";
                   13182:     }  
1.443     albertel 13183:     if ($three eq 'st') {
1.541     raeburn  13184:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
                   13185:                                          $one,$two,$sec,$context);
                   13186:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13187:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13188:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13189:         } else {
1.541     raeburn  13190:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13191:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13192:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13193:             if ($context eq 'auto') {
                   13194:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13195:             } else {
                   13196:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13197:                &mt('Add to classlist').': <b>ok</b>';
                   13198:             }
                   13199:             $output .= $linefeed;
1.443     albertel 13200:         }
                   13201:     } else {
                   13202:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13203:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13204:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13205:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13206:         if ($context eq 'auto') {
                   13207:             $output .= $result.$linefeed;
                   13208:         } else {
                   13209:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13210:         }
1.443     albertel 13211:     }
                   13212:     return $output;
                   13213: }
                   13214: 
                   13215: sub commit_studentrole {
1.541     raeburn  13216:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
1.626     raeburn  13217:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13218:     if ($context eq 'auto') {
                   13219:         $linefeed = "\n";
                   13220:     } else {
                   13221:         $linefeed = '<br />'."\n";
                   13222:     }
1.443     albertel 13223:     if (defined($one) && defined($two)) {
                   13224:         my $cid=$one.'_'.$two;
                   13225:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13226:         my $secchange = 0;
                   13227:         my $expire_role_result;
                   13228:         my $modify_section_result;
1.628     raeburn  13229:         if ($oldsec ne '-1') { 
                   13230:             if ($oldsec ne $sec) {
1.443     albertel 13231:                 $secchange = 1;
1.628     raeburn  13232:                 my $now = time;
1.443     albertel 13233:                 my $uurl='/'.$cid;
                   13234:                 $uurl=~s/\_/\//g;
                   13235:                 if ($oldsec) {
                   13236:                     $uurl.='/'.$oldsec;
                   13237:                 }
1.626     raeburn  13238:                 $oldsecurl = $uurl;
1.628     raeburn  13239:                 $expire_role_result = 
1.652     raeburn  13240:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13241:                 if ($env{'request.course.sec'} ne '') { 
                   13242:                     if ($expire_role_result eq 'refused') {
                   13243:                         my @roles = ('st');
                   13244:                         my @statuses = ('previous');
                   13245:                         my @roledoms = ($one);
                   13246:                         my $withsec = 1;
                   13247:                         my %roleshash = 
                   13248:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13249:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13250:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13251:                             my ($oldstart,$oldend) = 
                   13252:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13253:                             if ($oldend > 0 && $oldend <= $now) {
                   13254:                                 $expire_role_result = 'ok';
                   13255:                             }
                   13256:                         }
                   13257:                     }
                   13258:                 }
1.443     albertel 13259:                 $result = $expire_role_result;
                   13260:             }
                   13261:         }
                   13262:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.652     raeburn  13263:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
1.443     albertel 13264:             if ($modify_section_result =~ /^ok/) {
                   13265:                 if ($secchange == 1) {
1.628     raeburn  13266:                     if ($sec eq '') {
                   13267:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13268:                     } else {
                   13269:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13270:                     }
1.443     albertel 13271:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13272:                     if ($sec eq '') {
                   13273:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13274:                     } else {
                   13275:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13276:                     }
1.443     albertel 13277:                 } else {
1.628     raeburn  13278:                     if ($sec eq '') {
                   13279:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13280:                     } else {
                   13281:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13282:                     }
1.443     albertel 13283:                 }
                   13284:             } else {
1.628     raeburn  13285:                 if ($secchange) {       
                   13286:                     $$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;
                   13287:                 } else {
                   13288:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13289:                 }
1.443     albertel 13290:             }
                   13291:             $result = $modify_section_result;
                   13292:         } elsif ($secchange == 1) {
1.628     raeburn  13293:             if ($oldsec eq '') {
1.1103    raeburn  13294:                 $$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  13295:             } else {
                   13296:                 $$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;
                   13297:             }
1.626     raeburn  13298:             if ($expire_role_result eq 'refused') {
                   13299:                 my $newsecurl = '/'.$cid;
                   13300:                 $newsecurl =~ s/\_/\//g;
                   13301:                 if ($sec ne '') {
                   13302:                     $newsecurl.='/'.$sec;
                   13303:                 }
                   13304:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13305:                     if ($sec eq '') {
                   13306:                         $$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;
                   13307:                     } else {
                   13308:                         $$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;
                   13309:                     }
                   13310:                 }
                   13311:             }
1.443     albertel 13312:         }
                   13313:     } else {
1.626     raeburn  13314:         $$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 13315:         $result = "error: incomplete course id\n";
                   13316:     }
                   13317:     return $result;
                   13318: }
                   13319: 
                   13320: ############################################################
                   13321: ############################################################
                   13322: 
1.566     albertel 13323: sub check_clone {
1.578     raeburn  13324:     my ($args,$linefeed) = @_;
1.566     albertel 13325:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13326:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13327:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13328:     my $clonemsg;
                   13329:     my $can_clone = 0;
1.944     raeburn  13330:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13331:     if ($lctype ne 'community') {
                   13332:         $lctype = 'course';
                   13333:     }
1.566     albertel 13334:     if ($clonehome eq 'no_host') {
1.944     raeburn  13335:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13336:             $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'});
                   13337:         } else {
                   13338:             $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'});
                   13339:         }     
1.566     albertel 13340:     } else {
                   13341: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13342:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13343:             if ($clonedesc{'type'} ne 'Community') {
                   13344:                  $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'});
                   13345:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13346:             }
                   13347:         }
1.882     raeburn  13348: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13349:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13350: 	    $can_clone = 1;
                   13351: 	} else {
                   13352: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13353: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13354: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13355:             if (grep(/^\*$/,@cloners)) {
                   13356:                 $can_clone = 1;
                   13357:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13358:                 $can_clone = 1;
                   13359:             } else {
1.908     raeburn  13360:                 my $ccrole = 'cc';
1.944     raeburn  13361:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13362:                     $ccrole = 'co';
                   13363:                 }
1.578     raeburn  13364: 	        my %roleshash =
                   13365: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13366: 					 $args->{'ccdomain'},
1.908     raeburn  13367:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13368: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13369: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13370:                     $can_clone = 1;
                   13371:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13372:                     $can_clone = 1;
                   13373:                 } else {
1.944     raeburn  13374:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13375:                         $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'});
                   13376:                     } else {
                   13377:                         $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'});
                   13378:                     }
1.578     raeburn  13379: 	        }
1.566     albertel 13380: 	    }
1.578     raeburn  13381:         }
1.566     albertel 13382:     }
                   13383:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13384: }
                   13385: 
1.444     albertel 13386: sub construct_course {
1.885     raeburn  13387:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 13388:     my $outcome;
1.541     raeburn  13389:     my $linefeed =  '<br />'."\n";
                   13390:     if ($context eq 'auto') {
                   13391:         $linefeed = "\n";
                   13392:     }
1.566     albertel 13393: 
                   13394: #
                   13395: # Are we cloning?
                   13396: #
                   13397:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13398:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13399: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13400: 	if ($context ne 'auto') {
1.578     raeburn  13401:             if ($clonemsg ne '') {
                   13402: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13403:             }
1.566     albertel 13404: 	}
                   13405: 	$outcome .= $clonemsg.$linefeed;
                   13406: 
                   13407:         if (!$can_clone) {
                   13408: 	    return (0,$outcome);
                   13409: 	}
                   13410:     }
                   13411: 
1.444     albertel 13412: #
                   13413: # Open course
                   13414: #
                   13415:     my $crstype = lc($args->{'crstype'});
                   13416:     my %cenv=();
                   13417:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13418:                                              $args->{'cdescr'},
                   13419:                                              $args->{'curl'},
                   13420:                                              $args->{'course_home'},
                   13421:                                              $args->{'nonstandard'},
                   13422:                                              $args->{'crscode'},
                   13423:                                              $args->{'ccuname'}.':'.
                   13424:                                              $args->{'ccdomain'},
1.882     raeburn  13425:                                              $args->{'crstype'},
1.885     raeburn  13426:                                              $cnum,$context,$category);
1.444     albertel 13427: 
                   13428:     # Note: The testing routines depend on this being output; see 
                   13429:     # Utils::Course. This needs to at least be output as a comment
                   13430:     # if anyone ever decides to not show this, and Utils::Course::new
                   13431:     # will need to be suitably modified.
1.541     raeburn  13432:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13433:     if ($$courseid =~ /^error:/) {
                   13434:         return (0,$outcome);
                   13435:     }
                   13436: 
1.444     albertel 13437: #
                   13438: # Check if created correctly
                   13439: #
1.479     albertel 13440:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13441:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13442:     if ($crsuhome eq 'no_host') {
                   13443:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13444:         return (0,$outcome);
                   13445:     }
1.541     raeburn  13446:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13447: 
1.444     albertel 13448: #
1.566     albertel 13449: # Do the cloning
                   13450: #   
                   13451:     if ($can_clone && $cloneid) {
                   13452: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13453: 	if ($context ne 'auto') {
                   13454: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13455: 	}
                   13456: 	$outcome .= $clonemsg.$linefeed;
                   13457: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13458: # Copy all files
1.637     www      13459: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13460: # Restore URL
1.566     albertel 13461: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13462: # Restore title
1.566     albertel 13463: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13464: # Restore creation date, creator and creation context.
                   13465:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13466:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13467:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13468: # Mark as cloned
1.566     albertel 13469: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13470: # Need to clone grading mode
                   13471:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13472:         $cenv{'grading'}=$newenv{'grading'};
                   13473: # Do not clone these environment entries
                   13474:         &Apache::lonnet::del('environment',
                   13475:                   ['default_enrollment_start_date',
                   13476:                    'default_enrollment_end_date',
                   13477:                    'question.email',
                   13478:                    'policy.email',
                   13479:                    'comment.email',
                   13480:                    'pch.users.denied',
1.725     raeburn  13481:                    'plc.users.denied',
                   13482:                    'hidefromcat',
                   13483:                    'categories'],
1.638     www      13484:                    $$crsudom,$$crsunum);
1.444     albertel 13485:     }
1.566     albertel 13486: 
1.444     albertel 13487: #
                   13488: # Set environment (will override cloned, if existing)
                   13489: #
                   13490:     my @sections = ();
                   13491:     my @xlists = ();
                   13492:     if ($args->{'crstype'}) {
                   13493:         $cenv{'type'}=$args->{'crstype'};
                   13494:     }
                   13495:     if ($args->{'crsid'}) {
                   13496:         $cenv{'courseid'}=$args->{'crsid'};
                   13497:     }
                   13498:     if ($args->{'crscode'}) {
                   13499:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   13500:     }
                   13501:     if ($args->{'crsquota'} ne '') {
                   13502:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   13503:     } else {
                   13504:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   13505:     }
                   13506:     if ($args->{'ccuname'}) {
                   13507:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   13508:                                         ':'.$args->{'ccdomain'};
                   13509:     } else {
                   13510:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   13511:     }
                   13512:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   13513:     if ($args->{'crssections'}) {
                   13514:         $cenv{'internal.sectionnums'} = '';
                   13515:         if ($args->{'crssections'} =~ m/,/) {
                   13516:             @sections = split/,/,$args->{'crssections'};
                   13517:         } else {
                   13518:             $sections[0] = $args->{'crssections'};
                   13519:         }
                   13520:         if (@sections > 0) {
                   13521:             foreach my $item (@sections) {
                   13522:                 my ($sec,$gp) = split/:/,$item;
                   13523:                 my $class = $args->{'crscode'}.$sec;
                   13524:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   13525:                 $cenv{'internal.sectionnums'} .= $item.',';
                   13526:                 unless ($addcheck eq 'ok') {
                   13527:                     push @badclasses, $class;
                   13528:                 }
                   13529:             }
                   13530:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   13531:         }
                   13532:     }
                   13533: # do not hide course coordinator from staff listing, 
                   13534: # even if privileged
                   13535:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13536: # add crosslistings
                   13537:     if ($args->{'crsxlist'}) {
                   13538:         $cenv{'internal.crosslistings'}='';
                   13539:         if ($args->{'crsxlist'} =~ m/,/) {
                   13540:             @xlists = split/,/,$args->{'crsxlist'};
                   13541:         } else {
                   13542:             $xlists[0] = $args->{'crsxlist'};
                   13543:         }
                   13544:         if (@xlists > 0) {
                   13545:             foreach my $item (@xlists) {
                   13546:                 my ($xl,$gp) = split/:/,$item;
                   13547:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   13548:                 $cenv{'internal.crosslistings'} .= $item.',';
                   13549:                 unless ($addcheck eq 'ok') {
                   13550:                     push @badclasses, $xl;
                   13551:                 }
                   13552:             }
                   13553:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   13554:         }
                   13555:     }
                   13556:     if ($args->{'autoadds'}) {
                   13557:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   13558:     }
                   13559:     if ($args->{'autodrops'}) {
                   13560:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   13561:     }
                   13562: # check for notification of enrollment changes
                   13563:     my @notified = ();
                   13564:     if ($args->{'notify_owner'}) {
                   13565:         if ($args->{'ccuname'} ne '') {
                   13566:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   13567:         }
                   13568:     }
                   13569:     if ($args->{'notify_dc'}) {
                   13570:         if ($uname ne '') { 
1.630     raeburn  13571:             push(@notified,$uname.':'.$udom);
1.444     albertel 13572:         }
                   13573:     }
                   13574:     if (@notified > 0) {
                   13575:         my $notifylist;
                   13576:         if (@notified > 1) {
                   13577:             $notifylist = join(',',@notified);
                   13578:         } else {
                   13579:             $notifylist = $notified[0];
                   13580:         }
                   13581:         $cenv{'internal.notifylist'} = $notifylist;
                   13582:     }
                   13583:     if (@badclasses > 0) {
                   13584:         my %lt=&Apache::lonlocal::texthash(
                   13585:                 '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',
                   13586:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   13587:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   13588:         );
1.541     raeburn  13589:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   13590:                            ' ('.$lt{'adby'}.')';
                   13591:         if ($context eq 'auto') {
                   13592:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 13593:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  13594:             foreach my $item (@badclasses) {
                   13595:                 if ($context eq 'auto') {
                   13596:                     $outcome .= " - $item\n";
                   13597:                 } else {
                   13598:                     $outcome .= "<li>$item</li>\n";
                   13599:                 }
                   13600:             }
                   13601:             if ($context eq 'auto') {
                   13602:                 $outcome .= $linefeed;
                   13603:             } else {
1.566     albertel 13604:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  13605:             }
                   13606:         } 
1.444     albertel 13607:     }
                   13608:     if ($args->{'no_end_date'}) {
                   13609:         $args->{'endaccess'} = 0;
                   13610:     }
                   13611:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   13612:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   13613:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   13614:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   13615:     if ($args->{'showphotos'}) {
                   13616:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   13617:     }
                   13618:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   13619:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   13620:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   13621:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  13622:             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'); 
                   13623:             if ($context eq 'auto') {
                   13624:                 $outcome .= $krb_msg;
                   13625:             } else {
1.566     albertel 13626:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  13627:             }
                   13628:             $outcome .= $linefeed;
1.444     albertel 13629:         }
                   13630:     }
                   13631:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   13632:        if ($args->{'setpolicy'}) {
                   13633:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13634:        }
                   13635:        if ($args->{'setcontent'}) {
                   13636:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13637:        }
                   13638:     }
                   13639:     if ($args->{'reshome'}) {
                   13640: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   13641: 	$cenv{'reshome'}=~s/\/+$/\//;
                   13642:     }
                   13643: #
                   13644: # course has keyed access
                   13645: #
                   13646:     if ($args->{'setkeys'}) {
                   13647:        $cenv{'keyaccess'}='yes';
                   13648:     }
                   13649: # if specified, key authority is not course, but user
                   13650: # only active if keyaccess is yes
                   13651:     if ($args->{'keyauth'}) {
1.487     albertel 13652: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   13653: 	$user = &LONCAPA::clean_username($user);
                   13654: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     13655: 	if ($user ne '' && $domain ne '') {
1.487     albertel 13656: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 13657: 	}
                   13658:     }
                   13659: 
                   13660:     if ($args->{'disresdis'}) {
                   13661:         $cenv{'pch.roles.denied'}='st';
                   13662:     }
                   13663:     if ($args->{'disablechat'}) {
                   13664:         $cenv{'plc.roles.denied'}='st';
                   13665:     }
                   13666: 
                   13667:     # Record we've not yet viewed the Course Initialization Helper for this 
                   13668:     # course
                   13669:     $cenv{'course.helper.not.run'} = 1;
                   13670:     #
                   13671:     # Use new Randomseed
                   13672:     #
                   13673:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   13674:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   13675:     #
                   13676:     # The encryption code and receipt prefix for this course
                   13677:     #
                   13678:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   13679:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   13680:     #
                   13681:     # By default, use standard grading
                   13682:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   13683: 
1.541     raeburn  13684:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   13685:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13686: #
                   13687: # Open all assignments
                   13688: #
                   13689:     if ($args->{'openall'}) {
                   13690:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   13691:        my %storecontent = ($storeunder         => time,
                   13692:                            $storeunder.'.type' => 'date_start');
                   13693:        
                   13694:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  13695:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13696:    }
                   13697: #
                   13698: # Set first page
                   13699: #
                   13700:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   13701: 	    || ($cloneid)) {
1.445     albertel 13702: 	use LONCAPA::map;
1.444     albertel 13703: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 13704: 
                   13705: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   13706:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   13707: 
1.444     albertel 13708:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   13709:         my $title; my $url;
                   13710:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   13711: 	    $title=&mt('Syllabus');
1.444     albertel 13712:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   13713:         } else {
1.963     raeburn  13714:             $title=&mt('Table of Contents');
1.444     albertel 13715:             $url='/adm/navmaps';
                   13716:         }
1.445     albertel 13717: 
                   13718:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   13719: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   13720: 
                   13721: 	if ($errtext) { $fatal=2; }
1.541     raeburn  13722:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 13723:     }
1.566     albertel 13724: 
                   13725:     return (1,$outcome);
1.444     albertel 13726: }
                   13727: 
                   13728: ############################################################
                   13729: ############################################################
                   13730: 
1.953     droeschl 13731: #SD
                   13732: # only Community and Course, or anything else?
1.378     raeburn  13733: sub course_type {
                   13734:     my ($cid) = @_;
                   13735:     if (!defined($cid)) {
                   13736:         $cid = $env{'request.course.id'};
                   13737:     }
1.404     albertel 13738:     if (defined($env{'course.'.$cid.'.type'})) {
                   13739:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  13740:     } else {
                   13741:         return 'Course';
1.377     raeburn  13742:     }
                   13743: }
1.156     albertel 13744: 
1.406     raeburn  13745: sub group_term {
                   13746:     my $crstype = &course_type();
                   13747:     my %names = (
                   13748:                   'Course' => 'group',
1.865     raeburn  13749:                   'Community' => 'group',
1.406     raeburn  13750:                 );
                   13751:     return $names{$crstype};
                   13752: }
                   13753: 
1.902     raeburn  13754: sub course_types {
                   13755:     my @types = ('official','unofficial','community');
                   13756:     my %typename = (
                   13757:                          official   => 'Official course',
                   13758:                          unofficial => 'Unofficial course',
                   13759:                          community  => 'Community',
                   13760:                    );
                   13761:     return (\@types,\%typename);
                   13762: }
                   13763: 
1.156     albertel 13764: sub icon {
                   13765:     my ($file)=@_;
1.505     albertel 13766:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 13767:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 13768:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 13769:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   13770: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   13771: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13772: 	            $curfext.".gif") {
                   13773: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13774: 		$curfext.".gif";
                   13775: 	}
                   13776:     }
1.249     albertel 13777:     return &lonhttpdurl($iconname);
1.154     albertel 13778: } 
1.84      albertel 13779: 
1.575     albertel 13780: sub lonhttpdurl {
1.692     www      13781: #
                   13782: # Had been used for "small fry" static images on separate port 8080.
                   13783: # Modify here if lightweight http functionality desired again.
                   13784: # Currently eliminated due to increasing firewall issues.
                   13785: #
1.575     albertel 13786:     my ($url)=@_;
1.692     www      13787:     return $url;
1.215     albertel 13788: }
                   13789: 
1.213     albertel 13790: sub connection_aborted {
                   13791:     my ($r)=@_;
                   13792:     $r->print(" ");$r->rflush();
                   13793:     my $c = $r->connection;
                   13794:     return $c->aborted();
                   13795: }
                   13796: 
1.221     foxr     13797: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     13798: #    strings as 'strings'.
                   13799: sub escape_single {
1.221     foxr     13800:     my ($input) = @_;
1.223     albertel 13801:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     13802:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   13803:     return $input;
                   13804: }
1.223     albertel 13805: 
1.222     foxr     13806: #  Same as escape_single, but escape's "'s  This 
                   13807: #  can be used for  "strings"
                   13808: sub escape_double {
                   13809:     my ($input) = @_;
                   13810:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   13811:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   13812:     return $input;
                   13813: }
1.223     albertel 13814:  
1.222     foxr     13815: #   Escapes the last element of a full URL.
                   13816: sub escape_url {
                   13817:     my ($url)   = @_;
1.238     raeburn  13818:     my @urlslices = split(/\//, $url,-1);
1.369     www      13819:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 13820:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     13821: }
1.462     albertel 13822: 
1.820     raeburn  13823: sub compare_arrays {
                   13824:     my ($arrayref1,$arrayref2) = @_;
                   13825:     my (@difference,%count);
                   13826:     @difference = ();
                   13827:     %count = ();
                   13828:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   13829:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   13830:         foreach my $element (keys(%count)) {
                   13831:             if ($count{$element} == 1) {
                   13832:                 push(@difference,$element);
                   13833:             }
                   13834:         }
                   13835:     }
                   13836:     return @difference;
                   13837: }
                   13838: 
1.817     bisitz   13839: # -------------------------------------------------------- Initialize user login
1.462     albertel 13840: sub init_user_environment {
1.463     albertel 13841:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 13842:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   13843: 
                   13844:     my $public=($username eq 'public' && $domain eq 'public');
                   13845: 
                   13846: # See if old ID present, if so, remove
                   13847: 
1.1062    raeburn  13848:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 13849:     my $now=time;
                   13850: 
                   13851:     if ($public) {
                   13852: 	my $max_public=100;
                   13853: 	my $oldest;
                   13854: 	my $oldest_time=0;
                   13855: 	for(my $next=1;$next<=$max_public;$next++) {
                   13856: 	    if (-e $lonids."/publicuser_$next.id") {
                   13857: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   13858: 		if ($mtime<$oldest_time || !$oldest_time) {
                   13859: 		    $oldest_time=$mtime;
                   13860: 		    $oldest=$next;
                   13861: 		}
                   13862: 	    } else {
                   13863: 		$cookie="publicuser_$next";
                   13864: 		last;
                   13865: 	    }
                   13866: 	}
                   13867: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   13868:     } else {
1.463     albertel 13869: 	# if this isn't a robot, kill any existing non-robot sessions
                   13870: 	if (!$args->{'robot'}) {
                   13871: 	    opendir(DIR,$lonids);
                   13872: 	    while ($filename=readdir(DIR)) {
                   13873: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   13874: 		    unlink($lonids.'/'.$filename);
                   13875: 		}
1.462     albertel 13876: 	    }
1.463     albertel 13877: 	    closedir(DIR);
1.462     albertel 13878: 	}
                   13879: # Give them a new cookie
1.463     albertel 13880: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      13881: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 13882: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 13883:     
                   13884: # Initialize roles
                   13885: 
1.1062    raeburn  13886: 	($userroles,$firstaccenv,$timerintenv) = 
                   13887:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 13888:     }
                   13889: # ------------------------------------ Check browser type and MathML capability
                   13890: 
                   13891:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   13892:         $clientunicode,$clientos) = &decode_user_agent($r);
                   13893: 
                   13894: # ------------------------------------------------------------- Get environment
                   13895: 
                   13896:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   13897:     my ($tmp) = keys(%userenv);
                   13898:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   13899:     } else {
                   13900: 	undef(%userenv);
                   13901:     }
                   13902:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   13903: 	$form->{'interface'}=$userenv{'interface'};
                   13904:     }
                   13905:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   13906: 
                   13907: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   13908:     foreach my $option ('interface','localpath','localres') {
                   13909:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 13910:     }
                   13911: # --------------------------------------------------------- Write first profile
                   13912: 
                   13913:     {
                   13914: 	my %initial_env = 
                   13915: 	    ("user.name"          => $username,
                   13916: 	     "user.domain"        => $domain,
                   13917: 	     "user.home"          => $authhost,
                   13918: 	     "browser.type"       => $clientbrowser,
                   13919: 	     "browser.version"    => $clientversion,
                   13920: 	     "browser.mathml"     => $clientmathml,
                   13921: 	     "browser.unicode"    => $clientunicode,
                   13922: 	     "browser.os"         => $clientos,
                   13923: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   13924: 	     "request.course.fn"  => '',
                   13925: 	     "request.course.uri" => '',
                   13926: 	     "request.course.sec" => '',
                   13927: 	     "request.role"       => 'cm',
                   13928: 	     "request.role.adv"   => $env{'user.adv'},
                   13929: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   13930: 
                   13931:         if ($form->{'localpath'}) {
                   13932: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   13933: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   13934:         }
                   13935: 	
                   13936: 	if ($form->{'interface'}) {
                   13937: 	    $form->{'interface'}=~s/\W//gs;
                   13938: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   13939: 	    $env{'browser.interface'}=$form->{'interface'};
                   13940: 	}
                   13941: 
1.981     raeburn  13942:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  13943:         my %domdef;
                   13944:         unless ($domain eq 'public') {
                   13945:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   13946:         }
1.980     raeburn  13947: 
1.1081    raeburn  13948:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  13949:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  13950:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   13951:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  13952:         }
                   13953: 
1.864     raeburn  13954:         foreach my $crstype ('official','unofficial','community') {
1.765     raeburn  13955:             $userenv{'canrequest.'.$crstype} =
                   13956:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  13957:                                                   'reload','requestcourses',
                   13958:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  13959:         }
                   13960: 
1.1092    raeburn  13961:         $userenv{'canrequest.author'} =
                   13962:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   13963:                                         'reload','requestauthor',
                   13964:                                         \%userenv,\%domdef,\%is_adv);
                   13965:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   13966:                                              $domain,$username);
                   13967:         my $reqstatus = $reqauthor{'author_status'};
                   13968:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   13969:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   13970:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   13971:                                                   $reqauthor{'author'}{'timestamp'};
                   13972:             }
                   13973:         }
                   13974: 
1.462     albertel 13975: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  13976: 
1.462     albertel 13977: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   13978: 		 &GDBM_WRCREAT(),0640)) {
                   13979: 	    &_add_to_env(\%disk_env,\%initial_env);
                   13980: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   13981: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  13982:             if (ref($firstaccenv) eq 'HASH') {
                   13983:                 &_add_to_env(\%disk_env,$firstaccenv);
                   13984:             }
                   13985:             if (ref($timerintenv) eq 'HASH') {
                   13986:                 &_add_to_env(\%disk_env,$timerintenv);
                   13987:             }
1.463     albertel 13988: 	    if (ref($args->{'extra_env'})) {
                   13989: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   13990: 	    }
1.462     albertel 13991: 	    untie(%disk_env);
                   13992: 	} else {
1.705     tempelho 13993: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   13994: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 13995: 	    return 'error: '.$!;
                   13996: 	}
                   13997:     }
                   13998:     $env{'request.role'}='cm';
                   13999:     $env{'request.role.adv'}=$env{'user.adv'};
                   14000:     $env{'browser.type'}=$clientbrowser;
                   14001: 
                   14002:     return $cookie;
                   14003: 
                   14004: }
                   14005: 
                   14006: sub _add_to_env {
                   14007:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14008:     if (ref($env_data) eq 'HASH') {
                   14009:         while (my ($key,$value) = each(%$env_data)) {
                   14010: 	    $idf->{$prefix.$key} = $value;
                   14011: 	    $env{$prefix.$key}   = $value;
                   14012:         }
1.462     albertel 14013:     }
                   14014: }
                   14015: 
1.685     tempelho 14016: # --- Get the symbolic name of a problem and the url
                   14017: sub get_symb {
                   14018:     my ($request,$silent) = @_;
1.726     raeburn  14019:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14020:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14021:     if ($symb eq '') {
                   14022:         if (!$silent) {
1.1071    raeburn  14023:             if (ref($request)) { 
                   14024:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14025:             }
1.685     tempelho 14026:             return ();
                   14027:         }
                   14028:     }
                   14029:     &Apache::lonenc::check_decrypt(\$symb);
                   14030:     return ($symb);
                   14031: }
                   14032: 
                   14033: # --------------------------------------------------------------Get annotation
                   14034: 
                   14035: sub get_annotation {
                   14036:     my ($symb,$enc) = @_;
                   14037: 
                   14038:     my $key = $symb;
                   14039:     if (!$enc) {
                   14040:         $key =
                   14041:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14042:     }
                   14043:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14044:     return $annotation{$key};
                   14045: }
                   14046: 
                   14047: sub clean_symb {
1.731     raeburn  14048:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14049: 
                   14050:     &Apache::lonenc::check_decrypt(\$symb);
                   14051:     my $enc = $env{'request.enc'};
1.731     raeburn  14052:     if ($delete_enc) {
1.730     raeburn  14053:         delete($env{'request.enc'});
                   14054:     }
1.685     tempelho 14055: 
                   14056:     return ($symb,$enc);
                   14057: }
1.462     albertel 14058: 
1.990     raeburn  14059: sub build_release_hashes {
                   14060:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14061:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14062:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14063:                   (ref($randomizetry) eq 'HASH'));
                   14064:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14065:         my ($item,$name,$value) = split(/:/,$key);
                   14066:         if ($item eq 'parameter') {
                   14067:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14068:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14069:                     push(@{$checkparms->{$name}},$value);
                   14070:                 }
                   14071:             } else {
                   14072:                 push(@{$checkparms->{$name}},$value);
                   14073:             }
                   14074:         } elsif ($item eq 'resourcetag') {
                   14075:             if ($name eq 'responsetype') {
                   14076:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14077:             }
                   14078:         } elsif ($item eq 'course') {
                   14079:             if ($name eq 'crstype') {
                   14080:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14081:             }
                   14082:         }
                   14083:     }
                   14084:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14085:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14086:     return;
                   14087: }
                   14088: 
1.1083    raeburn  14089: sub update_content_constraints {
                   14090:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14091:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14092:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14093:     my %checkresponsetypes;
                   14094:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14095:         my ($item,$name,$value) = split(/:/,$key);
                   14096:         if ($item eq 'resourcetag') {
                   14097:             if ($name eq 'responsetype') {
                   14098:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14099:             }
                   14100:         }
                   14101:     }
                   14102:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14103:     if (defined($navmap)) {
                   14104:         my %allresponses;
                   14105:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14106:             my %responses = $res->responseTypes();
                   14107:             foreach my $key (keys(%responses)) {
                   14108:                 next unless(exists($checkresponsetypes{$key}));
                   14109:                 $allresponses{$key} += $responses{$key};
                   14110:             }
                   14111:         }
                   14112:         foreach my $key (keys(%allresponses)) {
                   14113:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14114:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14115:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14116:             }
                   14117:         }
                   14118:         undef($navmap);
                   14119:     }
                   14120:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14121:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14122:     }
                   14123:     return;
                   14124: }
                   14125: 
                   14126: sub parse_supplemental_title {
                   14127:     my ($title) = @_;
                   14128: 
                   14129:     my ($foldertitle,$renametitle);
                   14130:     if ($title =~ /&amp;&amp;&amp;/) {
                   14131:         $title = &HTML::Entites::decode($title);
                   14132:     }
                   14133:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14134:         $renametitle=$4;
                   14135:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14136:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14137:         my $name =  &plainname($uname,$udom);
                   14138:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14139:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14140:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14141:             $name.': <br />'.$foldertitle;
                   14142:     }
                   14143:     if (wantarray) {
                   14144:         return ($title,$foldertitle,$renametitle);
                   14145:     }
                   14146:     return $title;
                   14147: }
                   14148: 
1.1101    raeburn  14149: sub symb_to_docspath {
                   14150:     my ($symb) = @_;
                   14151:     return unless ($symb);
                   14152:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14153:     if ($resurl=~/\.(sequence|page)$/) {
                   14154:         $mapurl=$resurl;
                   14155:     } elsif ($resurl eq 'adm/navmaps') {
                   14156:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14157:     }
                   14158:     my $mapresobj;
                   14159:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14160:     if (ref($navmap)) {
                   14161:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14162:     }
                   14163:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14164:     my $type=$2;
                   14165:     my $path;
                   14166:     if (ref($mapresobj)) {
                   14167:         my $pcslist = $mapresobj->map_hierarchy();
                   14168:         if ($pcslist ne '') {
                   14169:             foreach my $pc (split(/,/,$pcslist)) {
                   14170:                 next if ($pc <= 1);
                   14171:                 my $res = $navmap->getByMapPc($pc);
                   14172:                 if (ref($res)) {
                   14173:                     my $thisurl = $res->src();
                   14174:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14175:                     my $thistitle = $res->title();
                   14176:                     $path .= '&'.
                   14177:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
                   14178:                              &Apache::lonhtmlcommon::entity_encode($thistitle).
                   14179:                              ':'.$res->randompick().
                   14180:                              ':'.$res->randomout().
                   14181:                              ':'.$res->encrypted().
                   14182:                              ':'.$res->randomorder().
                   14183:                              ':'.$res->is_page();
                   14184:                 }
                   14185:             }
                   14186:         }
                   14187:         $path =~ s/^\&//;
                   14188:         my $maptitle = $mapresobj->title();
                   14189:         if ($mapurl eq 'default') {
                   14190:             $maptitle = 'Main Course Documents';
                   14191:         }
                   14192:         $path .= (($path ne '')? '&' : '').
                   14193:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14194:                  &Apache::lonhtmlcommon::entity_encode($maptitle).
                   14195:                  ':'.$mapresobj->randompick().
                   14196:                  ':'.$mapresobj->randomout().
                   14197:                  ':'.$mapresobj->encrypted().
                   14198:                  ':'.$mapresobj->randomorder().
                   14199:                  ':'.$mapresobj->is_page();
                   14200:     } else {
                   14201:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14202:         my $ispage = (($type eq 'page')? 1 : '');
                   14203:         if ($mapurl eq 'default') {
                   14204:             $maptitle = 'Main Course Documents';
                   14205:         }
                   14206:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
                   14207:                 &Apache::lonhtmlcommon::entity_encode($maptitle).':::::'.$ispage;
                   14208:     }
                   14209:     unless ($mapurl eq 'default') {
                   14210:         $path = 'default&'.
                   14211:                 &Apache::lonhtmlcommon::entity_encode('Main Course Documents').
                   14212:                 ':::::&'.$path;
                   14213:     }
                   14214:     return $path;
                   14215: }
                   14216: 
1.1094    raeburn  14217: sub captcha_display {
                   14218:     my ($context,$lonhost) = @_;
                   14219:     my ($output,$error);
                   14220:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14221:     if ($captcha eq 'original') {
1.1094    raeburn  14222:         $output = &create_captcha();
                   14223:         unless ($output) {
                   14224:             $error = 'captcha'; 
                   14225:         }
                   14226:     } elsif ($captcha eq 'recaptcha') {
                   14227:         $output = &create_recaptcha($pubkey);
                   14228:         unless ($output) {
1.1095    raeburn  14229:             $error = 'recaptcha'; 
1.1094    raeburn  14230:         }
                   14231:     }
                   14232:     return ($output,$error);
                   14233: }
                   14234: 
                   14235: sub captcha_response {
                   14236:     my ($context,$lonhost) = @_;
                   14237:     my ($captcha_chk,$captcha_error);
                   14238:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  14239:     if ($captcha eq 'original') {
1.1094    raeburn  14240:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14241:     } elsif ($captcha eq 'recaptcha') {
                   14242:         $captcha_chk = &check_recaptcha($privkey);
                   14243:     } else {
                   14244:         $captcha_chk = 1;
                   14245:     }
                   14246:     return ($captcha_chk,$captcha_error);
                   14247: }
                   14248: 
                   14249: sub get_captcha_config {
                   14250:     my ($context,$lonhost) = @_;
1.1095    raeburn  14251:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  14252:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14253:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14254:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  14255:     if ($context eq 'usercreation') {
                   14256:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14257:         if (ref($domconfig{$context}) eq 'HASH') {
                   14258:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14259:             if (ref($hashtocheck) eq 'HASH') {
                   14260:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14261:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14262:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14263:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14264:                     }
                   14265:                     if ($privkey && $pubkey) {
                   14266:                         $captcha = 'recaptcha';
                   14267:                     } else {
                   14268:                         $captcha = 'original';
                   14269:                     }
                   14270:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14271:                     $captcha = 'original';
                   14272:                 }
1.1094    raeburn  14273:             }
1.1095    raeburn  14274:         } else {
                   14275:             $captcha = 'captcha';
                   14276:         }
                   14277:     } elsif ($context eq 'login') {
                   14278:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14279:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14280:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14281:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  14282:             if ($privkey && $pubkey) {
                   14283:                 $captcha = 'recaptcha';
1.1095    raeburn  14284:             } else {
                   14285:                 $captcha = 'original';
1.1094    raeburn  14286:             }
1.1095    raeburn  14287:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14288:             $captcha = 'original';
1.1094    raeburn  14289:         }
                   14290:     }
                   14291:     return ($captcha,$pubkey,$privkey);
                   14292: }
                   14293: 
                   14294: sub create_captcha {
                   14295:     my %captcha_params = &captcha_settings();
                   14296:     my ($output,$maxtries,$tries) = ('',10,0);
                   14297:     while ($tries < $maxtries) {
                   14298:         $tries ++;
                   14299:         my $captcha = Authen::Captcha->new (
                   14300:                                            output_folder => $captcha_params{'output_dir'},
                   14301:                                            data_folder   => $captcha_params{'db_dir'},
                   14302:                                           );
                   14303:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14304: 
                   14305:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14306:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14307:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14308:                      '<input type="text" size="5" name="code" value="" /><br />'.
                   14309:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
                   14310:             last;
                   14311:         }
                   14312:     }
                   14313:     return $output;
                   14314: }
                   14315: 
                   14316: sub captcha_settings {
                   14317:     my %captcha_params = (
                   14318:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14319:                            www_output_dir => "/captchaspool",
                   14320:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14321:                            numchars       => '5',
                   14322:                          );
                   14323:     return %captcha_params;
                   14324: }
                   14325: 
                   14326: sub check_captcha {
                   14327:     my ($captcha_chk,$captcha_error);
                   14328:     my $code = $env{'form.code'};
                   14329:     my $md5sum = $env{'form.crypt'};
                   14330:     my %captcha_params = &captcha_settings();
                   14331:     my $captcha = Authen::Captcha->new(
                   14332:                       output_folder => $captcha_params{'output_dir'},
                   14333:                       data_folder   => $captcha_params{'db_dir'},
                   14334:                   );
                   14335:     my $captcha_chk = $captcha->check_code($code,$md5sum);
                   14336:     my %captcha_hash = (
                   14337:                         0       => 'Code not checked (file error)',
                   14338:                        -1      => 'Failed: code expired',
                   14339:                        -2      => 'Failed: invalid code (not in database)',
                   14340:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   14341:     );
                   14342:     if ($captcha_chk != 1) {
                   14343:         $captcha_error = $captcha_hash{$captcha_chk}
                   14344:     }
                   14345:     return ($captcha_chk,$captcha_error);
                   14346: }
                   14347: 
                   14348: sub create_recaptcha {
                   14349:     my ($pubkey) = @_;
                   14350:     my $captcha = Captcha::reCAPTCHA->new;
                   14351:     return $captcha->get_options_setter({theme => 'white'})."\n".
                   14352:            $captcha->get_html($pubkey).
                   14353:            &mt('If either word is hard to read, [_1] will replace them.',
                   14354:                '<image src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   14355:            '<br /><br />';
                   14356: }
                   14357: 
                   14358: sub check_recaptcha {
                   14359:     my ($privkey) = @_;
                   14360:     my $captcha_chk;
                   14361:     my $captcha = Captcha::reCAPTCHA->new;
                   14362:     my $captcha_result =
                   14363:         $captcha->check_answer(
                   14364:                                 $privkey,
                   14365:                                 $ENV{'REMOTE_ADDR'},
                   14366:                                 $env{'form.recaptcha_challenge_field'},
                   14367:                                 $env{'form.recaptcha_response_field'},
                   14368:                               );
                   14369:     if ($captcha_result->{is_valid}) {
                   14370:         $captcha_chk = 1;
                   14371:     }
                   14372:     return $captcha_chk;
                   14373: }
                   14374: 
1.41      ng       14375: =pod
                   14376: 
                   14377: =back
                   14378: 
1.112     bowersj2 14379: =cut
1.41      ng       14380: 
1.112     bowersj2 14381: 1;
                   14382: __END__;
1.41      ng       14383: 

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