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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.62! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.61 2013/12/30 01:57:04 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.479     albertel   72: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    73: use DateTime::TimeZone;
1.687     raeburn    74: use DateTime::Locale::Catalog;
1.1075.2.14  raeburn    75: use Authen::Captcha;
                     76: use Captcha::reCAPTCHA;
1.117     www        77: 
1.517     raeburn    78: # ---------------------------------------------- Designs
                     79: use vars qw(%defaultdesign);
                     80: 
1.22      www        81: my $readit;
                     82: 
1.517     raeburn    83: 
1.157     matthew    84: ##
                     85: ## Global Variables
                     86: ##
1.46      matthew    87: 
1.643     foxr       88: 
                     89: # ----------------------------------------------- SSI with retries:
                     90: #
                     91: 
                     92: =pod
                     93: 
1.648     raeburn    94: =head1 Server Side include with retries:
1.643     foxr       95: 
                     96: =over 4
                     97: 
1.648     raeburn    98: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       99: 
                    100: Performs an ssi with some number of retries.  Retries continue either
                    101: until the result is ok or until the retry count supplied by the
                    102: caller is exhausted.  
                    103: 
                    104: Inputs:
1.648     raeburn   105: 
                    106: =over 4
                    107: 
1.643     foxr      108: resource   - Identifies the resource to insert.
1.648     raeburn   109: 
1.643     foxr      110: retries    - Count of the number of retries allowed.
1.648     raeburn   111: 
1.643     foxr      112: form       - Hash that identifies the rendering options.
                    113: 
1.648     raeburn   114: =back
                    115: 
                    116: Returns:
                    117: 
                    118: =over 4
                    119: 
1.643     foxr      120: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   121: 
1.643     foxr      122: response   - The response from the last attempt (which may or may not have been successful.
                    123: 
1.648     raeburn   124: =back
                    125: 
                    126: =back
                    127: 
1.643     foxr      128: =cut
                    129: 
                    130: sub ssi_with_retries {
                    131:     my ($resource, $retries, %form) = @_;
                    132: 
                    133: 
                    134:     my $ok = 0;			# True if we got a good response.
                    135:     my $content;
                    136:     my $response;
                    137: 
                    138:     # Try to get the ssi done. within the retries count:
                    139: 
                    140:     do {
                    141: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    142: 	$ok      = $response->is_success;
1.650     www       143:         if (!$ok) {
                    144:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    145:         }
1.643     foxr      146: 	$retries--;
                    147:     } while (!$ok && ($retries > 0));
                    148: 
                    149:     if (!$ok) {
                    150: 	$content = '';		# On error return an empty content.
                    151:     }
                    152:     return ($content, $response);
                    153: 
                    154: }
                    155: 
                    156: 
                    157: 
1.20      www       158: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  159: my %language;
1.124     www       160: my %supported_language;
1.1048    foxr      161: my %latex_language;		# For choosing hyphenation in <transl..>
                    162: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  163: my %cprtag;
1.192     taceyjo1  164: my %scprtag;
1.351     www       165: my %fe; my %fd; my %fm;
1.41      ng        166: my %category_extensions;
1.12      harris41  167: 
1.46      matthew   168: # ---------------------------------------------- Thesaurus variables
1.144     matthew   169: #
                    170: # %Keywords:
                    171: #      A hash used by &keyword to determine if a word is considered a keyword.
                    172: # $thesaurus_db_file 
                    173: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   174: 
                    175: my %Keywords;
                    176: my $thesaurus_db_file;
                    177: 
1.144     matthew   178: #
                    179: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    180: # thesaurus.tab, and filecategories.tab.
                    181: #
1.18      www       182: BEGIN {
1.46      matthew   183:     # Variable initialization
                    184:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    185:     #
1.22      www       186:     unless ($readit) {
1.12      harris41  187: # ------------------------------------------------------------------- languages
                    188:     {
1.158     raeburn   189:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    190:                                    '/language.tab';
                    191:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  192:             while (my $line = <$fh>) {
                    193:                 next if ($line=~/^\#/);
                    194:                 chomp($line);
1.1048    foxr      195:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   196:                 $language{$key}=$val.' - '.$enc;
                    197:                 if ($sup) {
                    198:                     $supported_language{$key}=$sup;
                    199:                 }
1.1048    foxr      200: 		if ($latex) {
                    201: 		    $latex_language_bykey{$key} = $latex;
                    202: 		    $latex_language{$two} = $latex;
                    203: 		}
1.158     raeburn   204:             }
                    205:             close($fh);
                    206:         }
1.12      harris41  207:     }
                    208: # ------------------------------------------------------------------ copyrights
                    209:     {
1.158     raeburn   210:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    211:                                   '/copyright.tab';
                    212:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  213:             while (my $line = <$fh>) {
                    214:                 next if ($line=~/^\#/);
                    215:                 chomp($line);
                    216:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   217:                 $cprtag{$key}=$val;
                    218:             }
                    219:             close($fh);
                    220:         }
1.12      harris41  221:     }
1.351     www       222: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  223:     {
                    224:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    225:                                   '/source_copyright.tab';
                    226:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  227:             while (my $line = <$fh>) {
                    228:                 next if ($line =~ /^\#/);
                    229:                 chomp($line);
                    230:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  231:                 $scprtag{$key}=$val;
                    232:             }
                    233:             close($fh);
                    234:         }
                    235:     }
1.63      www       236: 
1.517     raeburn   237: # -------------------------------------------------------------- default domain designs
1.63      www       238:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   239:     my $designfile = $designdir.'/default.tab';
                    240:     if ( open (my $fh,"<$designfile") ) {
                    241:         while (my $line = <$fh>) {
                    242:             next if ($line =~ /^\#/);
                    243:             chomp($line);
                    244:             my ($key,$val)=(split(/\=/,$line));
                    245:             if ($val) { $defaultdesign{$key}=$val; }
                    246:         }
                    247:         close($fh);
1.63      www       248:     }
                    249: 
1.15      harris41  250: # ------------------------------------------------------------- file categories
                    251:     {
1.158     raeburn   252:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    253:                                   '/filecategories.tab';
                    254:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  255: 	    while (my $line = <$fh>) {
                    256: 		next if ($line =~ /^\#/);
                    257: 		chomp($line);
                    258:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   259:                 push @{$category_extensions{lc($category)}},$extension;
                    260:             }
                    261:             close($fh);
                    262:         }
                    263: 
1.15      harris41  264:     }
1.12      harris41  265: # ------------------------------------------------------------------ file types
                    266:     {
1.158     raeburn   267:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    268:                '/filetypes.tab';
                    269:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  270:             while (my $line = <$fh>) {
                    271: 		next if ($line =~ /^\#/);
                    272: 		chomp($line);
                    273:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   274:                 if ($descr ne '') {
                    275:                     $fe{$ending}=lc($emb);
                    276:                     $fd{$ending}=$descr;
1.351     www       277:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   278:                 }
                    279:             }
                    280:             close($fh);
                    281:         }
1.12      harris41  282:     }
1.22      www       283:     &Apache::lonnet::logthis(
1.705     tempelho  284:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       285:     $readit=1;
1.46      matthew   286:     }  # end of unless($readit) 
1.32      matthew   287:     
                    288: }
1.112     bowersj2  289: 
1.42      matthew   290: ###############################################################
                    291: ##           HTML and Javascript Helper Functions            ##
                    292: ###############################################################
                    293: 
                    294: =pod 
                    295: 
1.112     bowersj2  296: =head1 HTML and Javascript Functions
1.42      matthew   297: 
1.112     bowersj2  298: =over 4
                    299: 
1.648     raeburn   300: =item * &browser_and_searcher_javascript()
1.112     bowersj2  301: 
                    302: X<browsing, javascript>X<searching, javascript>Returns a string
                    303: containing javascript with two functions, C<openbrowser> and
                    304: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    305: tags.
1.42      matthew   306: 
1.648     raeburn   307: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   308: 
                    309: inputs: formname, elementname, only, omit
                    310: 
                    311: formname and elementname indicate the name of the html form and name of
                    312: the element that the results of the browsing selection are to be placed in. 
                    313: 
                    314: Specifying 'only' will restrict the browser to displaying only files
1.185     www       315: with the given extension.  Can be a comma separated list.
1.42      matthew   316: 
                    317: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       318: with the given extension.  Can be a comma separated list.
1.42      matthew   319: 
1.648     raeburn   320: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   321: 
                    322: Inputs: formname, elementname
                    323: 
                    324: formname and elementname specify the name of the html form and the name
                    325: of the element the selection from the search results will be placed in.
1.542     raeburn   326: 
1.42      matthew   327: =cut
                    328: 
                    329: sub browser_and_searcher_javascript {
1.199     albertel  330:     my ($mode)=@_;
                    331:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  332:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   333:     return <<END;
1.219     albertel  334: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   335:     var editbrowser = null;
1.135     albertel  336:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       337:         var url = '$resurl/?';
1.42      matthew   338:         if (editbrowser == null) {
                    339:             url += 'launch=1&';
                    340:         }
                    341:         url += 'catalogmode=interactive&';
1.199     albertel  342:         url += 'mode=$mode&';
1.611     albertel  343:         url += 'inhibitmenu=yes&';
1.42      matthew   344:         url += 'form=' + formname + '&';
                    345:         if (only != null) {
                    346:             url += 'only=' + only + '&';
1.217     albertel  347:         } else {
                    348:             url += 'only=&';
                    349: 	}
1.42      matthew   350:         if (omit != null) {
                    351:             url += 'omit=' + omit + '&';
1.217     albertel  352:         } else {
                    353:             url += 'omit=&';
                    354: 	}
1.135     albertel  355:         if (titleelement != null) {
                    356:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  357:         } else {
                    358: 	    url += 'titleelement=&';
                    359: 	}
1.42      matthew   360:         url += 'element=' + elementname + '';
                    361:         var title = 'Browser';
1.435     albertel  362:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   363:         options += ',width=700,height=600';
                    364:         editbrowser = open(url,title,options,'1');
                    365:         editbrowser.focus();
                    366:     }
                    367:     var editsearcher;
1.135     albertel  368:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   369:         var url = '/adm/searchcat?';
                    370:         if (editsearcher == null) {
                    371:             url += 'launch=1&';
                    372:         }
                    373:         url += 'catalogmode=interactive&';
1.199     albertel  374:         url += 'mode=$mode&';
1.42      matthew   375:         url += 'form=' + formname + '&';
1.135     albertel  376:         if (titleelement != null) {
                    377:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  378:         } else {
                    379: 	    url += 'titleelement=&';
                    380: 	}
1.42      matthew   381:         url += 'element=' + elementname + '';
                    382:         var title = 'Search';
1.435     albertel  383:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   384:         options += ',width=700,height=600';
                    385:         editsearcher = open(url,title,options,'1');
                    386:         editsearcher.focus();
                    387:     }
1.219     albertel  388: // END LON-CAPA Internal -->
1.42      matthew   389: END
1.170     www       390: }
                    391: 
                    392: sub lastresurl {
1.258     albertel  393:     if ($env{'environment.lastresurl'}) {
                    394: 	return $env{'environment.lastresurl'}
1.170     www       395:     } else {
                    396: 	return '/res';
                    397:     }
                    398: }
                    399: 
                    400: sub storeresurl {
                    401:     my $resurl=&Apache::lonnet::clutter(shift);
                    402:     unless ($resurl=~/^\/res/) { return 0; }
                    403:     $resurl=~s/\/$//;
                    404:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   405:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       406:     return 1;
1.42      matthew   407: }
                    408: 
1.74      www       409: sub studentbrowser_javascript {
1.111     www       410:    unless (
1.258     albertel  411:             (($env{'request.course.id'}) && 
1.302     albertel  412:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    413: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    414: 					  '/'.$env{'request.course.sec'})
                    415: 	      ))
1.258     albertel  416:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       417:           ) { return ''; }  
1.74      www       418:    return (<<'ENDSTDBRW');
1.776     bisitz    419: <script type="text/javascript" language="Javascript">
1.824     bisitz    420: // <![CDATA[
1.74      www       421:     var stdeditbrowser;
1.999     www       422:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       423:         var url = '/adm/pickstudent?';
                    424:         var filter;
1.558     albertel  425: 	if (!ignorefilter) {
                    426: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    427: 	}
1.74      www       428:         if (filter != null) {
                    429:            if (filter != '') {
                    430:                url += 'filter='+filter+'&';
                    431: 	   }
                    432:         }
                    433:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       434:                                     '&udomelement='+udom+
                    435:                                     '&clicker='+clicker;
1.111     www       436: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   437:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       438:         var title = 'Student_Browser';
1.74      www       439:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    440:         options += ',width=700,height=600';
                    441:         stdeditbrowser = open(url,title,options,'1');
                    442:         stdeditbrowser.focus();
                    443:     }
1.824     bisitz    444: // ]]>
1.74      www       445: </script>
                    446: ENDSTDBRW
                    447: }
1.42      matthew   448: 
1.1003    www       449: sub resourcebrowser_javascript {
                    450:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       451:    return (<<'ENDRESBRW');
1.1003    www       452: <script type="text/javascript" language="Javascript">
                    453: // <![CDATA[
                    454:     var reseditbrowser;
1.1004    www       455:     function openresbrowser(formname,reslink) {
1.1005    www       456:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       457:         var title = 'Resource_Browser';
                    458:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       459:         options += ',width=700,height=500';
1.1004    www       460:         reseditbrowser = open(url,title,options,'1');
                    461:         reseditbrowser.focus();
1.1003    www       462:     }
                    463: // ]]>
                    464: </script>
1.1004    www       465: ENDRESBRW
1.1003    www       466: }
                    467: 
1.74      www       468: sub selectstudent_link {
1.999     www       469:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    470:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    471:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    472:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  473:    if ($env{'request.course.id'}) {  
1.302     albertel  474:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    475: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    476: 					'/'.$env{'request.course.sec'})) {
1.111     www       477: 	   return '';
                    478:        }
1.999     www       479:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   480:        if ($courseadvonly)  {
                    481:            $callargs .= ",'',1,1";
                    482:        }
                    483:        return '<span class="LC_nobreak">'.
                    484:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    485:               &mt('Select User').'</a></span>';
1.74      www       486:    }
1.258     albertel  487:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       488:        $callargs .= ",'',1"; 
1.793     raeburn   489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.111     www       492:    }
                    493:    return '';
1.91      www       494: }
                    495: 
1.1004    www       496: sub selectresource_link {
                    497:    my ($form,$reslink,$arg)=@_;
                    498:    
                    499:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    500:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    501:    unless ($env{'request.course.id'}) { return $arg; }
                    502:    return '<span class="LC_nobreak">'.
                    503:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    504:               $arg.'</a></span>';
                    505: }
                    506: 
                    507: 
                    508: 
1.653     raeburn   509: sub authorbrowser_javascript {
                    510:     return <<"ENDAUTHORBRW";
1.776     bisitz    511: <script type="text/javascript" language="JavaScript">
1.824     bisitz    512: // <![CDATA[
1.653     raeburn   513: var stdeditbrowser;
                    514: 
                    515: function openauthorbrowser(formname,udom) {
                    516:     var url = '/adm/pickauthor?';
                    517:     url += 'form='+formname+'&roledom='+udom;
                    518:     var title = 'Author_Browser';
                    519:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    520:     options += ',width=700,height=600';
                    521:     stdeditbrowser = open(url,title,options,'1');
                    522:     stdeditbrowser.focus();
                    523: }
                    524: 
1.824     bisitz    525: // ]]>
1.653     raeburn   526: </script>
                    527: ENDAUTHORBRW
                    528: }
                    529: 
1.91      www       530: sub coursebrowser_javascript {
1.1075.2.31  raeburn   531:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    532:         $credits_element) = @_;
1.932     raeburn   533:     my $wintitle = 'Course_Browser';
1.931     raeburn   534:     if ($crstype eq 'Community') {
1.932     raeburn   535:         $wintitle = 'Community_Browser';
1.909     raeburn   536:     }
1.876     raeburn   537:     my $id_functions = &javascript_index_functions();
                    538:     my $output = '
1.776     bisitz    539: <script type="text/javascript" language="JavaScript">
1.824     bisitz    540: // <![CDATA[
1.468     raeburn   541:     var stdeditbrowser;'."\n";
1.876     raeburn   542: 
                    543:     $output .= <<"ENDSTDBRW";
1.909     raeburn   544:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       545:         var url = '/adm/pickcourse?';
1.895     raeburn   546:         var formid = getFormIdByName(formname);
1.876     raeburn   547:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  548:         if (domainfilter != null) {
                    549:            if (domainfilter != '') {
                    550:                url += 'domainfilter='+domainfilter+'&';
                    551: 	   }
                    552:         }
1.91      www       553:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  554: 	                            '&cdomelement='+udom+
                    555:                                     '&cnameelement='+desc;
1.468     raeburn   556:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   557:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   558:                 url += '&roleelement='+extra_element;
                    559:                 if (domainfilter == null || domainfilter == '') {
                    560:                     url += '&domainfilter='+extra_element;
                    561:                 }
1.234     raeburn   562:             }
1.468     raeburn   563:             else {
                    564:                 if (formname == 'portform') {
                    565:                     url += '&setroles='+extra_element;
1.800     raeburn   566:                 } else {
                    567:                     if (formname == 'rules') {
                    568:                         url += '&fixeddom='+extra_element; 
                    569:                     }
1.468     raeburn   570:                 }
                    571:             }     
1.230     raeburn   572:         }
1.909     raeburn   573:         if (type != null && type != '') {
                    574:             url += '&type='+type;
                    575:         }
                    576:         if (type_elem != null && type_elem != '') {
                    577:             url += '&typeelement='+type_elem;
                    578:         }
1.872     raeburn   579:         if (formname == 'ccrs') {
                    580:             var ownername = document.forms[formid].ccuname.value;
                    581:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    582:             url += '&cloner='+ownername+':'+ownerdom;
                    583:         }
1.293     raeburn   584:         if (multflag !=null && multflag != '') {
                    585:             url += '&multiple='+multflag;
                    586:         }
1.909     raeburn   587:         var title = '$wintitle';
1.91      www       588:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    589:         options += ',width=700,height=600';
                    590:         stdeditbrowser = open(url,title,options,'1');
                    591:         stdeditbrowser.focus();
                    592:     }
1.876     raeburn   593: $id_functions
                    594: ENDSTDBRW
1.1075.2.31  raeburn   595:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    596:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    597:                                       $credits_element);
1.876     raeburn   598:     }
                    599:     $output .= '
                    600: // ]]>
                    601: </script>';
                    602:     return $output;
                    603: }
                    604: 
                    605: sub javascript_index_functions {
                    606:     return <<"ENDJS";
                    607: 
                    608: function getFormIdByName(formname) {
                    609:     for (var i=0;i<document.forms.length;i++) {
                    610:         if (document.forms[i].name == formname) {
                    611:             return i;
                    612:         }
                    613:     }
                    614:     return -1;
                    615: }
                    616: 
                    617: function getIndexByName(formid,item) {
                    618:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    619:         if (document.forms[formid].elements[i].name == item) {
                    620:             return i;
                    621:         }
                    622:     }
                    623:     return -1;
                    624: }
1.468     raeburn   625: 
1.876     raeburn   626: function getDomainFromSelectbox(formname,udom) {
                    627:     var userdom;
                    628:     var formid = getFormIdByName(formname);
                    629:     if (formid > -1) {
                    630:         var domid = getIndexByName(formid,udom);
                    631:         if (domid > -1) {
                    632:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    633:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    634:             }
                    635:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    636:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   637:             }
                    638:         }
                    639:     }
1.876     raeburn   640:     return userdom;
                    641: }
                    642: 
                    643: ENDJS
1.468     raeburn   644: 
1.876     raeburn   645: }
                    646: 
1.1017    raeburn   647: sub javascript_array_indexof {
1.1018    raeburn   648:     return <<ENDJS;
1.1017    raeburn   649: <script type="text/javascript" language="JavaScript">
                    650: // <![CDATA[
                    651: 
                    652: if (!Array.prototype.indexOf) {
                    653:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    654:         "use strict";
                    655:         if (this === void 0 || this === null) {
                    656:             throw new TypeError();
                    657:         }
                    658:         var t = Object(this);
                    659:         var len = t.length >>> 0;
                    660:         if (len === 0) {
                    661:             return -1;
                    662:         }
                    663:         var n = 0;
                    664:         if (arguments.length > 0) {
                    665:             n = Number(arguments[1]);
                    666:             if (n !== n) { // shortcut for verifying if it's NaN
                    667:                 n = 0;
                    668:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    669:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    670:             }
                    671:         }
                    672:         if (n >= len) {
                    673:             return -1;
                    674:         }
                    675:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    676:         for (; k < len; k++) {
                    677:             if (k in t && t[k] === searchElement) {
                    678:                 return k;
                    679:             }
                    680:         }
                    681:         return -1;
                    682:     }
                    683: }
                    684: 
                    685: // ]]>
                    686: </script>
                    687: 
                    688: ENDJS
                    689: 
                    690: }
                    691: 
1.876     raeburn   692: sub userbrowser_javascript {
                    693:     my $id_functions = &javascript_index_functions();
                    694:     return <<"ENDUSERBRW";
                    695: 
1.888     raeburn   696: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   697:     var url = '/adm/pickuser?';
                    698:     var userdom = getDomainFromSelectbox(formname,udom);
                    699:     if (userdom != null) {
                    700:        if (userdom != '') {
                    701:            url += 'srchdom='+userdom+'&';
                    702:        }
                    703:     }
                    704:     url += 'form=' + formname + '&unameelement='+uname+
                    705:                                 '&udomelement='+udom+
                    706:                                 '&ulastelement='+ulast+
                    707:                                 '&ufirstelement='+ufirst+
                    708:                                 '&uemailelement='+uemail+
1.881     raeburn   709:                                 '&hideudomelement='+hideudom+
                    710:                                 '&coursedom='+crsdom;
1.888     raeburn   711:     if ((caller != null) && (caller != undefined)) {
                    712:         url += '&caller='+caller;
                    713:     }
1.876     raeburn   714:     var title = 'User_Browser';
                    715:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    716:     options += ',width=700,height=600';
                    717:     var stdeditbrowser = open(url,title,options,'1');
                    718:     stdeditbrowser.focus();
                    719: }
                    720: 
1.888     raeburn   721: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   722:     var formid = getFormIdByName(formname);
                    723:     if (formid > -1) {
1.888     raeburn   724:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   725:         var domid = getIndexByName(formid,udom);
                    726:         var hidedomid = getIndexByName(formid,origdom);
                    727:         if (hidedomid > -1) {
                    728:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   729:             var unameval = document.forms[formid].elements[unameid].value;
                    730:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    731:                 if (domid > -1) {
                    732:                     var slct = document.forms[formid].elements[domid];
                    733:                     if (slct.type == 'select-one') {
                    734:                         var i;
                    735:                         for (i=0;i<slct.length;i++) {
                    736:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    737:                         }
                    738:                     }
                    739:                     if (slct.type == 'hidden') {
                    740:                         slct.value = fixeddom;
1.876     raeburn   741:                     }
                    742:                 }
1.468     raeburn   743:             }
                    744:         }
                    745:     }
1.876     raeburn   746:     return;
                    747: }
                    748: 
                    749: $id_functions
                    750: ENDUSERBRW
1.468     raeburn   751: }
                    752: 
                    753: sub setsec_javascript {
1.1075.2.31  raeburn   754:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   755:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    756:         $communityrolestr);
                    757:     if ($role_element ne '') {
                    758:         my @allroles = ('st','ta','ep','in','ad');
                    759:         foreach my $crstype ('Course','Community') {
                    760:             if ($crstype eq 'Community') {
                    761:                 foreach my $role (@allroles) {
                    762:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    763:                 }
                    764:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    765:             } else {
                    766:                 foreach my $role (@allroles) {
                    767:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    768:                 }
                    769:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    770:             }
                    771:         }
                    772:         $rolestr = '"'.join('","',@allroles).'"';
                    773:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    774:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    775:     }
1.468     raeburn   776:     my $setsections = qq|
                    777: function setSect(sectionlist) {
1.629     raeburn   778:     var sectionsArray = new Array();
                    779:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    780:         sectionsArray = sectionlist.split(",");
                    781:     }
1.468     raeburn   782:     var numSections = sectionsArray.length;
                    783:     document.$formname.$sec_element.length = 0;
                    784:     if (numSections == 0) {
                    785:         document.$formname.$sec_element.multiple=false;
                    786:         document.$formname.$sec_element.size=1;
                    787:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    788:     } else {
                    789:         if (numSections == 1) {
                    790:             document.$formname.$sec_element.multiple=false;
                    791:             document.$formname.$sec_element.size=1;
                    792:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    793:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    794:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    795:         } else {
                    796:             for (var i=0; i<numSections; i++) {
                    797:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    798:             }
                    799:             document.$formname.$sec_element.multiple=true
                    800:             if (numSections < 3) {
                    801:                 document.$formname.$sec_element.size=numSections;
                    802:             } else {
                    803:                 document.$formname.$sec_element.size=3;
                    804:             }
                    805:             document.$formname.$sec_element.options[0].selected = false
                    806:         }
                    807:     }
1.91      www       808: }
1.905     raeburn   809: 
                    810: function setRole(crstype) {
1.468     raeburn   811: |;
1.905     raeburn   812:     if ($role_element eq '') {
                    813:         $setsections .= '    return;
                    814: }
                    815: ';
                    816:     } else {
                    817:         $setsections .= qq|
                    818:     var elementLength = document.$formname.$role_element.length;
                    819:     var allroles = Array($rolestr);
                    820:     var courserolenames = Array($courserolestr);
                    821:     var communityrolenames = Array($communityrolestr);
                    822:     if (elementLength != undefined) {
                    823:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    824:             if (crstype == 'Course') {
                    825:                 return;
                    826:             } else {
                    827:                 allroles[5] = 'co';
                    828:                 for (var i=0; i<6; i++) {
                    829:                     document.$formname.$role_element.options[i].value = allroles[i];
                    830:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    831:                 }
                    832:             }
                    833:         } else {
                    834:             if (crstype == 'Community') {
                    835:                 return;
                    836:             } else {
                    837:                 allroles[5] = 'cc';
                    838:                 for (var i=0; i<6; i++) {
                    839:                     document.$formname.$role_element.options[i].value = allroles[i];
                    840:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    841:                 }
                    842:             }
                    843:         }
                    844:     }
                    845:     return;
                    846: }
                    847: |;
                    848:     }
1.1075.2.31  raeburn   849:     if ($credits_element) {
                    850:         $setsections .= qq|
                    851: function setCredits(defaultcredits) {
                    852:     document.$formname.$credits_element.value = defaultcredits;
                    853:     return;
                    854: }
                    855: |;
                    856:     }
1.468     raeburn   857:     return $setsections;
                    858: }
                    859: 
1.91      www       860: sub selectcourse_link {
1.909     raeburn   861:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    862:        $typeelement) = @_;
                    863:    my $type = $selecttype;
1.871     raeburn   864:    my $linktext = &mt('Select Course');
                    865:    if ($selecttype eq 'Community') {
1.909     raeburn   866:        $linktext = &mt('Select Community');
1.906     raeburn   867:    } elsif ($selecttype eq 'Course/Community') {
                    868:        $linktext = &mt('Select Course/Community');
1.909     raeburn   869:        $type = '';
1.1019    raeburn   870:    } elsif ($selecttype eq 'Select') {
                    871:        $linktext = &mt('Select');
                    872:        $type = '';
1.871     raeburn   873:    }
1.787     bisitz    874:    return '<span class="LC_nobreak">'
                    875:          ."<a href='"
                    876:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    877:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   878:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   879:          ."'>".$linktext.'</a>'
1.787     bisitz    880:          .'</span>';
1.74      www       881: }
1.42      matthew   882: 
1.653     raeburn   883: sub selectauthor_link {
                    884:    my ($form,$udom)=@_;
                    885:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    886:           &mt('Select Author').'</a>';
                    887: }
                    888: 
1.876     raeburn   889: sub selectuser_link {
1.881     raeburn   890:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   891:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   892:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   893:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   894:            ');">'.$linktext.'</a>';
1.876     raeburn   895: }
                    896: 
1.273     raeburn   897: sub check_uncheck_jscript {
                    898:     my $jscript = <<"ENDSCRT";
                    899: function checkAll(field) {
                    900:     if (field.length > 0) {
                    901:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   902:             if (!field[i].disabled) {
                    903:                 field[i].checked = true;
                    904:             }
1.273     raeburn   905:         }
                    906:     } else {
1.1075.2.14  raeburn   907:         if (!field.disabled) {
                    908:             field.checked = true;
                    909:         }
1.273     raeburn   910:     }
                    911: }
                    912:  
                    913: function uncheckAll(field) {
                    914:     if (field.length > 0) {
                    915:         for (i = 0; i < field.length; i++) {
                    916:             field[i].checked = false ;
1.543     albertel  917:         }
                    918:     } else {
1.273     raeburn   919:         field.checked = false ;
                    920:     }
                    921: }
                    922: ENDSCRT
                    923:     return $jscript;
                    924: }
                    925: 
1.656     www       926: sub select_timezone {
1.659     raeburn   927:    my ($name,$selected,$onchange,$includeempty)=@_;
                    928:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    929:    if ($includeempty) {
                    930:        $output .= '<option value=""';
                    931:        if (($selected eq '') || ($selected eq 'local')) {
                    932:            $output .= ' selected="selected" ';
                    933:        }
                    934:        $output .= '> </option>';
                    935:    }
1.657     raeburn   936:    my @timezones = DateTime::TimeZone->all_names;
                    937:    foreach my $tzone (@timezones) {
                    938:        $output.= '<option value="'.$tzone.'"';
                    939:        if ($tzone eq $selected) {
                    940:            $output.=' selected="selected"';
                    941:        }
                    942:        $output.=">$tzone</option>\n";
1.656     www       943:    }
                    944:    $output.="</select>";
                    945:    return $output;
                    946: }
1.273     raeburn   947: 
1.687     raeburn   948: sub select_datelocale {
                    949:     my ($name,$selected,$onchange,$includeempty)=@_;
                    950:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    951:     if ($includeempty) {
                    952:         $output .= '<option value=""';
                    953:         if ($selected eq '') {
                    954:             $output .= ' selected="selected" ';
                    955:         }
                    956:         $output .= '> </option>';
                    957:     }
                    958:     my (@possibles,%locale_names);
                    959:     my @locales = DateTime::Locale::Catalog::Locales;
                    960:     foreach my $locale (@locales) {
                    961:         if (ref($locale) eq 'HASH') {
                    962:             my $id = $locale->{'id'};
                    963:             if ($id ne '') {
                    964:                 my $en_terr = $locale->{'en_territory'};
                    965:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   966:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   967:                 if (grep(/^en$/,@languages) || !@languages) {
                    968:                     if ($en_terr ne '') {
                    969:                         $locale_names{$id} = '('.$en_terr.')';
                    970:                     } elsif ($native_terr ne '') {
                    971:                         $locale_names{$id} = $native_terr;
                    972:                     }
                    973:                 } else {
                    974:                     if ($native_terr ne '') {
                    975:                         $locale_names{$id} = $native_terr.' ';
                    976:                     } elsif ($en_terr ne '') {
                    977:                         $locale_names{$id} = '('.$en_terr.')';
                    978:                     }
                    979:                 }
                    980:                 push (@possibles,$id);
                    981:             }
                    982:         }
                    983:     }
                    984:     foreach my $item (sort(@possibles)) {
                    985:         $output.= '<option value="'.$item.'"';
                    986:         if ($item eq $selected) {
                    987:             $output.=' selected="selected"';
                    988:         }
                    989:         $output.=">$item";
                    990:         if ($locale_names{$item} ne '') {
                    991:             $output.="  $locale_names{$item}</option>\n";
                    992:         }
                    993:         $output.="</option>\n";
                    994:     }
                    995:     $output.="</select>";
                    996:     return $output;
                    997: }
                    998: 
1.792     raeburn   999: sub select_language {
                   1000:     my ($name,$selected,$includeempty) = @_;
                   1001:     my %langchoices;
                   1002:     if ($includeempty) {
1.1075.2.32  raeburn  1003:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1004:     }
                   1005:     foreach my $id (&languageids()) {
                   1006:         my $code = &supportedlanguagecode($id);
                   1007:         if ($code) {
                   1008:             $langchoices{$code} = &plainlanguagedescription($id);
                   1009:         }
                   1010:     }
1.1075.2.32  raeburn  1011:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1012:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1013: }
                   1014: 
1.42      matthew  1015: =pod
1.36      matthew  1016: 
1.648     raeburn  1017: =item * &linked_select_forms(...)
1.36      matthew  1018: 
                   1019: linked_select_forms returns a string containing a <script></script> block
                   1020: and html for two <select> menus.  The select menus will be linked in that
                   1021: changing the value of the first menu will result in new values being placed
                   1022: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1023: order unless a defined order is provided.
1.36      matthew  1024: 
                   1025: linked_select_forms takes the following ordered inputs:
                   1026: 
                   1027: =over 4
                   1028: 
1.112     bowersj2 1029: =item * $formname, the name of the <form> tag
1.36      matthew  1030: 
1.112     bowersj2 1031: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1032: 
1.112     bowersj2 1033: =item * $firstdefault, the default value for the first menu
1.36      matthew  1034: 
1.112     bowersj2 1035: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1036: 
1.112     bowersj2 1037: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1038: 
1.112     bowersj2 1039: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1040: 
1.609     raeburn  1041: =item * $menuorder, the order of values in the first menu
                   1042: 
1.1075.2.31  raeburn  1043: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1044:         event for the first <select> tag
                   1045: 
                   1046: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1047:         event for the second <select> tag
                   1048: 
1.41      ng       1049: =back 
                   1050: 
1.36      matthew  1051: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1052: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1053: values for the first select menu.  The text that coincides with the 
1.41      ng       1054: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1055: and text for the second menu are given in the hash pointed to by 
                   1056: $menu{$choice1}->{'select2'}.  
                   1057: 
1.112     bowersj2 1058:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1059:                        default => "B3",
                   1060:                        select2 => { 
                   1061:                            B1 => "Choice B1",
                   1062:                            B2 => "Choice B2",
                   1063:                            B3 => "Choice B3",
                   1064:                            B4 => "Choice B4"
1.609     raeburn  1065:                            },
                   1066:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1067:                    },
                   1068:                A2 => { text =>"Choice A2" ,
                   1069:                        default => "C2",
                   1070:                        select2 => { 
                   1071:                            C1 => "Choice C1",
                   1072:                            C2 => "Choice C2",
                   1073:                            C3 => "Choice C3"
1.609     raeburn  1074:                            },
                   1075:                        order => ['C2','C1','C3'],
1.112     bowersj2 1076:                    },
                   1077:                A3 => { text =>"Choice A3" ,
                   1078:                        default => "D6",
                   1079:                        select2 => { 
                   1080:                            D1 => "Choice D1",
                   1081:                            D2 => "Choice D2",
                   1082:                            D3 => "Choice D3",
                   1083:                            D4 => "Choice D4",
                   1084:                            D5 => "Choice D5",
                   1085:                            D6 => "Choice D6",
                   1086:                            D7 => "Choice D7"
1.609     raeburn  1087:                            },
                   1088:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1089:                    }
                   1090:                );
1.36      matthew  1091: 
                   1092: =cut
                   1093: 
                   1094: sub linked_select_forms {
                   1095:     my ($formname,
                   1096:         $middletext,
                   1097:         $firstdefault,
                   1098:         $firstselectname,
                   1099:         $secondselectname, 
1.609     raeburn  1100:         $hashref,
                   1101:         $menuorder,
1.1075.2.31  raeburn  1102:         $onchangefirst,
                   1103:         $onchangesecond
1.36      matthew  1104:         ) = @_;
                   1105:     my $second = "document.$formname.$secondselectname";
                   1106:     my $first = "document.$formname.$firstselectname";
                   1107:     # output the javascript to do the changing
                   1108:     my $result = '';
1.776     bisitz   1109:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1110:     $result.="// <![CDATA[\n";
1.36      matthew  1111:     $result.="var select2data = new Object();\n";
                   1112:     $" = '","';
                   1113:     my $debug = '';
                   1114:     foreach my $s1 (sort(keys(%$hashref))) {
                   1115:         $result.="select2data.d_$s1 = new Object();\n";        
                   1116:         $result.="select2data.d_$s1.def = new String('".
                   1117:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1118:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1119:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1120:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1121:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1122:         }
1.36      matthew  1123:         $result.="\"@s2values\");\n";
                   1124:         $result.="select2data.d_$s1.texts = new Array(";        
                   1125:         my @s2texts;
                   1126:         foreach my $value (@s2values) {
                   1127:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1128:         }
                   1129:         $result.="\"@s2texts\");\n";
                   1130:     }
                   1131:     $"=' ';
                   1132:     $result.= <<"END";
                   1133: 
                   1134: function select1_changed() {
                   1135:     // Determine new choice
                   1136:     var newvalue = "d_" + $first.value;
                   1137:     // update select2
                   1138:     var values     = select2data[newvalue].values;
                   1139:     var texts      = select2data[newvalue].texts;
                   1140:     var select2def = select2data[newvalue].def;
                   1141:     var i;
                   1142:     // out with the old
                   1143:     for (i = 0; i < $second.options.length; i++) {
                   1144:         $second.options[i] = null;
                   1145:     }
                   1146:     // in with the nuclear
                   1147:     for (i=0;i<values.length; i++) {
                   1148:         $second.options[i] = new Option(values[i]);
1.143     matthew  1149:         $second.options[i].value = values[i];
1.36      matthew  1150:         $second.options[i].text = texts[i];
                   1151:         if (values[i] == select2def) {
                   1152:             $second.options[i].selected = true;
                   1153:         }
                   1154:     }
                   1155: }
1.824     bisitz   1156: // ]]>
1.36      matthew  1157: </script>
                   1158: END
                   1159:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1160:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1161:     my @order = sort(keys(%{$hashref}));
                   1162:     if (ref($menuorder) eq 'ARRAY') {
                   1163:         @order = @{$menuorder};
                   1164:     }
                   1165:     foreach my $value (@order) {
1.36      matthew  1166:         $result.="    <option value=\"$value\" ";
1.253     albertel 1167:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1168:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1169:     }
                   1170:     $result .= "</select>\n";
                   1171:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1172:     $result .= $middletext;
1.1075.2.31  raeburn  1173:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1174:     if ($onchangesecond) {
                   1175:         $result .= ' onchange="'.$onchangesecond.'"';
                   1176:     }
                   1177:     $result .= ">\n";
1.36      matthew  1178:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1179:     
                   1180:     my @secondorder = sort(keys(%select2));
                   1181:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1182:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1183:     }
                   1184:     foreach my $value (@secondorder) {
1.36      matthew  1185:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1186:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1187:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1188:     }
                   1189:     $result .= "</select>\n";
                   1190:     #    return $debug;
                   1191:     return $result;
                   1192: }   #  end of sub linked_select_forms {
                   1193: 
1.45      matthew  1194: =pod
1.44      bowersj2 1195: 
1.973     raeburn  1196: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1197: 
1.112     bowersj2 1198: Returns a string corresponding to an HTML link to the given help
                   1199: $topic, where $topic corresponds to the name of a .tex file in
                   1200: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1201: spaces. 
                   1202: 
                   1203: $text will optionally be linked to the same topic, allowing you to
                   1204: link text in addition to the graphic. If you do not want to link
                   1205: text, but wish to specify one of the later parameters, pass an
                   1206: empty string. 
                   1207: 
                   1208: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1209: the link will not open a new window. If false, the link will open
                   1210: a new window using Javascript. (Default is false.) 
                   1211: 
                   1212: $width and $height are optional numerical parameters that will
                   1213: override the width and height of the popped up window, which may
1.973     raeburn  1214: be useful for certain help topics with big pictures included.
                   1215: 
                   1216: $imgid is the id of the img tag used for the help icon. This may be
                   1217: used in a javascript call to switch the image src.  See 
                   1218: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1219: 
                   1220: =cut
                   1221: 
                   1222: sub help_open_topic {
1.973     raeburn  1223:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1224:     $text = "" if (not defined $text);
1.44      bowersj2 1225:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1226:     $width = 500 if (not defined $width);
1.44      bowersj2 1227:     $height = 400 if (not defined $height);
                   1228:     my $filename = $topic;
                   1229:     $filename =~ s/ /_/g;
                   1230: 
1.48      bowersj2 1231:     my $template = "";
                   1232:     my $link;
1.572     banghart 1233:     
1.159     www      1234:     $topic=~s/\W/\_/g;
1.44      bowersj2 1235: 
1.572     banghart 1236:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1237:         if ($env{'browser.mobile'}) {
                   1238: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1239:         } else {
                   1240:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1241:         }
1.1037    www      1242:     } elsif ($stayOnPage eq 'popup') {
                   1243:         $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 1244:     } else {
1.48      bowersj2 1245: 	$link = "/adm/help/${filename}.hlp";
                   1246:     }
                   1247: 
                   1248:     # Add the text
1.755     neumanie 1249:     if ($text ne "") {	
1.763     bisitz   1250: 	$template.='<span class="LC_help_open_topic">'
                   1251:                   .'<a target="_top" href="'.$link.'">'
                   1252:                   .$text.'</a>';
1.48      bowersj2 1253:     }
                   1254: 
1.763     bisitz   1255:     # (Always) Add the graphic
1.179     matthew  1256:     my $title = &mt('Online Help');
1.667     raeburn  1257:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1258:     if ($imgid ne '') {
                   1259:         $imgid = ' id="'.$imgid.'"';
                   1260:     }
1.763     bisitz   1261:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1262:               .'<img src="'.$helpicon.'" border="0"'
                   1263:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1264:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1265:               .' /></a>';
                   1266:     if ($text ne "") {	
                   1267:         $template.='</span>';
                   1268:     }
1.44      bowersj2 1269:     return $template;
                   1270: 
1.106     bowersj2 1271: }
                   1272: 
                   1273: # This is a quicky function for Latex cheatsheet editing, since it 
                   1274: # appears in at least four places
                   1275: sub helpLatexCheatsheet {
1.1037    www      1276:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1277:     my $out;
1.106     bowersj2 1278:     my $addOther = '';
1.732     raeburn  1279:     if ($topic) {
1.1037    www      1280: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1281:     }
                   1282:     $out = '<span>' # Start cheatsheet
                   1283: 	  .$addOther
                   1284:           .'<span>'
1.1037    www      1285: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1286: 	  .'</span> <span>'
1.1037    www      1287: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1288: 	  .'</span>';
1.732     raeburn  1289:     unless ($not_author) {
1.763     bisitz   1290:         $out .= ' <span>'
1.1037    www      1291: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1292: 	       .'</span>';
1.732     raeburn  1293:     }
1.763     bisitz   1294:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1295:     return $out;
1.172     www      1296: }
                   1297: 
1.430     albertel 1298: sub general_help {
                   1299:     my $helptopic='Student_Intro';
                   1300:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1301: 	$helptopic='Authoring_Intro';
1.907     raeburn  1302:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1303: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1304:     } elsif ($env{'request.role'}=~/^dc/) {
                   1305:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1306:     }
                   1307:     return $helptopic;
                   1308: }
                   1309: 
                   1310: sub update_help_link {
                   1311:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1312:     my $origurl = $ENV{'REQUEST_URI'};
                   1313:     $origurl=~s|^/~|/priv/|;
                   1314:     my $timestamp = time;
                   1315:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1316:         $$datum = &escape($$datum);
                   1317:     }
                   1318: 
                   1319:     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";
                   1320:     my $output .= <<"ENDOUTPUT";
                   1321: <script type="text/javascript">
1.824     bisitz   1322: // <![CDATA[
1.430     albertel 1323: banner_link = '$banner_link';
1.824     bisitz   1324: // ]]>
1.430     albertel 1325: </script>
                   1326: ENDOUTPUT
                   1327:     return $output;
                   1328: }
                   1329: 
                   1330: # now just updates the help link and generates a blue icon
1.193     raeburn  1331: sub help_open_menu {
1.430     albertel 1332:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1333: 	= @_;    
1.949     droeschl 1334:     $stayOnPage = 1;
1.430     albertel 1335:     my $output;
                   1336:     if ($component_help) {
                   1337: 	if (!$text) {
                   1338: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1339: 				       $width,$height);
                   1340: 	} else {
                   1341: 	    my $help_text;
                   1342: 	    $help_text=&unescape($topic);
                   1343: 	    $output='<table><tr><td>'.
                   1344: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1345: 				 $width,$height).'</td></tr></table>';
                   1346: 	}
                   1347:     }
                   1348:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1349:     return $output.$banner_link;
                   1350: }
                   1351: 
                   1352: sub top_nav_help {
                   1353:     my ($text) = @_;
1.436     albertel 1354:     $text = &mt($text);
1.1075.2.60  raeburn  1355:     my $stay_on_page;
                   1356:     unless ($env{'environment.remote'} eq 'on') {
                   1357:         $stay_on_page = 1;
                   1358:     }
1.1075.2.61  raeburn  1359:     my ($link,$banner_link);
                   1360:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1361:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1362: 	                         : "javascript:helpMenu('open')";
                   1363:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1364:     }
1.201     raeburn  1365:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1366:     if ($link) {
                   1367:         return <<"END";
1.436     albertel 1368: $banner_link
1.1075.2.56  raeburn  1369: <a href="$link" title="$title">$text</a>
1.436     albertel 1370: END
1.1075.2.61  raeburn  1371:     } else {
                   1372:         return '&nbsp;'.$text.'&nbsp;';
                   1373:     }
1.436     albertel 1374: }
                   1375: 
                   1376: sub help_menu_js {
1.1075.2.52  raeburn  1377:     my ($httphost) = @_;
1.949     droeschl 1378:     my $stayOnPage = 1;
1.436     albertel 1379:     my $width = 620;
                   1380:     my $height = 600;
1.430     albertel 1381:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1382:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1383:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1384:     my $start_page =
                   1385:         &Apache::loncommon::start_page('Help Menu', undef,
                   1386: 				       {'frameset'    => 1,
                   1387: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1388:                                         'use_absolute' => $httphost, 
1.331     albertel 1389: 					'add_entries' => {
                   1390: 					    'border' => '0',
1.579     raeburn  1391: 					    'rows'   => "110,*",},});
1.331     albertel 1392:     my $end_page =
                   1393:         &Apache::loncommon::end_page({'frameset' => 1,
                   1394: 				      'js_ready' => 1,});
                   1395: 
1.436     albertel 1396:     my $template .= <<"ENDTEMPLATE";
                   1397: <script type="text/javascript">
1.877     bisitz   1398: // <![CDATA[
1.253     albertel 1399: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1400: var banner_link = '';
1.243     raeburn  1401: function helpMenu(target) {
                   1402:     var caller = this;
                   1403:     if (target == 'open') {
                   1404:         var newWindow = null;
                   1405:         try {
1.262     albertel 1406:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1407:         }
                   1408:         catch(error) {
                   1409:             writeHelp(caller);
                   1410:             return;
                   1411:         }
                   1412:         if (newWindow) {
                   1413:             caller = newWindow;
                   1414:         }
1.193     raeburn  1415:     }
1.243     raeburn  1416:     writeHelp(caller);
                   1417:     return;
                   1418: }
                   1419: function writeHelp(caller) {
1.1075.2.61  raeburn  1420:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1421:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1422:     caller.document.close();
                   1423:     caller.focus();
1.193     raeburn  1424: }
1.877     bisitz   1425: // END LON-CAPA Internal -->
1.253     albertel 1426: // ]]>
1.436     albertel 1427: </script>
1.193     raeburn  1428: ENDTEMPLATE
                   1429:     return $template;
                   1430: }
                   1431: 
1.172     www      1432: sub help_open_bug {
                   1433:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1434:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1435:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1436:     $text = "" if (not defined $text);
                   1437: 	$stayOnPage=1;
1.184     albertel 1438:     $width = 600 if (not defined $width);
                   1439:     $height = 600 if (not defined $height);
1.172     www      1440: 
                   1441:     $topic=~s/\W+/\+/g;
                   1442:     my $link='';
                   1443:     my $template='';
1.379     albertel 1444:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1445: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1446:     if (!$stayOnPage)
                   1447:     {
                   1448: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1449:     }
                   1450:     else
                   1451:     {
                   1452: 	$link = $url;
                   1453:     }
                   1454:     # Add the text
                   1455:     if ($text ne "")
                   1456:     {
                   1457: 	$template .= 
                   1458:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1459:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1460:     }
                   1461: 
                   1462:     # Add the graphic
1.179     matthew  1463:     my $title = &mt('Report a Bug');
1.215     albertel 1464:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1465:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1466:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1467: ENDTEMPLATE
                   1468:     if ($text ne '') { $template.='</td></tr></table>' };
                   1469:     return $template;
                   1470: 
                   1471: }
                   1472: 
                   1473: sub help_open_faq {
                   1474:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1475:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1476:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1477:     $text = "" if (not defined $text);
                   1478: 	$stayOnPage=1;
                   1479:     $width = 350 if (not defined $width);
                   1480:     $height = 400 if (not defined $height);
                   1481: 
                   1482:     $topic=~s/\W+/\+/g;
                   1483:     my $link='';
                   1484:     my $template='';
                   1485:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1486:     if (!$stayOnPage)
                   1487:     {
                   1488: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1489:     }
                   1490:     else
                   1491:     {
                   1492: 	$link = $url;
                   1493:     }
                   1494: 
                   1495:     # Add the text
                   1496:     if ($text ne "")
                   1497:     {
                   1498: 	$template .= 
1.173     www      1499:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1500:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1501:     }
                   1502: 
                   1503:     # Add the graphic
1.179     matthew  1504:     my $title = &mt('View the FAQ');
1.215     albertel 1505:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1506:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1507:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1508: ENDTEMPLATE
                   1509:     if ($text ne '') { $template.='</td></tr></table>' };
                   1510:     return $template;
                   1511: 
1.44      bowersj2 1512: }
1.37      matthew  1513: 
1.180     matthew  1514: ###############################################################
                   1515: ###############################################################
                   1516: 
1.45      matthew  1517: =pod
                   1518: 
1.648     raeburn  1519: =item * &change_content_javascript():
1.256     matthew  1520: 
                   1521: This and the next function allow you to create small sections of an
                   1522: otherwise static HTML page that you can update on the fly with
                   1523: Javascript, even in Netscape 4.
                   1524: 
                   1525: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1526: must be written to the HTML page once. It will prove the Javascript
                   1527: function "change(name, content)". Calling the change function with the
                   1528: name of the section 
                   1529: you want to update, matching the name passed to C<changable_area>, and
                   1530: the new content you want to put in there, will put the content into
                   1531: that area.
                   1532: 
                   1533: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1534: to contain room for the original contents. You need to "make space"
                   1535: for whatever changes you wish to make, and be B<sure> to check your
                   1536: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1537: it's adequate for updating a one-line status display, but little more.
                   1538: This script will set the space to 100% width, so you only need to
                   1539: worry about height in Netscape 4.
                   1540: 
                   1541: Modern browsers are much less limiting, and if you can commit to the
                   1542: user not using Netscape 4, this feature may be used freely with
                   1543: pretty much any HTML.
                   1544: 
                   1545: =cut
                   1546: 
                   1547: sub change_content_javascript {
                   1548:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1549:     if ($env{'browser.type'} eq 'netscape' &&
                   1550: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1551: 	return (<<NETSCAPE4);
                   1552: 	function change(name, content) {
                   1553: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1554: 	    doc.open();
                   1555: 	    doc.write(content);
                   1556: 	    doc.close();
                   1557: 	}
                   1558: NETSCAPE4
                   1559:     } else {
                   1560: 	# Otherwise, we need to use semi-standards-compliant code
                   1561: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1562: 	# is really scary, and every useful browser supports it
                   1563: 	return (<<DOMBASED);
                   1564: 	function change(name, content) {
                   1565: 	    element = document.getElementById(name);
                   1566: 	    element.innerHTML = content;
                   1567: 	}
                   1568: DOMBASED
                   1569:     }
                   1570: }
                   1571: 
                   1572: =pod
                   1573: 
1.648     raeburn  1574: =item * &changable_area($name,$origContent):
1.256     matthew  1575: 
                   1576: This provides a "changable area" that can be modified on the fly via
                   1577: the Javascript code provided in C<change_content_javascript>. $name is
                   1578: the name you will use to reference the area later; do not repeat the
                   1579: same name on a given HTML page more then once. $origContent is what
                   1580: the area will originally contain, which can be left blank.
                   1581: 
                   1582: =cut
                   1583: 
                   1584: sub changable_area {
                   1585:     my ($name, $origContent) = @_;
                   1586: 
1.258     albertel 1587:     if ($env{'browser.type'} eq 'netscape' &&
                   1588: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1589: 	# If this is netscape 4, we need to use the Layer tag
                   1590: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1591:     } else {
                   1592: 	return "<span id='$name'>$origContent</span>";
                   1593:     }
                   1594: }
                   1595: 
                   1596: =pod
                   1597: 
1.648     raeburn  1598: =item * &viewport_geometry_js 
1.590     raeburn  1599: 
                   1600: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1601: 
                   1602: =cut
                   1603: 
                   1604: 
                   1605: sub viewport_geometry_js { 
                   1606:     return <<"GEOMETRY";
                   1607: var Geometry = {};
                   1608: function init_geometry() {
                   1609:     if (Geometry.init) { return };
                   1610:     Geometry.init=1;
                   1611:     if (window.innerHeight) {
                   1612:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1613:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1614:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1615:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1616:     }
                   1617:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1618:         Geometry.getViewportHeight =
                   1619:             function() { return document.documentElement.clientHeight; };
                   1620:         Geometry.getViewportWidth =
                   1621:             function() { return document.documentElement.clientWidth; };
                   1622: 
                   1623:         Geometry.getHorizontalScroll =
                   1624:             function() { return document.documentElement.scrollLeft; };
                   1625:         Geometry.getVerticalScroll =
                   1626:             function() { return document.documentElement.scrollTop; };
                   1627:     }
                   1628:     else if (document.body.clientHeight) {
                   1629:         Geometry.getViewportHeight =
                   1630:             function() { return document.body.clientHeight; };
                   1631:         Geometry.getViewportWidth =
                   1632:             function() { return document.body.clientWidth; };
                   1633:         Geometry.getHorizontalScroll =
                   1634:             function() { return document.body.scrollLeft; };
                   1635:         Geometry.getVerticalScroll =
                   1636:             function() { return document.body.scrollTop; };
                   1637:     }
                   1638: }
                   1639: 
                   1640: GEOMETRY
                   1641: }
                   1642: 
                   1643: =pod
                   1644: 
1.648     raeburn  1645: =item * &viewport_size_js()
1.590     raeburn  1646: 
                   1647: 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. 
                   1648: 
                   1649: =cut
                   1650: 
                   1651: sub viewport_size_js {
                   1652:     my $geometry = &viewport_geometry_js();
                   1653:     return <<"DIMS";
                   1654: 
                   1655: $geometry
                   1656: 
                   1657: function getViewportDims(width,height) {
                   1658:     init_geometry();
                   1659:     width.value = Geometry.getViewportWidth();
                   1660:     height.value = Geometry.getViewportHeight();
                   1661:     return;
                   1662: }
                   1663: 
                   1664: DIMS
                   1665: }
                   1666: 
                   1667: =pod
                   1668: 
1.648     raeburn  1669: =item * &resize_textarea_js()
1.565     albertel 1670: 
                   1671: emits the needed javascript to resize a textarea to be as big as possible
                   1672: 
                   1673: creates a function resize_textrea that takes two IDs first should be
                   1674: the id of the element to resize, second should be the id of a div that
                   1675: surrounds everything that comes after the textarea, this routine needs
                   1676: to be attached to the <body> for the onload and onresize events.
                   1677: 
1.648     raeburn  1678: =back
1.565     albertel 1679: 
                   1680: =cut
                   1681: 
                   1682: sub resize_textarea_js {
1.590     raeburn  1683:     my $geometry = &viewport_geometry_js();
1.565     albertel 1684:     return <<"RESIZE";
                   1685:     <script type="text/javascript">
1.824     bisitz   1686: // <![CDATA[
1.590     raeburn  1687: $geometry
1.565     albertel 1688: 
1.588     albertel 1689: function getX(element) {
                   1690:     var x = 0;
                   1691:     while (element) {
                   1692: 	x += element.offsetLeft;
                   1693: 	element = element.offsetParent;
                   1694:     }
                   1695:     return x;
                   1696: }
                   1697: function getY(element) {
                   1698:     var y = 0;
                   1699:     while (element) {
                   1700: 	y += element.offsetTop;
                   1701: 	element = element.offsetParent;
                   1702:     }
                   1703:     return y;
                   1704: }
                   1705: 
                   1706: 
1.565     albertel 1707: function resize_textarea(textarea_id,bottom_id) {
                   1708:     init_geometry();
                   1709:     var textarea        = document.getElementById(textarea_id);
                   1710:     //alert(textarea);
                   1711: 
1.588     albertel 1712:     var textarea_top    = getY(textarea);
1.565     albertel 1713:     var textarea_height = textarea.offsetHeight;
                   1714:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1715:     var bottom_top      = getY(bottom);
1.565     albertel 1716:     var bottom_height   = bottom.offsetHeight;
                   1717:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1718:     var fudge           = 23;
1.565     albertel 1719:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1720:     if (new_height < 300) {
                   1721: 	new_height = 300;
                   1722:     }
                   1723:     textarea.style.height=new_height+'px';
                   1724: }
1.824     bisitz   1725: // ]]>
1.565     albertel 1726: </script>
                   1727: RESIZE
                   1728: 
                   1729: }
                   1730: 
                   1731: =pod
                   1732: 
1.256     matthew  1733: =head1 Excel and CSV file utility routines
                   1734: 
                   1735: =cut
                   1736: 
                   1737: ###############################################################
                   1738: ###############################################################
                   1739: 
                   1740: =pod
                   1741: 
1.1075.2.56  raeburn  1742: =over 4
                   1743: 
1.648     raeburn  1744: =item * &csv_translate($text) 
1.37      matthew  1745: 
1.185     www      1746: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1747: format.
                   1748: 
                   1749: =cut
                   1750: 
1.180     matthew  1751: ###############################################################
                   1752: ###############################################################
1.37      matthew  1753: sub csv_translate {
                   1754:     my $text = shift;
                   1755:     $text =~ s/\"/\"\"/g;
1.209     albertel 1756:     $text =~ s/\n/ /g;
1.37      matthew  1757:     return $text;
                   1758: }
1.180     matthew  1759: 
                   1760: ###############################################################
                   1761: ###############################################################
                   1762: 
                   1763: =pod
                   1764: 
1.648     raeburn  1765: =item * &define_excel_formats()
1.180     matthew  1766: 
                   1767: Define some commonly used Excel cell formats.
                   1768: 
                   1769: Currently supported formats:
                   1770: 
                   1771: =over 4
                   1772: 
                   1773: =item header
                   1774: 
                   1775: =item bold
                   1776: 
                   1777: =item h1
                   1778: 
                   1779: =item h2
                   1780: 
                   1781: =item h3
                   1782: 
1.256     matthew  1783: =item h4
                   1784: 
                   1785: =item i
                   1786: 
1.180     matthew  1787: =item date
                   1788: 
                   1789: =back
                   1790: 
                   1791: Inputs: $workbook
                   1792: 
                   1793: Returns: $format, a hash reference.
                   1794: 
1.1057    foxr     1795: 
1.180     matthew  1796: =cut
                   1797: 
                   1798: ###############################################################
                   1799: ###############################################################
                   1800: sub define_excel_formats {
                   1801:     my ($workbook) = @_;
                   1802:     my $format;
                   1803:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1804:                                                 bottom    => 1,
                   1805:                                                 align     => 'center');
                   1806:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1807:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1808:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1809:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1810:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1811:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1812:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1813:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1814:     return $format;
                   1815: }
                   1816: 
                   1817: ###############################################################
                   1818: ###############################################################
1.113     bowersj2 1819: 
                   1820: =pod
                   1821: 
1.648     raeburn  1822: =item * &create_workbook()
1.255     matthew  1823: 
                   1824: Create an Excel worksheet.  If it fails, output message on the
                   1825: request object and return undefs.
                   1826: 
                   1827: Inputs: Apache request object
                   1828: 
                   1829: Returns (undef) on failure, 
                   1830:     Excel worksheet object, scalar with filename, and formats 
                   1831:     from &Apache::loncommon::define_excel_formats on success
                   1832: 
                   1833: =cut
                   1834: 
                   1835: ###############################################################
                   1836: ###############################################################
                   1837: sub create_workbook {
                   1838:     my ($r) = @_;
                   1839:         #
                   1840:     # Create the excel spreadsheet
                   1841:     my $filename = '/prtspool/'.
1.258     albertel 1842:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1843:         time.'_'.rand(1000000000).'.xls';
                   1844:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1845:     if (! defined($workbook)) {
                   1846:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1847:         $r->print(
                   1848:             '<p class="LC_error">'
                   1849:            .&mt('Problems occurred in creating the new Excel file.')
                   1850:            .' '.&mt('This error has been logged.')
                   1851:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1852:            .'</p>'
                   1853:         );
1.255     matthew  1854:         return (undef);
                   1855:     }
                   1856:     #
1.1014    foxr     1857:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1858:     #
                   1859:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1860:     return ($workbook,$filename,$format);
                   1861: }
                   1862: 
                   1863: ###############################################################
                   1864: ###############################################################
                   1865: 
                   1866: =pod
                   1867: 
1.648     raeburn  1868: =item * &create_text_file()
1.113     bowersj2 1869: 
1.542     raeburn  1870: Create a file to write to and eventually make available to the user.
1.256     matthew  1871: If file creation fails, outputs an error message on the request object and 
                   1872: return undefs.
1.113     bowersj2 1873: 
1.256     matthew  1874: Inputs: Apache request object, and file suffix
1.113     bowersj2 1875: 
1.256     matthew  1876: Returns (undef) on failure, 
                   1877:     Filehandle and filename on success.
1.113     bowersj2 1878: 
                   1879: =cut
                   1880: 
1.256     matthew  1881: ###############################################################
                   1882: ###############################################################
                   1883: sub create_text_file {
                   1884:     my ($r,$suffix) = @_;
                   1885:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1886:     my $fh;
                   1887:     my $filename = '/prtspool/'.
1.258     albertel 1888:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1889:         time.'_'.rand(1000000000).'.'.$suffix;
                   1890:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1891:     if (! defined($fh)) {
                   1892:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1893:         $r->print(
                   1894:             '<p class="LC_error">'
                   1895:            .&mt('Problems occurred in creating the output file.')
                   1896:            .' '.&mt('This error has been logged.')
                   1897:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1898:            .'</p>'
                   1899:         );
1.113     bowersj2 1900:     }
1.256     matthew  1901:     return ($fh,$filename)
1.113     bowersj2 1902: }
                   1903: 
                   1904: 
1.256     matthew  1905: =pod 
1.113     bowersj2 1906: 
                   1907: =back
                   1908: 
                   1909: =cut
1.37      matthew  1910: 
                   1911: ###############################################################
1.33      matthew  1912: ##        Home server <option> list generating code          ##
                   1913: ###############################################################
1.35      matthew  1914: 
1.169     www      1915: # ------------------------------------------
                   1916: 
                   1917: sub domain_select {
                   1918:     my ($name,$value,$multiple)=@_;
                   1919:     my %domains=map { 
1.514     albertel 1920: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1921:     } &Apache::lonnet::all_domains();
1.169     www      1922:     if ($multiple) {
                   1923: 	$domains{''}=&mt('Any domain');
1.550     albertel 1924: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1925: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1926:     } else {
1.550     albertel 1927: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1928: 	return &select_form($name,$value,\%domains);
1.169     www      1929:     }
                   1930: }
                   1931: 
1.282     albertel 1932: #-------------------------------------------
                   1933: 
                   1934: =pod
                   1935: 
1.519     raeburn  1936: =head1 Routines for form select boxes
                   1937: 
                   1938: =over 4
                   1939: 
1.648     raeburn  1940: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1941: 
                   1942: Returns a string containing a <select> element int multiple mode
                   1943: 
                   1944: 
                   1945: Args:
                   1946:   $name - name of the <select> element
1.506     raeburn  1947:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1948:   $size - number of rows long the select element is
1.283     albertel 1949:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1950:           (shown text should already have been &mt())
1.506     raeburn  1951:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1952: 
1.282     albertel 1953: =cut
                   1954: 
                   1955: #-------------------------------------------
1.169     www      1956: sub multiple_select_form {
1.284     albertel 1957:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1958:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1959:     my $output='';
1.191     matthew  1960:     if (! defined($size)) {
                   1961:         $size = 4;
1.283     albertel 1962:         if (scalar(keys(%$hash))<4) {
                   1963:             $size = scalar(keys(%$hash));
1.191     matthew  1964:         }
                   1965:     }
1.734     bisitz   1966:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1967:     my @order;
1.506     raeburn  1968:     if (ref($order) eq 'ARRAY')  {
                   1969:         @order = @{$order};
                   1970:     } else {
                   1971:         @order = sort(keys(%$hash));
1.501     banghart 1972:     }
                   1973:     if (exists($$hash{'select_form_order'})) {
                   1974:         @order = @{$$hash{'select_form_order'}};
                   1975:     }
                   1976:         
1.284     albertel 1977:     foreach my $key (@order) {
1.356     albertel 1978:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1979:         $output.='selected="selected" ' if ($selected{$key});
                   1980:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1981:     }
                   1982:     $output.="</select>\n";
                   1983:     return $output;
                   1984: }
                   1985: 
1.88      www      1986: #-------------------------------------------
                   1987: 
                   1988: =pod
                   1989: 
1.970     raeburn  1990: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1991: 
                   1992: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1993: allow a user to select options from a ref to a hash containing:
                   1994: option_name => displayed text. An optional $onchange can include
                   1995: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   1996: 
1.88      www      1997: See lonrights.pm for an example invocation and use.
                   1998: 
                   1999: =cut
                   2000: 
                   2001: #-------------------------------------------
                   2002: sub select_form {
1.970     raeburn  2003:     my ($def,$name,$hashref,$onchange) = @_;
                   2004:     return unless (ref($hashref) eq 'HASH');
                   2005:     if ($onchange) {
                   2006:         $onchange = ' onchange="'.$onchange.'"';
                   2007:     }
                   2008:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2009:     my @keys;
1.970     raeburn  2010:     if (exists($hashref->{'select_form_order'})) {
                   2011: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2012:     } else {
1.970     raeburn  2013: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2014:     }
1.356     albertel 2015:     foreach my $key (@keys) {
                   2016:         $selectform.=
                   2017: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2018:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2019:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2020:     }
                   2021:     $selectform.="</select>";
                   2022:     return $selectform;
                   2023: }
                   2024: 
1.475     www      2025: # For display filters
                   2026: 
                   2027: sub display_filter {
1.1074    raeburn  2028:     my ($context) = @_;
1.475     www      2029:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2030:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2031:     my $phraseinput = 'hidden';
                   2032:     my $includeinput = 'hidden';
                   2033:     my ($checked,$includetypestext);
                   2034:     if ($env{'form.displayfilter'} eq 'containing') {
                   2035:         $phraseinput = 'text'; 
                   2036:         if ($context eq 'parmslog') {
                   2037:             $includeinput = 'checkbox';
                   2038:             if ($env{'form.includetypes'}) {
                   2039:                 $checked = ' checked="checked"';
                   2040:             }
                   2041:             $includetypestext = &mt('Include parameter types');
                   2042:         }
                   2043:     } else {
                   2044:         $includetypestext = '&nbsp;';
                   2045:     }
                   2046:     my ($additional,$secondid,$thirdid);
                   2047:     if ($context eq 'parmslog') {
                   2048:         $additional = 
                   2049:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2050:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2051:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2052:             '</label>';
                   2053:         $secondid = 'includetypes';
                   2054:         $thirdid = 'includetypestext';
                   2055:     }
                   2056:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2057:                                                     '$secondid','$thirdid')";
                   2058:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2059: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2060: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2061: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2062:            &mt('Filter: [_1]',
1.477     www      2063: 	   &select_form($env{'form.displayfilter'},
                   2064: 			'displayfilter',
1.970     raeburn  2065: 			{'currentfolder' => 'Current folder/page',
1.477     www      2066: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2067: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2068: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2069:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2070:                          '" />'.$additional;
                   2071: }
                   2072: 
                   2073: sub display_filter_js {
                   2074:     my $includetext = &mt('Include parameter types');
                   2075:     return <<"ENDJS";
                   2076:   
                   2077: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2078:     var firstType = 'hidden';
                   2079:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2080:         firstType = 'text';
                   2081:     }
                   2082:     firstObject = document.getElementById(firstid);
                   2083:     if (typeof(firstObject) == 'object') {
                   2084:         if (firstObject.type != firstType) {
                   2085:             changeInputType(firstObject,firstType);
                   2086:         }
                   2087:     }
                   2088:     if (context == 'parmslog') {
                   2089:         var secondType = 'hidden';
                   2090:         if (firstType == 'text') {
                   2091:             secondType = 'checkbox';
                   2092:         }
                   2093:         secondObject = document.getElementById(secondid);  
                   2094:         if (typeof(secondObject) == 'object') {
                   2095:             if (secondObject.type != secondType) {
                   2096:                 changeInputType(secondObject,secondType);
                   2097:             }
                   2098:         }
                   2099:         var textItem = document.getElementById(thirdid);
                   2100:         var currtext = textItem.innerHTML;
                   2101:         var newtext;
                   2102:         if (firstType == 'text') {
                   2103:             newtext = '$includetext';
                   2104:         } else {
                   2105:             newtext = '&nbsp;';
                   2106:         }
                   2107:         if (currtext != newtext) {
                   2108:             textItem.innerHTML = newtext;
                   2109:         }
                   2110:     }
                   2111:     return;
                   2112: }
                   2113: 
                   2114: function changeInputType(oldObject,newType) {
                   2115:     var newObject = document.createElement('input');
                   2116:     newObject.type = newType;
                   2117:     if (oldObject.size) {
                   2118:         newObject.size = oldObject.size;
                   2119:     }
                   2120:     if (oldObject.value) {
                   2121:         newObject.value = oldObject.value;
                   2122:     }
                   2123:     if (oldObject.name) {
                   2124:         newObject.name = oldObject.name;
                   2125:     }
                   2126:     if (oldObject.id) {
                   2127:         newObject.id = oldObject.id;
                   2128:     }
                   2129:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2130:     return;
                   2131: }
                   2132: 
                   2133: ENDJS
1.475     www      2134: }
                   2135: 
1.167     www      2136: sub gradeleveldescription {
                   2137:     my $gradelevel=shift;
                   2138:     my %gradelevels=(0 => 'Not specified',
                   2139: 		     1 => 'Grade 1',
                   2140: 		     2 => 'Grade 2',
                   2141: 		     3 => 'Grade 3',
                   2142: 		     4 => 'Grade 4',
                   2143: 		     5 => 'Grade 5',
                   2144: 		     6 => 'Grade 6',
                   2145: 		     7 => 'Grade 7',
                   2146: 		     8 => 'Grade 8',
                   2147: 		     9 => 'Grade 9',
                   2148: 		     10 => 'Grade 10',
                   2149: 		     11 => 'Grade 11',
                   2150: 		     12 => 'Grade 12',
                   2151: 		     13 => 'Grade 13',
                   2152: 		     14 => '100 Level',
                   2153: 		     15 => '200 Level',
                   2154: 		     16 => '300 Level',
                   2155: 		     17 => '400 Level',
                   2156: 		     18 => 'Graduate Level');
                   2157:     return &mt($gradelevels{$gradelevel});
                   2158: }
                   2159: 
1.163     www      2160: sub select_level_form {
                   2161:     my ($deflevel,$name)=@_;
                   2162:     unless ($deflevel) { $deflevel=0; }
1.167     www      2163:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2164:     for (my $i=0; $i<=18; $i++) {
                   2165:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2166:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2167:                 ">".&gradeleveldescription($i)."</option>\n";
                   2168:     }
                   2169:     $selectform.="</select>";
                   2170:     return $selectform;
1.163     www      2171: }
1.167     www      2172: 
1.35      matthew  2173: #-------------------------------------------
                   2174: 
1.45      matthew  2175: =pod
                   2176: 
1.1075.2.42  raeburn  2177: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2178: 
                   2179: Returns a string containing a <select name='$name' size='1'> form to 
                   2180: allow a user to select the domain to preform an operation in.  
                   2181: See loncreateuser.pm for an example invocation and use.
                   2182: 
1.90      www      2183: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2184: selected");
                   2185: 
1.743     raeburn  2186: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2187: 
1.910     raeburn  2188: 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.
                   2189: 
1.1075.2.36  raeburn  2190: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2191: 
                   2192: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
1.563     raeburn  2193: 
1.35      matthew  2194: =cut
                   2195: 
                   2196: #-------------------------------------------
1.34      matthew  2197: sub select_dom_form {
1.1075.2.36  raeburn  2198:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2199:     if ($onchange) {
1.874     raeburn  2200:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2201:     }
1.1075.2.36  raeburn  2202:     my (@domains,%exclude);
1.910     raeburn  2203:     if (ref($incdoms) eq 'ARRAY') {
                   2204:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2205:     } else {
                   2206:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2207:     }
1.90      www      2208:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2209:     if (ref($excdoms) eq 'ARRAY') {
                   2210:         map { $exclude{$_} = 1; } @{$excdoms};
                   2211:     }
1.743     raeburn  2212:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2213:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2214:         next if ($exclude{$dom});
1.356     albertel 2215:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2216:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2217:         if ($showdomdesc) {
                   2218:             if ($dom ne '') {
                   2219:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2220:                 if ($domdesc ne '') {
                   2221:                     $selectdomain .= ' ('.$domdesc.')';
                   2222:                 }
                   2223:             } 
                   2224:         }
                   2225:         $selectdomain .= "</option>\n";
1.34      matthew  2226:     }
                   2227:     $selectdomain.="</select>";
                   2228:     return $selectdomain;
                   2229: }
                   2230: 
1.35      matthew  2231: #-------------------------------------------
                   2232: 
1.45      matthew  2233: =pod
                   2234: 
1.648     raeburn  2235: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2236: 
1.586     raeburn  2237: input: 4 arguments (two required, two optional) - 
                   2238:     $domain - domain of new user
                   2239:     $name - name of form element
                   2240:     $default - Value of 'default' causes a default item to be first 
                   2241:                             option, and selected by default. 
                   2242:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2243:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2244: output: returns 2 items: 
1.586     raeburn  2245: (a) form element which contains either:
                   2246:    (i) <select name="$name">
                   2247:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2248:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2249:        </select>
                   2250:        form item if there are multiple library servers in $domain, or
                   2251:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2252:        if there is only one library server in $domain.
                   2253: 
                   2254: (b) number of library servers found.
                   2255: 
                   2256: See loncreateuser.pm for example of use.
1.35      matthew  2257: 
                   2258: =cut
                   2259: 
                   2260: #-------------------------------------------
1.586     raeburn  2261: sub home_server_form_item {
                   2262:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2263:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2264:     my $result;
                   2265:     my $numlib = keys(%servers);
                   2266:     if ($numlib > 1) {
                   2267:         $result .= '<select name="'.$name.'" />'."\n";
                   2268:         if ($default) {
1.804     bisitz   2269:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2270:                        '</option>'."\n";
                   2271:         }
                   2272:         foreach my $hostid (sort(keys(%servers))) {
                   2273:             $result.= '<option value="'.$hostid.'">'.
                   2274: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2275:         }
                   2276:         $result .= '</select>'."\n";
                   2277:     } elsif ($numlib == 1) {
                   2278:         my $hostid;
                   2279:         foreach my $item (keys(%servers)) {
                   2280:             $hostid = $item;
                   2281:         }
                   2282:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2283:                    $hostid.'" />';
                   2284:                    if (!$hide) {
                   2285:                        $result .= $hostid.' '.$servers{$hostid};
                   2286:                    }
                   2287:                    $result .= "\n";
                   2288:     } elsif ($default) {
                   2289:         $result .= '<input type="hidden" name="'.$name.
                   2290:                    '" value="default" />';
                   2291:                    if (!$hide) {
                   2292:                        $result .= &mt('default');
                   2293:                    }
                   2294:                    $result .= "\n";
1.33      matthew  2295:     }
1.586     raeburn  2296:     return ($result,$numlib);
1.33      matthew  2297: }
1.112     bowersj2 2298: 
                   2299: =pod
                   2300: 
1.534     albertel 2301: =back 
                   2302: 
1.112     bowersj2 2303: =cut
1.87      matthew  2304: 
                   2305: ###############################################################
1.112     bowersj2 2306: ##                  Decoding User Agent                      ##
1.87      matthew  2307: ###############################################################
                   2308: 
                   2309: =pod
                   2310: 
1.112     bowersj2 2311: =head1 Decoding the User Agent
                   2312: 
                   2313: =over 4
                   2314: 
                   2315: =item * &decode_user_agent()
1.87      matthew  2316: 
                   2317: Inputs: $r
                   2318: 
                   2319: Outputs:
                   2320: 
                   2321: =over 4
                   2322: 
1.112     bowersj2 2323: =item * $httpbrowser
1.87      matthew  2324: 
1.112     bowersj2 2325: =item * $clientbrowser
1.87      matthew  2326: 
1.112     bowersj2 2327: =item * $clientversion
1.87      matthew  2328: 
1.112     bowersj2 2329: =item * $clientmathml
1.87      matthew  2330: 
1.112     bowersj2 2331: =item * $clientunicode
1.87      matthew  2332: 
1.112     bowersj2 2333: =item * $clientos
1.87      matthew  2334: 
1.1075.2.42  raeburn  2335: =item * $clientmobile
                   2336: 
                   2337: =item * $clientinfo
                   2338: 
1.87      matthew  2339: =back
                   2340: 
1.157     matthew  2341: =back 
                   2342: 
1.87      matthew  2343: =cut
                   2344: 
                   2345: ###############################################################
                   2346: ###############################################################
                   2347: sub decode_user_agent {
1.247     albertel 2348:     my ($r)=@_;
1.87      matthew  2349:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2350:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2351:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2352:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2353:     my $clientbrowser='unknown';
                   2354:     my $clientversion='0';
                   2355:     my $clientmathml='';
                   2356:     my $clientunicode='0';
1.1075.2.42  raeburn  2357:     my $clientmobile=0;
1.87      matthew  2358:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2359:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2360: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2361: 	    $clientbrowser=$bname;
                   2362:             $httpbrowser=~/$vreg/i;
                   2363: 	    $clientversion=$1;
                   2364:             $clientmathml=($clientversion>=$minv);
                   2365:             $clientunicode=($clientversion>=$univ);
                   2366: 	}
                   2367:     }
                   2368:     my $clientos='unknown';
1.1075.2.42  raeburn  2369:     my $clientinfo;
1.87      matthew  2370:     if (($httpbrowser=~/linux/i) ||
                   2371:         ($httpbrowser=~/unix/i) ||
                   2372:         ($httpbrowser=~/ux/i) ||
                   2373:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2374:     if (($httpbrowser=~/vax/i) ||
                   2375:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2376:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2377:     if (($httpbrowser=~/mac/i) ||
                   2378:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2379:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2380:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2381:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2382:         $clientmobile=lc($1);
                   2383:     }
                   2384:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2385:         $clientinfo = 'firefox-'.$1;
                   2386:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2387:         $clientinfo = 'chromeframe-'.$1;
                   2388:     }
1.87      matthew  2389:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.42  raeburn  2390:             $clientunicode,$clientos,$clientmobile,$clientinfo);
1.87      matthew  2391: }
                   2392: 
1.32      matthew  2393: ###############################################################
                   2394: ##    Authentication changing form generation subroutines    ##
                   2395: ###############################################################
                   2396: ##
                   2397: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2398: ## hash, and have reasonable default values.
                   2399: ##
                   2400: ##    formname = the name given in the <form> tag.
1.35      matthew  2401: #-------------------------------------------
                   2402: 
1.45      matthew  2403: =pod
                   2404: 
1.112     bowersj2 2405: =head1 Authentication Routines
                   2406: 
                   2407: =over 4
                   2408: 
1.648     raeburn  2409: =item * &authform_xxxxxx()
1.35      matthew  2410: 
                   2411: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2412: handle some of the conveniences required for authentication forms.  
                   2413: This is not an optimal method, but it works.  
                   2414: 
                   2415: =over 4
                   2416: 
1.112     bowersj2 2417: =item * authform_header
1.35      matthew  2418: 
1.112     bowersj2 2419: =item * authform_authorwarning
1.35      matthew  2420: 
1.112     bowersj2 2421: =item * authform_nochange
1.35      matthew  2422: 
1.112     bowersj2 2423: =item * authform_kerberos
1.35      matthew  2424: 
1.112     bowersj2 2425: =item * authform_internal
1.35      matthew  2426: 
1.112     bowersj2 2427: =item * authform_filesystem
1.35      matthew  2428: 
                   2429: =back
                   2430: 
1.648     raeburn  2431: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2432: 
1.35      matthew  2433: =cut
                   2434: 
                   2435: #-------------------------------------------
1.32      matthew  2436: sub authform_header{  
                   2437:     my %in = (
                   2438:         formname => 'cu',
1.80      albertel 2439:         kerb_def_dom => '',
1.32      matthew  2440:         @_,
                   2441:     );
                   2442:     $in{'formname'} = 'document.' . $in{'formname'};
                   2443:     my $result='';
1.80      albertel 2444: 
                   2445: #---------------------------------------------- Code for upper case translation
                   2446:     my $Javascript_toUpperCase;
                   2447:     unless ($in{kerb_def_dom}) {
                   2448:         $Javascript_toUpperCase =<<"END";
                   2449:         switch (choice) {
                   2450:            case 'krb': currentform.elements[choicearg].value =
                   2451:                currentform.elements[choicearg].value.toUpperCase();
                   2452:                break;
                   2453:            default:
                   2454:         }
                   2455: END
                   2456:     } else {
                   2457:         $Javascript_toUpperCase = "";
                   2458:     }
                   2459: 
1.165     raeburn  2460:     my $radioval = "'nochange'";
1.591     raeburn  2461:     if (defined($in{'curr_authtype'})) {
                   2462:         if ($in{'curr_authtype'} ne '') {
                   2463:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2464:         }
1.174     matthew  2465:     }
1.165     raeburn  2466:     my $argfield = 'null';
1.591     raeburn  2467:     if (defined($in{'mode'})) {
1.165     raeburn  2468:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2469:             if (defined($in{'curr_autharg'})) {
                   2470:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2471:                     $argfield = "'$in{'curr_autharg'}'";
                   2472:                 }
                   2473:             }
                   2474:         }
                   2475:     }
                   2476: 
1.32      matthew  2477:     $result.=<<"END";
                   2478: var current = new Object();
1.165     raeburn  2479: current.radiovalue = $radioval;
                   2480: current.argfield = $argfield;
1.32      matthew  2481: 
                   2482: function changed_radio(choice,currentform) {
                   2483:     var choicearg = choice + 'arg';
                   2484:     // If a radio button in changed, we need to change the argfield
                   2485:     if (current.radiovalue != choice) {
                   2486:         current.radiovalue = choice;
                   2487:         if (current.argfield != null) {
                   2488:             currentform.elements[current.argfield].value = '';
                   2489:         }
                   2490:         if (choice == 'nochange') {
                   2491:             current.argfield = null;
                   2492:         } else {
                   2493:             current.argfield = choicearg;
                   2494:             switch(choice) {
                   2495:                 case 'krb': 
                   2496:                     currentform.elements[current.argfield].value = 
                   2497:                         "$in{'kerb_def_dom'}";
                   2498:                 break;
                   2499:               default:
                   2500:                 break;
                   2501:             }
                   2502:         }
                   2503:     }
                   2504:     return;
                   2505: }
1.22      www      2506: 
1.32      matthew  2507: function changed_text(choice,currentform) {
                   2508:     var choicearg = choice + 'arg';
                   2509:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2510:         $Javascript_toUpperCase
1.32      matthew  2511:         // clear old field
                   2512:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2513:             currentform.elements[current.argfield].value = '';
                   2514:         }
                   2515:         current.argfield = choicearg;
                   2516:     }
                   2517:     set_auth_radio_buttons(choice,currentform);
                   2518:     return;
1.20      www      2519: }
1.32      matthew  2520: 
                   2521: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2522:     var numauthchoices = currentform.login.length;
                   2523:     if (typeof numauthchoices  == "undefined") {
                   2524:         return;
                   2525:     } 
1.32      matthew  2526:     var i=0;
1.986     raeburn  2527:     while (i < numauthchoices) {
1.32      matthew  2528:         if (currentform.login[i].value == newvalue) { break; }
                   2529:         i++;
                   2530:     }
1.986     raeburn  2531:     if (i == numauthchoices) {
1.32      matthew  2532:         return;
                   2533:     }
                   2534:     current.radiovalue = newvalue;
                   2535:     currentform.login[i].checked = true;
                   2536:     return;
                   2537: }
                   2538: END
                   2539:     return $result;
                   2540: }
                   2541: 
1.1075.2.20  raeburn  2542: sub authform_authorwarning {
1.32      matthew  2543:     my $result='';
1.144     matthew  2544:     $result='<i>'.
                   2545:         &mt('As a general rule, only authors or co-authors should be '.
                   2546:             'filesystem authenticated '.
                   2547:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2548:     return $result;
                   2549: }
                   2550: 
1.1075.2.20  raeburn  2551: sub authform_nochange {
1.32      matthew  2552:     my %in = (
                   2553:               formname => 'document.cu',
                   2554:               kerb_def_dom => 'MSU.EDU',
                   2555:               @_,
                   2556:           );
1.1075.2.20  raeburn  2557:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2558:     my $result;
1.1075.2.20  raeburn  2559:     if (!$authnum) {
                   2560:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2561:     } else {
                   2562:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2563:                   '<input type="radio" name="login" value="nochange" '.
                   2564:                   'checked="checked" onclick="'.
1.281     albertel 2565:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2566: 	    '</label>';
1.586     raeburn  2567:     }
1.32      matthew  2568:     return $result;
                   2569: }
                   2570: 
1.591     raeburn  2571: sub authform_kerberos {
1.32      matthew  2572:     my %in = (
                   2573:               formname => 'document.cu',
                   2574:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2575:               kerb_def_auth => 'krb4',
1.32      matthew  2576:               @_,
                   2577:               );
1.586     raeburn  2578:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2579:         $autharg,$jscall);
1.1075.2.20  raeburn  2580:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2581:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2582:        $check5 = ' checked="checked"';
1.80      albertel 2583:     } else {
1.772     bisitz   2584:        $check4 = ' checked="checked"';
1.80      albertel 2585:     }
1.165     raeburn  2586:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2587:     if (defined($in{'curr_authtype'})) {
                   2588:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2589:             $krbcheck = ' checked="checked"';
1.623     raeburn  2590:             if (defined($in{'mode'})) {
                   2591:                 if ($in{'mode'} eq 'modifyuser') {
                   2592:                     $krbcheck = '';
                   2593:                 }
                   2594:             }
1.591     raeburn  2595:             if (defined($in{'curr_kerb_ver'})) {
                   2596:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2597:                     $check5 = ' checked="checked"';
1.591     raeburn  2598:                     $check4 = '';
                   2599:                 } else {
1.772     bisitz   2600:                     $check4 = ' checked="checked"';
1.591     raeburn  2601:                     $check5 = '';
                   2602:                 }
1.586     raeburn  2603:             }
1.591     raeburn  2604:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2605:                 $krbarg = $in{'curr_autharg'};
                   2606:             }
1.586     raeburn  2607:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2608:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2609:                     $result = 
                   2610:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2611:         $in{'curr_autharg'},$krbver);
                   2612:                 } else {
                   2613:                     $result =
                   2614:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2615:                 }
                   2616:                 return $result; 
                   2617:             }
                   2618:         }
                   2619:     } else {
                   2620:         if ($authnum == 1) {
1.784     bisitz   2621:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2622:         }
                   2623:     }
1.586     raeburn  2624:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2625:         return;
1.587     raeburn  2626:     } elsif ($authtype eq '') {
1.591     raeburn  2627:         if (defined($in{'mode'})) {
1.587     raeburn  2628:             if ($in{'mode'} eq 'modifycourse') {
                   2629:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2630:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2631:                 }
                   2632:             }
                   2633:         }
1.586     raeburn  2634:     }
                   2635:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2636:     if ($authtype eq '') {
                   2637:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2638:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2639:                     $krbcheck.' />';
                   2640:     }
                   2641:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2642:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2643:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2644:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2645:          $in{'curr_authtype'} eq 'krb4')) {
                   2646:         $result .= &mt
1.144     matthew  2647:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2648:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2649:          '<label>'.$authtype,
1.281     albertel 2650:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2651:              'value="'.$krbarg.'" '.
1.144     matthew  2652:              'onchange="'.$jscall.'" />',
1.281     albertel 2653:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2654:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2655: 	 '</label>');
1.586     raeburn  2656:     } elsif ($can_assign{'krb4'}) {
                   2657:         $result .= &mt
                   2658:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2659:          '[_3] Version 4 [_4]',
                   2660:          '<label>'.$authtype,
                   2661:          '</label><input type="text" size="10" name="krbarg" '.
                   2662:              'value="'.$krbarg.'" '.
                   2663:              'onchange="'.$jscall.'" />',
                   2664:          '<label><input type="hidden" name="krbver" value="4" />',
                   2665:          '</label>');
                   2666:     } elsif ($can_assign{'krb5'}) {
                   2667:         $result .= &mt
                   2668:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2669:          '[_3] Version 5 [_4]',
                   2670:          '<label>'.$authtype,
                   2671:          '</label><input type="text" size="10" name="krbarg" '.
                   2672:              'value="'.$krbarg.'" '.
                   2673:              'onchange="'.$jscall.'" />',
                   2674:          '<label><input type="hidden" name="krbver" value="5" />',
                   2675:          '</label>');
                   2676:     }
1.32      matthew  2677:     return $result;
                   2678: }
                   2679: 
1.1075.2.20  raeburn  2680: sub authform_internal {
1.586     raeburn  2681:     my %in = (
1.32      matthew  2682:                 formname => 'document.cu',
                   2683:                 kerb_def_dom => 'MSU.EDU',
                   2684:                 @_,
                   2685:                 );
1.586     raeburn  2686:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2687:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2688:     if (defined($in{'curr_authtype'})) {
                   2689:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2690:             if ($can_assign{'int'}) {
1.772     bisitz   2691:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2692:                 if (defined($in{'mode'})) {
                   2693:                     if ($in{'mode'} eq 'modifyuser') {
                   2694:                         $intcheck = '';
                   2695:                     }
                   2696:                 }
1.591     raeburn  2697:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2698:                     $intarg = $in{'curr_autharg'};
                   2699:                 }
                   2700:             } else {
                   2701:                 $result = &mt('Currently internally authenticated.');
                   2702:                 return $result;
1.165     raeburn  2703:             }
                   2704:         }
1.586     raeburn  2705:     } else {
                   2706:         if ($authnum == 1) {
1.784     bisitz   2707:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2708:         }
                   2709:     }
                   2710:     if (!$can_assign{'int'}) {
                   2711:         return;
1.587     raeburn  2712:     } elsif ($authtype eq '') {
1.591     raeburn  2713:         if (defined($in{'mode'})) {
1.587     raeburn  2714:             if ($in{'mode'} eq 'modifycourse') {
                   2715:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2716:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2717:                 }
                   2718:             }
                   2719:         }
1.165     raeburn  2720:     }
1.586     raeburn  2721:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2722:     if ($authtype eq '') {
                   2723:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2724:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2725:     }
1.605     bisitz   2726:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2727:                $intarg.'" onchange="'.$jscall.'" />';
                   2728:     $result = &mt
1.144     matthew  2729:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2730:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2731:     $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  2732:     return $result;
                   2733: }
                   2734: 
1.1075.2.20  raeburn  2735: sub authform_local {
1.32      matthew  2736:     my %in = (
                   2737:               formname => 'document.cu',
                   2738:               kerb_def_dom => 'MSU.EDU',
                   2739:               @_,
                   2740:               );
1.586     raeburn  2741:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2742:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2743:     if (defined($in{'curr_authtype'})) {
                   2744:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2745:             if ($can_assign{'loc'}) {
1.772     bisitz   2746:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2747:                 if (defined($in{'mode'})) {
                   2748:                     if ($in{'mode'} eq 'modifyuser') {
                   2749:                         $loccheck = '';
                   2750:                     }
                   2751:                 }
1.591     raeburn  2752:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2753:                     $locarg = $in{'curr_autharg'};
                   2754:                 }
                   2755:             } else {
                   2756:                 $result = &mt('Currently using local (institutional) authentication.');
                   2757:                 return $result;
1.165     raeburn  2758:             }
                   2759:         }
1.586     raeburn  2760:     } else {
                   2761:         if ($authnum == 1) {
1.784     bisitz   2762:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2763:         }
                   2764:     }
                   2765:     if (!$can_assign{'loc'}) {
                   2766:         return;
1.587     raeburn  2767:     } elsif ($authtype eq '') {
1.591     raeburn  2768:         if (defined($in{'mode'})) {
1.587     raeburn  2769:             if ($in{'mode'} eq 'modifycourse') {
                   2770:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2771:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2772:                 }
                   2773:             }
                   2774:         }
1.165     raeburn  2775:     }
1.586     raeburn  2776:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2777:     if ($authtype eq '') {
                   2778:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2779:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2780:                     $jscall.'" />';
                   2781:     }
                   2782:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2783:                $locarg.'" onchange="'.$jscall.'" />';
                   2784:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2785:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2786:     return $result;
                   2787: }
                   2788: 
1.1075.2.20  raeburn  2789: sub authform_filesystem {
1.32      matthew  2790:     my %in = (
                   2791:               formname => 'document.cu',
                   2792:               kerb_def_dom => 'MSU.EDU',
                   2793:               @_,
                   2794:               );
1.586     raeburn  2795:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2796:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2797:     if (defined($in{'curr_authtype'})) {
                   2798:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2799:             if ($can_assign{'fsys'}) {
1.772     bisitz   2800:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2801:                 if (defined($in{'mode'})) {
                   2802:                     if ($in{'mode'} eq 'modifyuser') {
                   2803:                         $fsyscheck = '';
                   2804:                     }
                   2805:                 }
1.586     raeburn  2806:             } else {
                   2807:                 $result = &mt('Currently Filesystem Authenticated.');
                   2808:                 return $result;
                   2809:             }           
                   2810:         }
                   2811:     } else {
                   2812:         if ($authnum == 1) {
1.784     bisitz   2813:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2814:         }
                   2815:     }
                   2816:     if (!$can_assign{'fsys'}) {
                   2817:         return;
1.587     raeburn  2818:     } elsif ($authtype eq '') {
1.591     raeburn  2819:         if (defined($in{'mode'})) {
1.587     raeburn  2820:             if ($in{'mode'} eq 'modifycourse') {
                   2821:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2822:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2823:                 }
                   2824:             }
                   2825:         }
1.586     raeburn  2826:     }
                   2827:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2828:     if ($authtype eq '') {
                   2829:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2830:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2831:                     $jscall.'" />';
                   2832:     }
                   2833:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2834:                ' onchange="'.$jscall.'" />';
                   2835:     $result = &mt
1.144     matthew  2836:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2837:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2838:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2839:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2840:                   'onchange="'.$jscall.'" />');
1.32      matthew  2841:     return $result;
                   2842: }
                   2843: 
1.586     raeburn  2844: sub get_assignable_auth {
                   2845:     my ($dom) = @_;
                   2846:     if ($dom eq '') {
                   2847:         $dom = $env{'request.role.domain'};
                   2848:     }
                   2849:     my %can_assign = (
                   2850:                           krb4 => 1,
                   2851:                           krb5 => 1,
                   2852:                           int  => 1,
                   2853:                           loc  => 1,
                   2854:                      );
                   2855:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2856:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2857:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2858:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2859:             my $context;
                   2860:             if ($env{'request.role'} =~ /^au/) {
                   2861:                 $context = 'author';
                   2862:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2863:                 $context = 'domain';
                   2864:             } elsif ($env{'request.course.id'}) {
                   2865:                 $context = 'course';
                   2866:             }
                   2867:             if ($context) {
                   2868:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2869:                    %can_assign = %{$authhash->{$context}}; 
                   2870:                 }
                   2871:             }
                   2872:         }
                   2873:     }
                   2874:     my $authnum = 0;
                   2875:     foreach my $key (keys(%can_assign)) {
                   2876:         if ($can_assign{$key}) {
                   2877:             $authnum ++;
                   2878:         }
                   2879:     }
                   2880:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2881:         $authnum --;
                   2882:     }
                   2883:     return ($authnum,%can_assign);
                   2884: }
                   2885: 
1.80      albertel 2886: ###############################################################
                   2887: ##    Get Kerberos Defaults for Domain                 ##
                   2888: ###############################################################
                   2889: ##
                   2890: ## Returns default kerberos version and an associated argument
                   2891: ## as listed in file domain.tab. If not listed, provides
                   2892: ## appropriate default domain and kerberos version.
                   2893: ##
                   2894: #-------------------------------------------
                   2895: 
                   2896: =pod
                   2897: 
1.648     raeburn  2898: =item * &get_kerberos_defaults()
1.80      albertel 2899: 
                   2900: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2901: version and domain. If not found, it defaults to version 4 and the 
                   2902: domain of the server.
1.80      albertel 2903: 
1.648     raeburn  2904: =over 4
                   2905: 
1.80      albertel 2906: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2907: 
1.648     raeburn  2908: =back
                   2909: 
                   2910: =back
                   2911: 
1.80      albertel 2912: =cut
                   2913: 
                   2914: #-------------------------------------------
                   2915: sub get_kerberos_defaults {
                   2916:     my $domain=shift;
1.641     raeburn  2917:     my ($krbdef,$krbdefdom);
                   2918:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2919:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2920:         $krbdef = $domdefaults{'auth_def'};
                   2921:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2922:     } else {
1.80      albertel 2923:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2924:         my $krbdefdom=$1;
                   2925:         $krbdefdom=~tr/a-z/A-Z/;
                   2926:         $krbdef = "krb4";
                   2927:     }
                   2928:     return ($krbdef,$krbdefdom);
                   2929: }
1.112     bowersj2 2930: 
1.32      matthew  2931: 
1.46      matthew  2932: ###############################################################
                   2933: ##                Thesaurus Functions                        ##
                   2934: ###############################################################
1.20      www      2935: 
1.46      matthew  2936: =pod
1.20      www      2937: 
1.112     bowersj2 2938: =head1 Thesaurus Functions
                   2939: 
                   2940: =over 4
                   2941: 
1.648     raeburn  2942: =item * &initialize_keywords()
1.46      matthew  2943: 
                   2944: Initializes the package variable %Keywords if it is empty.  Uses the
                   2945: package variable $thesaurus_db_file.
                   2946: 
                   2947: =cut
                   2948: 
                   2949: ###################################################
                   2950: 
                   2951: sub initialize_keywords {
                   2952:     return 1 if (scalar keys(%Keywords));
                   2953:     # If we are here, %Keywords is empty, so fill it up
                   2954:     #   Make sure the file we need exists...
                   2955:     if (! -e $thesaurus_db_file) {
                   2956:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2957:                                  " failed because it does not exist");
                   2958:         return 0;
                   2959:     }
                   2960:     #   Set up the hash as a database
                   2961:     my %thesaurus_db;
                   2962:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2963:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2964:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2965:                                  $thesaurus_db_file);
                   2966:         return 0;
                   2967:     } 
                   2968:     #  Get the average number of appearances of a word.
                   2969:     my $avecount = $thesaurus_db{'average.count'};
                   2970:     #  Put keywords (those that appear > average) into %Keywords
                   2971:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2972:         my ($count,undef) = split /:/,$data;
                   2973:         $Keywords{$word}++ if ($count > $avecount);
                   2974:     }
                   2975:     untie %thesaurus_db;
                   2976:     # Remove special values from %Keywords.
1.356     albertel 2977:     foreach my $value ('total.count','average.count') {
                   2978:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2979:   }
1.46      matthew  2980:     return 1;
                   2981: }
                   2982: 
                   2983: ###################################################
                   2984: 
                   2985: =pod
                   2986: 
1.648     raeburn  2987: =item * &keyword($word)
1.46      matthew  2988: 
                   2989: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2990: than the average number of times in the thesaurus database.  Calls 
                   2991: &initialize_keywords
                   2992: 
                   2993: =cut
                   2994: 
                   2995: ###################################################
1.20      www      2996: 
                   2997: sub keyword {
1.46      matthew  2998:     return if (!&initialize_keywords());
                   2999:     my $word=lc(shift());
                   3000:     $word=~s/\W//g;
                   3001:     return exists($Keywords{$word});
1.20      www      3002: }
1.46      matthew  3003: 
                   3004: ###############################################################
                   3005: 
                   3006: =pod 
1.20      www      3007: 
1.648     raeburn  3008: =item * &get_related_words()
1.46      matthew  3009: 
1.160     matthew  3010: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3011: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3012: will be returned.  The order of the words returned is determined by the
                   3013: database which holds them.
                   3014: 
                   3015: Uses global $thesaurus_db_file.
                   3016: 
1.1057    foxr     3017: 
1.46      matthew  3018: =cut
                   3019: 
                   3020: ###############################################################
                   3021: sub get_related_words {
                   3022:     my $keyword = shift;
                   3023:     my %thesaurus_db;
                   3024:     if (! -e $thesaurus_db_file) {
                   3025:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3026:                                  "failed because the file does not exist");
                   3027:         return ();
                   3028:     }
                   3029:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3030:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3031:         return ();
                   3032:     } 
                   3033:     my @Words=();
1.429     www      3034:     my $count=0;
1.46      matthew  3035:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3036: 	# The first element is the number of times
                   3037: 	# the word appears.  We do not need it now.
1.429     www      3038: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3039: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3040: 	my $threshold=$mostfrequentcount/10;
                   3041:         foreach my $possibleword (@RelatedWords) {
                   3042:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3043:             if ($wordcount>$threshold) {
                   3044: 		push(@Words,$word);
                   3045:                 $count++;
                   3046:                 if ($count>10) { last; }
                   3047: 	    }
1.20      www      3048:         }
                   3049:     }
1.46      matthew  3050:     untie %thesaurus_db;
                   3051:     return @Words;
1.14      harris41 3052: }
1.46      matthew  3053: 
1.112     bowersj2 3054: =pod
                   3055: 
                   3056: =back
                   3057: 
                   3058: =cut
1.61      www      3059: 
                   3060: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3061: =pod
                   3062: 
1.112     bowersj2 3063: =head1 User Name Functions
                   3064: 
                   3065: =over 4
                   3066: 
1.648     raeburn  3067: =item * &plainname($uname,$udom,$first)
1.81      albertel 3068: 
1.112     bowersj2 3069: Takes a users logon name and returns it as a string in
1.226     albertel 3070: "first middle last generation" form 
                   3071: if $first is set to 'lastname' then it returns it as
                   3072: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3073: 
                   3074: =cut
1.61      www      3075: 
1.295     www      3076: 
1.81      albertel 3077: ###############################################################
1.61      www      3078: sub plainname {
1.226     albertel 3079:     my ($uname,$udom,$first)=@_;
1.537     albertel 3080:     return if (!defined($uname) || !defined($udom));
1.295     www      3081:     my %names=&getnames($uname,$udom);
1.226     albertel 3082:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3083: 					  $names{'middlename'},
                   3084: 					  $names{'lastname'},
                   3085: 					  $names{'generation'},$first);
                   3086:     $name=~s/^\s+//;
1.62      www      3087:     $name=~s/\s+$//;
                   3088:     $name=~s/\s+/ /g;
1.353     albertel 3089:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3090:     return $name;
1.61      www      3091: }
1.66      www      3092: 
                   3093: # -------------------------------------------------------------------- Nickname
1.81      albertel 3094: =pod
                   3095: 
1.648     raeburn  3096: =item * &nickname($uname,$udom)
1.81      albertel 3097: 
                   3098: Gets a users name and returns it as a string as
                   3099: 
                   3100: "&quot;nickname&quot;"
1.66      www      3101: 
1.81      albertel 3102: if the user has a nickname or
                   3103: 
                   3104: "first middle last generation"
                   3105: 
                   3106: if the user does not
                   3107: 
                   3108: =cut
1.66      www      3109: 
                   3110: sub nickname {
                   3111:     my ($uname,$udom)=@_;
1.537     albertel 3112:     return if (!defined($uname) || !defined($udom));
1.295     www      3113:     my %names=&getnames($uname,$udom);
1.68      albertel 3114:     my $name=$names{'nickname'};
1.66      www      3115:     if ($name) {
                   3116:        $name='&quot;'.$name.'&quot;'; 
                   3117:     } else {
                   3118:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3119: 	     $names{'lastname'}.' '.$names{'generation'};
                   3120:        $name=~s/\s+$//;
                   3121:        $name=~s/\s+/ /g;
                   3122:     }
                   3123:     return $name;
                   3124: }
                   3125: 
1.295     www      3126: sub getnames {
                   3127:     my ($uname,$udom)=@_;
1.537     albertel 3128:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3129:     if ($udom eq 'public' && $uname eq 'public') {
                   3130: 	return ('lastname' => &mt('Public'));
                   3131:     }
1.295     www      3132:     my $id=$uname.':'.$udom;
                   3133:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3134:     if ($cached) {
                   3135: 	return %{$names};
                   3136:     } else {
                   3137: 	my %loadnames=&Apache::lonnet::get('environment',
                   3138:                     ['firstname','middlename','lastname','generation','nickname'],
                   3139: 					 $udom,$uname);
                   3140: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3141: 	return %loadnames;
                   3142:     }
                   3143: }
1.61      www      3144: 
1.542     raeburn  3145: # -------------------------------------------------------------------- getemails
1.648     raeburn  3146: 
1.542     raeburn  3147: =pod
                   3148: 
1.648     raeburn  3149: =item * &getemails($uname,$udom)
1.542     raeburn  3150: 
                   3151: Gets a user's email information and returns it as a hash with keys:
                   3152: notification, critnotification, permanentemail
                   3153: 
                   3154: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3155: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3156:  
1.648     raeburn  3157: 
1.542     raeburn  3158: =cut
                   3159: 
1.648     raeburn  3160: 
1.466     albertel 3161: sub getemails {
                   3162:     my ($uname,$udom)=@_;
                   3163:     if ($udom eq 'public' && $uname eq 'public') {
                   3164: 	return;
                   3165:     }
1.467     www      3166:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3167:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3168:     my $id=$uname.':'.$udom;
                   3169:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3170:     if ($cached) {
                   3171: 	return %{$names};
                   3172:     } else {
                   3173: 	my %loadnames=&Apache::lonnet::get('environment',
                   3174:                     			   ['notification','critnotification',
                   3175: 					    'permanentemail'],
                   3176: 					   $udom,$uname);
                   3177: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3178: 	return %loadnames;
                   3179:     }
                   3180: }
                   3181: 
1.551     albertel 3182: sub flush_email_cache {
                   3183:     my ($uname,$udom)=@_;
                   3184:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3185:     if (!$uname) { $uname=$env{'user.name'};   }
                   3186:     return if ($udom eq 'public' && $uname eq 'public');
                   3187:     my $id=$uname.':'.$udom;
                   3188:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3189: }
                   3190: 
1.728     raeburn  3191: # -------------------------------------------------------------------- getlangs
                   3192: 
                   3193: =pod
                   3194: 
                   3195: =item * &getlangs($uname,$udom)
                   3196: 
                   3197: Gets a user's language preference and returns it as a hash with key:
                   3198: language.
                   3199: 
                   3200: =cut
                   3201: 
                   3202: 
                   3203: sub getlangs {
                   3204:     my ($uname,$udom) = @_;
                   3205:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3206:     if (!$uname) { $uname=$env{'user.name'};   }
                   3207:     my $id=$uname.':'.$udom;
                   3208:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3209:     if ($cached) {
                   3210:         return %{$langs};
                   3211:     } else {
                   3212:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3213:                                            $udom,$uname);
                   3214:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3215:         return %loadlangs;
                   3216:     }
                   3217: }
                   3218: 
                   3219: sub flush_langs_cache {
                   3220:     my ($uname,$udom)=@_;
                   3221:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3222:     if (!$uname) { $uname=$env{'user.name'};   }
                   3223:     return if ($udom eq 'public' && $uname eq 'public');
                   3224:     my $id=$uname.':'.$udom;
                   3225:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3226: }
                   3227: 
1.61      www      3228: # ------------------------------------------------------------------ Screenname
1.81      albertel 3229: 
                   3230: =pod
                   3231: 
1.648     raeburn  3232: =item * &screenname($uname,$udom)
1.81      albertel 3233: 
                   3234: Gets a users screenname and returns it as a string
                   3235: 
                   3236: =cut
1.61      www      3237: 
                   3238: sub screenname {
                   3239:     my ($uname,$udom)=@_;
1.258     albertel 3240:     if ($uname eq $env{'user.name'} &&
                   3241: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3242:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3243:     return $names{'screenname'};
1.62      www      3244: }
                   3245: 
1.212     albertel 3246: 
1.802     bisitz   3247: # ------------------------------------------------------------- Confirm Wrapper
                   3248: =pod
                   3249: 
1.1075.2.42  raeburn  3250: =item * &confirmwrapper($message)
1.802     bisitz   3251: 
                   3252: Wrap messages about completion of operation in box
                   3253: 
                   3254: =cut
                   3255: 
                   3256: sub confirmwrapper {
                   3257:     my ($message)=@_;
                   3258:     if ($message) {
                   3259:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3260:                .$message."\n"
                   3261:                .'</div>'."\n";
                   3262:     } else {
                   3263:         return $message;
                   3264:     }
                   3265: }
                   3266: 
1.62      www      3267: # ------------------------------------------------------------- Message Wrapper
                   3268: 
                   3269: sub messagewrapper {
1.369     www      3270:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3271:     return 
1.441     albertel 3272:         '<a href="/adm/email?compose=individual&amp;'.
                   3273:         'recname='.$username.'&amp;recdom='.$domain.
                   3274: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3275:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3276: }
1.802     bisitz   3277: 
1.74      www      3278: # --------------------------------------------------------------- Notes Wrapper
                   3279: 
                   3280: sub noteswrapper {
                   3281:     my ($link,$un,$do)=@_;
                   3282:     return 
1.896     amueller 3283: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3284: }
1.802     bisitz   3285: 
1.62      www      3286: # ------------------------------------------------------------- Aboutme Wrapper
                   3287: 
                   3288: sub aboutmewrapper {
1.1070    raeburn  3289:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3290:     if (!defined($username)  && !defined($domain)) {
                   3291:         return;
                   3292:     }
1.1075.2.15  raeburn  3293:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3294: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3295: }
                   3296: 
                   3297: # ------------------------------------------------------------ Syllabus Wrapper
                   3298: 
                   3299: sub syllabuswrapper {
1.707     bisitz   3300:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3301:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3302: }
1.14      harris41 3303: 
1.802     bisitz   3304: # -----------------------------------------------------------------------------
                   3305: 
1.208     matthew  3306: sub track_student_link {
1.887     raeburn  3307:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3308:     my $link ="/adm/trackstudent?";
1.208     matthew  3309:     my $title = 'View recent activity';
                   3310:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3311:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3312:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3313:         $title .= ' of this student';
1.268     albertel 3314:     } 
1.208     matthew  3315:     if (defined($target) && $target !~ /^\s*$/) {
                   3316:         $target = qq{target="$target"};
                   3317:     } else {
                   3318:         $target = '';
                   3319:     }
1.268     albertel 3320:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3321:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3322:     $title = &mt($title);
                   3323:     $linktext = &mt($linktext);
1.448     albertel 3324:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3325: 	&help_open_topic('View_recent_activity');
1.208     matthew  3326: }
                   3327: 
1.781     raeburn  3328: sub slot_reservations_link {
                   3329:     my ($linktext,$sname,$sdom,$target) = @_;
                   3330:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3331:     my $title = 'View slot reservation history';
                   3332:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3333:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3334:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3335:         $title .= ' of this student';
                   3336:     }
                   3337:     if (defined($target) && $target !~ /^\s*$/) {
                   3338:         $target = qq{target="$target"};
                   3339:     } else {
                   3340:         $target = '';
                   3341:     }
                   3342:     $title = &mt($title);
                   3343:     $linktext = &mt($linktext);
                   3344:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3345: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3346: 
                   3347: }
                   3348: 
1.508     www      3349: # ===================================================== Display a student photo
                   3350: 
                   3351: 
1.509     albertel 3352: sub student_image_tag {
1.508     www      3353:     my ($domain,$user)=@_;
                   3354:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3355:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3356: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3357:     } else {
                   3358: 	return '';
                   3359:     }
                   3360: }
                   3361: 
1.112     bowersj2 3362: =pod
                   3363: 
                   3364: =back
                   3365: 
                   3366: =head1 Access .tab File Data
                   3367: 
                   3368: =over 4
                   3369: 
1.648     raeburn  3370: =item * &languageids() 
1.112     bowersj2 3371: 
                   3372: returns list of all language ids
                   3373: 
                   3374: =cut
                   3375: 
1.14      harris41 3376: sub languageids {
1.16      harris41 3377:     return sort(keys(%language));
1.14      harris41 3378: }
                   3379: 
1.112     bowersj2 3380: =pod
                   3381: 
1.648     raeburn  3382: =item * &languagedescription() 
1.112     bowersj2 3383: 
                   3384: returns description of a specified language id
                   3385: 
                   3386: =cut
                   3387: 
1.14      harris41 3388: sub languagedescription {
1.125     www      3389:     my $code=shift;
                   3390:     return  ($supported_language{$code}?'* ':'').
                   3391:             $language{$code}.
1.126     www      3392: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3393: }
                   3394: 
1.1048    foxr     3395: =pod
                   3396: 
                   3397: =item * &plainlanguagedescription
                   3398: 
                   3399: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3400: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3401: 
                   3402: =cut
                   3403: 
1.145     www      3404: sub plainlanguagedescription {
                   3405:     my $code=shift;
                   3406:     return $language{$code};
                   3407: }
                   3408: 
1.1048    foxr     3409: =pod
                   3410: 
                   3411: =item * &supportedlanguagecode
                   3412: 
                   3413: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3414: code.
                   3415: 
                   3416: =cut
                   3417: 
1.145     www      3418: sub supportedlanguagecode {
                   3419:     my $code=shift;
                   3420:     return $supported_language{$code};
1.97      www      3421: }
                   3422: 
1.112     bowersj2 3423: =pod
                   3424: 
1.1048    foxr     3425: =item * &latexlanguage()
                   3426: 
                   3427: Given a language key code returns the correspondnig language to use
                   3428: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3429: is no supported hyphenation for the language code.
                   3430: 
                   3431: =cut
                   3432: 
                   3433: sub latexlanguage {
                   3434:     my $code = shift;
                   3435:     return $latex_language{$code};
                   3436: }
                   3437: 
                   3438: =pod
                   3439: 
                   3440: =item * &latexhyphenation()
                   3441: 
                   3442: Same as above but what's supplied is the language as it might be stored
                   3443: in the metadata.
                   3444: 
                   3445: =cut
                   3446: 
                   3447: sub latexhyphenation {
                   3448:     my $key = shift;
                   3449:     return $latex_language_bykey{$key};
                   3450: }
                   3451: 
                   3452: =pod
                   3453: 
1.648     raeburn  3454: =item * &copyrightids() 
1.112     bowersj2 3455: 
                   3456: returns list of all copyrights
                   3457: 
                   3458: =cut
                   3459: 
                   3460: sub copyrightids {
                   3461:     return sort(keys(%cprtag));
                   3462: }
                   3463: 
                   3464: =pod
                   3465: 
1.648     raeburn  3466: =item * &copyrightdescription() 
1.112     bowersj2 3467: 
                   3468: returns description of a specified copyright id
                   3469: 
                   3470: =cut
                   3471: 
                   3472: sub copyrightdescription {
1.166     www      3473:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3474: }
1.197     matthew  3475: 
                   3476: =pod
                   3477: 
1.648     raeburn  3478: =item * &source_copyrightids() 
1.192     taceyjo1 3479: 
                   3480: returns list of all source copyrights
                   3481: 
                   3482: =cut
                   3483: 
                   3484: sub source_copyrightids {
                   3485:     return sort(keys(%scprtag));
                   3486: }
                   3487: 
                   3488: =pod
                   3489: 
1.648     raeburn  3490: =item * &source_copyrightdescription() 
1.192     taceyjo1 3491: 
                   3492: returns description of a specified source copyright id
                   3493: 
                   3494: =cut
                   3495: 
                   3496: sub source_copyrightdescription {
                   3497:     return &mt($scprtag{shift(@_)});
                   3498: }
1.112     bowersj2 3499: 
                   3500: =pod
                   3501: 
1.648     raeburn  3502: =item * &filecategories() 
1.112     bowersj2 3503: 
                   3504: returns list of all file categories
                   3505: 
                   3506: =cut
                   3507: 
                   3508: sub filecategories {
                   3509:     return sort(keys(%category_extensions));
                   3510: }
                   3511: 
                   3512: =pod
                   3513: 
1.648     raeburn  3514: =item * &filecategorytypes() 
1.112     bowersj2 3515: 
                   3516: returns list of file types belonging to a given file
                   3517: category
                   3518: 
                   3519: =cut
                   3520: 
                   3521: sub filecategorytypes {
1.356     albertel 3522:     my ($cat) = @_;
                   3523:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3524: }
                   3525: 
                   3526: =pod
                   3527: 
1.648     raeburn  3528: =item * &fileembstyle() 
1.112     bowersj2 3529: 
                   3530: returns embedding style for a specified file type
                   3531: 
                   3532: =cut
                   3533: 
                   3534: sub fileembstyle {
                   3535:     return $fe{lc(shift(@_))};
1.169     www      3536: }
                   3537: 
1.351     www      3538: sub filemimetype {
                   3539:     return $fm{lc(shift(@_))};
                   3540: }
                   3541: 
1.169     www      3542: 
                   3543: sub filecategoryselect {
                   3544:     my ($name,$value)=@_;
1.189     matthew  3545:     return &select_form($value,$name,
1.970     raeburn  3546:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3547: }
                   3548: 
                   3549: =pod
                   3550: 
1.648     raeburn  3551: =item * &filedescription() 
1.112     bowersj2 3552: 
                   3553: returns description for a specified file type
                   3554: 
                   3555: =cut
                   3556: 
                   3557: sub filedescription {
1.188     matthew  3558:     my $file_description = $fd{lc(shift())};
                   3559:     $file_description =~ s:([\[\]]):~$1:g;
                   3560:     return &mt($file_description);
1.112     bowersj2 3561: }
                   3562: 
                   3563: =pod
                   3564: 
1.648     raeburn  3565: =item * &filedescriptionex() 
1.112     bowersj2 3566: 
                   3567: returns description for a specified file type with
                   3568: extra formatting
                   3569: 
                   3570: =cut
                   3571: 
                   3572: sub filedescriptionex {
                   3573:     my $ex=shift;
1.188     matthew  3574:     my $file_description = $fd{lc($ex)};
                   3575:     $file_description =~ s:([\[\]]):~$1:g;
                   3576:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3577: }
                   3578: 
                   3579: # End of .tab access
                   3580: =pod
                   3581: 
                   3582: =back
                   3583: 
                   3584: =cut
                   3585: 
                   3586: # ------------------------------------------------------------------ File Types
                   3587: sub fileextensions {
                   3588:     return sort(keys(%fe));
                   3589: }
                   3590: 
1.97      www      3591: # ----------------------------------------------------------- Display Languages
                   3592: # returns a hash with all desired display languages
                   3593: #
                   3594: 
                   3595: sub display_languages {
                   3596:     my %languages=();
1.695     raeburn  3597:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3598: 	$languages{$lang}=1;
1.97      www      3599:     }
                   3600:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3601:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3602: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3603: 	    $languages{$lang}=1;
1.97      www      3604:         }
                   3605:     }
                   3606:     return %languages;
1.14      harris41 3607: }
                   3608: 
1.582     albertel 3609: sub languages {
                   3610:     my ($possible_langs) = @_;
1.695     raeburn  3611:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3612:     if (!ref($possible_langs)) {
                   3613: 	if( wantarray ) {
                   3614: 	    return @preferred_langs;
                   3615: 	} else {
                   3616: 	    return $preferred_langs[0];
                   3617: 	}
                   3618:     }
                   3619:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3620:     my @preferred_possibilities;
                   3621:     foreach my $preferred_lang (@preferred_langs) {
                   3622: 	if (exists($possibilities{$preferred_lang})) {
                   3623: 	    push(@preferred_possibilities, $preferred_lang);
                   3624: 	}
                   3625:     }
                   3626:     if( wantarray ) {
                   3627: 	return @preferred_possibilities;
                   3628:     }
                   3629:     return $preferred_possibilities[0];
                   3630: }
                   3631: 
1.742     raeburn  3632: sub user_lang {
                   3633:     my ($touname,$toudom,$fromcid) = @_;
                   3634:     my @userlangs;
                   3635:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3636:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3637:                     $env{'course.'.$fromcid.'.languages'}));
                   3638:     } else {
                   3639:         my %langhash = &getlangs($touname,$toudom);
                   3640:         if ($langhash{'languages'} ne '') {
                   3641:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3642:         } else {
                   3643:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3644:             if ($domdefs{'lang_def'} ne '') {
                   3645:                 @userlangs = ($domdefs{'lang_def'});
                   3646:             }
                   3647:         }
                   3648:     }
                   3649:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3650:     my $user_lh = Apache::localize->get_handle(@languages);
                   3651:     return $user_lh;
                   3652: }
                   3653: 
                   3654: 
1.112     bowersj2 3655: ###############################################################
                   3656: ##               Student Answer Attempts                     ##
                   3657: ###############################################################
                   3658: 
                   3659: =pod
                   3660: 
                   3661: =head1 Alternate Problem Views
                   3662: 
                   3663: =over 4
                   3664: 
1.648     raeburn  3665: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3666:     $getattempt, $regexp, $gradesub)
                   3667: 
                   3668: Return string with previous attempt on problem. Arguments:
                   3669: 
                   3670: =over 4
                   3671: 
                   3672: =item * $symb: Problem, including path
                   3673: 
                   3674: =item * $username: username of the desired student
                   3675: 
                   3676: =item * $domain: domain of the desired student
1.14      harris41 3677: 
1.112     bowersj2 3678: =item * $course: Course ID
1.14      harris41 3679: 
1.112     bowersj2 3680: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3681:     something
1.14      harris41 3682: 
1.112     bowersj2 3683: =item * $regexp: if string matches this regexp, the string will be
                   3684:     sent to $gradesub
1.14      harris41 3685: 
1.112     bowersj2 3686: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3687: 
1.112     bowersj2 3688: =back
1.14      harris41 3689: 
1.112     bowersj2 3690: The output string is a table containing all desired attempts, if any.
1.16      harris41 3691: 
1.112     bowersj2 3692: =cut
1.1       albertel 3693: 
                   3694: sub get_previous_attempt {
1.43      ng       3695:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3696:   my $prevattempts='';
1.43      ng       3697:   no strict 'refs';
1.1       albertel 3698:   if ($symb) {
1.3       albertel 3699:     my (%returnhash)=
                   3700:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3701:     if ($returnhash{'version'}) {
                   3702:       my %lasthash=();
                   3703:       my $version;
                   3704:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3705:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3706: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3707:         }
1.1       albertel 3708:       }
1.596     albertel 3709:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3710:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3711:       my (%typeparts,%lasthidden);
1.945     raeburn  3712:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3713:       foreach my $key (sort(keys(%lasthash))) {
                   3714: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3715: 	if ($#parts > 0) {
1.31      albertel 3716: 	  my $data=$parts[-1];
1.989     raeburn  3717:           next if ($data eq 'foilorder');
1.31      albertel 3718: 	  pop(@parts);
1.1010    www      3719:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3720:           if ($data eq 'type') {
                   3721:               unless ($showsurv) {
                   3722:                   my $id = join(',',@parts);
                   3723:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3724:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3725:                       $lasthidden{$ign.'.'.$id} = 1;
                   3726:                   }
1.945     raeburn  3727:               }
1.1010    www      3728:           } 
1.31      albertel 3729: 	} else {
1.41      ng       3730: 	  if ($#parts == 0) {
                   3731: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3732: 	  } else {
                   3733: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3734: 	  }
1.31      albertel 3735: 	}
1.16      harris41 3736:       }
1.596     albertel 3737:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3738:       if ($getattempt eq '') {
                   3739: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3740:             my @hidden;
                   3741:             if (%typeparts) {
                   3742:                 foreach my $id (keys(%typeparts)) {
                   3743:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3744:                         push(@hidden,$id);
                   3745:                     }
                   3746:                 }
                   3747:             }
                   3748:             $prevattempts.=&start_data_table_row().
                   3749:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3750:             if (@hidden) {
                   3751:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3752:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3753:                     my $hide;
                   3754:                     foreach my $id (@hidden) {
                   3755:                         if ($key =~ /^\Q$id\E/) {
                   3756:                             $hide = 1;
                   3757:                             last;
                   3758:                         }
                   3759:                     }
                   3760:                     if ($hide) {
                   3761:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3762:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3763:                             my $value = &format_previous_attempt_value($key,
                   3764:                                              $returnhash{$version.':'.$key});
                   3765:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3766:                         } else {
                   3767:                             $prevattempts.='<td>&nbsp;</td>';
                   3768:                         }
                   3769:                     } else {
                   3770:                         if ($key =~ /\./) {
                   3771:                             my $value = &format_previous_attempt_value($key,
                   3772:                                               $returnhash{$version.':'.$key});
                   3773:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3774:                         } else {
                   3775:                             $prevattempts.='<td>&nbsp;</td>';
                   3776:                         }
                   3777:                     }
                   3778:                 }
                   3779:             } else {
                   3780: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3781:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3782: 		    my $value = &format_previous_attempt_value($key,
                   3783: 			            $returnhash{$version.':'.$key});
                   3784: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3785: 	        }
                   3786:             }
                   3787: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3788: 	 }
1.1       albertel 3789:       }
1.945     raeburn  3790:       my @currhidden = keys(%lasthidden);
1.596     albertel 3791:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3792:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3793:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3794:           if (%typeparts) {
                   3795:               my $hidden;
                   3796:               foreach my $id (@currhidden) {
                   3797:                   if ($key =~ /^\Q$id\E/) {
                   3798:                       $hidden = 1;
                   3799:                       last;
                   3800:                   }
                   3801:               }
                   3802:               if ($hidden) {
                   3803:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3804:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3805:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3806:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3807:                           $value = &$gradesub($value);
                   3808:                       }
                   3809:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3810:                   } else {
                   3811:                       $prevattempts.='<td>&nbsp;</td>';
                   3812:                   }
                   3813:               } else {
                   3814:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3815:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3816:                       $value = &$gradesub($value);
                   3817:                   }
                   3818:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3819:               }
                   3820:           } else {
                   3821: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3822: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3823:                   $value = &$gradesub($value);
                   3824:               }
                   3825: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3826:           }
1.16      harris41 3827:       }
1.596     albertel 3828:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3829:     } else {
1.596     albertel 3830:       $prevattempts=
                   3831: 	  &start_data_table().&start_data_table_row().
                   3832: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3833: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3834:     }
                   3835:   } else {
1.596     albertel 3836:     $prevattempts=
                   3837: 	  &start_data_table().&start_data_table_row().
                   3838: 	  '<td>'.&mt('No data.').'</td>'.
                   3839: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3840:   }
1.10      albertel 3841: }
                   3842: 
1.581     albertel 3843: sub format_previous_attempt_value {
                   3844:     my ($key,$value) = @_;
1.1011    www      3845:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3846: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3847:     } elsif (ref($value) eq 'ARRAY') {
                   3848: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3849:     } elsif ($key =~ /answerstring$/) {
                   3850:         my %answers = &Apache::lonnet::str2hash($value);
                   3851:         my @anskeys = sort(keys(%answers));
                   3852:         if (@anskeys == 1) {
                   3853:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3854:             if ($answer =~ m{\0}) {
                   3855:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3856:             }
                   3857:             my $tag_internal_answer_name = 'INTERNAL';
                   3858:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3859:                 $value = $answer; 
                   3860:             } else {
                   3861:                 $value = $anskeys[0].'='.$answer;
                   3862:             }
                   3863:         } else {
                   3864:             foreach my $ans (@anskeys) {
                   3865:                 my $answer = $answers{$ans};
1.1001    raeburn  3866:                 if ($answer =~ m{\0}) {
                   3867:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3868:                 }
                   3869:                 $value .=  $ans.'='.$answer.'<br />';;
                   3870:             } 
                   3871:         }
1.581     albertel 3872:     } else {
                   3873: 	$value = &unescape($value);
                   3874:     }
                   3875:     return $value;
                   3876: }
                   3877: 
                   3878: 
1.107     albertel 3879: sub relative_to_absolute {
                   3880:     my ($url,$output)=@_;
                   3881:     my $parser=HTML::TokeParser->new(\$output);
                   3882:     my $token;
                   3883:     my $thisdir=$url;
                   3884:     my @rlinks=();
                   3885:     while ($token=$parser->get_token) {
                   3886: 	if ($token->[0] eq 'S') {
                   3887: 	    if ($token->[1] eq 'a') {
                   3888: 		if ($token->[2]->{'href'}) {
                   3889: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3890: 		}
                   3891: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3892: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3893: 	    } elsif ($token->[1] eq 'base') {
                   3894: 		$thisdir=$token->[2]->{'href'};
                   3895: 	    }
                   3896: 	}
                   3897:     }
                   3898:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3899:     foreach my $link (@rlinks) {
1.726     raeburn  3900: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3901: 		($link=~/^\//) ||
                   3902: 		($link=~/^javascript:/i) ||
                   3903: 		($link=~/^mailto:/i) ||
                   3904: 		($link=~/^\#/)) {
                   3905: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3906: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3907: 	}
                   3908:     }
                   3909: # -------------------------------------------------- Deal with Applet codebases
                   3910:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3911:     return $output;
                   3912: }
                   3913: 
1.112     bowersj2 3914: =pod
                   3915: 
1.648     raeburn  3916: =item * &get_student_view()
1.112     bowersj2 3917: 
                   3918: show a snapshot of what student was looking at
                   3919: 
                   3920: =cut
                   3921: 
1.10      albertel 3922: sub get_student_view {
1.186     albertel 3923:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3924:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3925:   my (%form);
1.10      albertel 3926:   my @elements=('symb','courseid','domain','username');
                   3927:   foreach my $element (@elements) {
1.186     albertel 3928:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3929:   }
1.186     albertel 3930:   if (defined($moreenv)) {
                   3931:       %form=(%form,%{$moreenv});
                   3932:   }
1.236     albertel 3933:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3934:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3935:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3936:   $userview=~s/\<body[^\>]*\>//gi;
                   3937:   $userview=~s/\<\/body\>//gi;
                   3938:   $userview=~s/\<html\>//gi;
                   3939:   $userview=~s/\<\/html\>//gi;
                   3940:   $userview=~s/\<head\>//gi;
                   3941:   $userview=~s/\<\/head\>//gi;
                   3942:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3943:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3944:   if (wantarray) {
                   3945:      return ($userview,$response);
                   3946:   } else {
                   3947:      return $userview;
                   3948:   }
                   3949: }
                   3950: 
                   3951: sub get_student_view_with_retries {
                   3952:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3953: 
                   3954:     my $ok = 0;                 # True if we got a good response.
                   3955:     my $content;
                   3956:     my $response;
                   3957: 
                   3958:     # Try to get the student_view done. within the retries count:
                   3959:     
                   3960:     do {
                   3961:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3962:          $ok      = $response->is_success;
                   3963:          if (!$ok) {
                   3964:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3965:          }
                   3966:          $retries--;
                   3967:     } while (!$ok && ($retries > 0));
                   3968:     
                   3969:     if (!$ok) {
                   3970:        $content = '';          # On error return an empty content.
                   3971:     }
1.651     www      3972:     if (wantarray) {
                   3973:        return ($content, $response);
                   3974:     } else {
                   3975:        return $content;
                   3976:     }
1.11      albertel 3977: }
                   3978: 
1.112     bowersj2 3979: =pod
                   3980: 
1.648     raeburn  3981: =item * &get_student_answers() 
1.112     bowersj2 3982: 
                   3983: show a snapshot of how student was answering problem
                   3984: 
                   3985: =cut
                   3986: 
1.11      albertel 3987: sub get_student_answers {
1.100     sakharuk 3988:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      3989:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3990:   my (%moreenv);
1.11      albertel 3991:   my @elements=('symb','courseid','domain','username');
                   3992:   foreach my $element (@elements) {
1.186     albertel 3993:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3994:   }
1.186     albertel 3995:   $moreenv{'grade_target'}='answer';
                   3996:   %moreenv=(%form,%moreenv);
1.497     raeburn  3997:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   3998:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 3999:   return $userview;
1.1       albertel 4000: }
1.116     albertel 4001: 
                   4002: =pod
                   4003: 
                   4004: =item * &submlink()
                   4005: 
1.242     albertel 4006: Inputs: $text $uname $udom $symb $target
1.116     albertel 4007: 
                   4008: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4009: 
                   4010: =cut
                   4011: 
                   4012: ###############################################
                   4013: sub submlink {
1.242     albertel 4014:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4015:     if (!($uname && $udom)) {
                   4016: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4017: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4018: 	if (!$symb) { $symb=$cursymb; }
                   4019:     }
1.254     matthew  4020:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4021:     $symb=&escape($symb);
1.960     bisitz   4022:     if ($target) { $target=" target=\"$target\""; }
                   4023:     return
                   4024:         '<a href="/adm/grades?command=submission'.
                   4025:         '&amp;symb='.$symb.
                   4026:         '&amp;student='.$uname.
                   4027:         '&amp;userdom='.$udom.'"'.
                   4028:         $target.'>'.$text.'</a>';
1.242     albertel 4029: }
                   4030: ##############################################
                   4031: 
                   4032: =pod
                   4033: 
                   4034: =item * &pgrdlink()
                   4035: 
                   4036: Inputs: $text $uname $udom $symb $target
                   4037: 
                   4038: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4039: 
                   4040: =cut
                   4041: 
                   4042: ###############################################
                   4043: sub pgrdlink {
                   4044:     my $link=&submlink(@_);
                   4045:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4046:     return $link;
                   4047: }
                   4048: ##############################################
                   4049: 
                   4050: =pod
                   4051: 
                   4052: =item * &pprmlink()
                   4053: 
                   4054: Inputs: $text $uname $udom $symb $target
                   4055: 
                   4056: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4057: student and a specific resource
1.242     albertel 4058: 
                   4059: =cut
                   4060: 
                   4061: ###############################################
                   4062: sub pprmlink {
                   4063:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4064:     if (!($uname && $udom)) {
                   4065: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4066: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4067: 	if (!$symb) { $symb=$cursymb; }
                   4068:     }
1.254     matthew  4069:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4070:     $symb=&escape($symb);
1.242     albertel 4071:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4072:     return '<a href="/adm/parmset?command=set&amp;'.
                   4073: 	'symb='.$symb.'&amp;uname='.$uname.
                   4074: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4075: }
                   4076: ##############################################
1.37      matthew  4077: 
1.112     bowersj2 4078: =pod
                   4079: 
                   4080: =back
                   4081: 
                   4082: =cut
                   4083: 
1.37      matthew  4084: ###############################################
1.51      www      4085: 
                   4086: 
                   4087: sub timehash {
1.687     raeburn  4088:     my ($thistime) = @_;
                   4089:     my $timezone = &Apache::lonlocal::gettimezone();
                   4090:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4091:                      ->set_time_zone($timezone);
                   4092:     my $wday = $dt->day_of_week();
                   4093:     if ($wday == 7) { $wday = 0; }
                   4094:     return ( 'second' => $dt->second(),
                   4095:              'minute' => $dt->minute(),
                   4096:              'hour'   => $dt->hour(),
                   4097:              'day'     => $dt->day_of_month(),
                   4098:              'month'   => $dt->month(),
                   4099:              'year'    => $dt->year(),
                   4100:              'weekday' => $wday,
                   4101:              'dayyear' => $dt->day_of_year(),
                   4102:              'dlsav'   => $dt->is_dst() );
1.51      www      4103: }
                   4104: 
1.370     www      4105: sub utc_string {
                   4106:     my ($date)=@_;
1.371     www      4107:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4108: }
                   4109: 
1.51      www      4110: sub maketime {
                   4111:     my %th=@_;
1.687     raeburn  4112:     my ($epoch_time,$timezone,$dt);
                   4113:     $timezone = &Apache::lonlocal::gettimezone();
                   4114:     eval {
                   4115:         $dt = DateTime->new( year   => $th{'year'},
                   4116:                              month  => $th{'month'},
                   4117:                              day    => $th{'day'},
                   4118:                              hour   => $th{'hour'},
                   4119:                              minute => $th{'minute'},
                   4120:                              second => $th{'second'},
                   4121:                              time_zone => $timezone,
                   4122:                          );
                   4123:     };
                   4124:     if (!$@) {
                   4125:         $epoch_time = $dt->epoch;
                   4126:         if ($epoch_time) {
                   4127:             return $epoch_time;
                   4128:         }
                   4129:     }
1.51      www      4130:     return POSIX::mktime(
                   4131:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4132:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4133: }
                   4134: 
                   4135: #########################################
1.51      www      4136: 
                   4137: sub findallcourses {
1.482     raeburn  4138:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4139:     my %roles;
                   4140:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4141:     my %courses;
1.51      www      4142:     my $now=time;
1.482     raeburn  4143:     if (!defined($uname)) {
                   4144:         $uname = $env{'user.name'};
                   4145:     }
                   4146:     if (!defined($udom)) {
                   4147:         $udom = $env{'user.domain'};
                   4148:     }
                   4149:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4150:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4151:         if (!%roles) {
                   4152:             %roles = (
                   4153:                        cc => 1,
1.907     raeburn  4154:                        co => 1,
1.482     raeburn  4155:                        in => 1,
                   4156:                        ep => 1,
                   4157:                        ta => 1,
                   4158:                        cr => 1,
                   4159:                        st => 1,
                   4160:              );
                   4161:         }
                   4162:         foreach my $entry (keys(%roleshash)) {
                   4163:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4164:             if ($trole =~ /^cr/) { 
                   4165:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4166:             } else {
                   4167:                 next if (!exists($roles{$trole}));
                   4168:             }
                   4169:             if ($tend) {
                   4170:                 next if ($tend < $now);
                   4171:             }
                   4172:             if ($tstart) {
                   4173:                 next if ($tstart > $now);
                   4174:             }
1.1058    raeburn  4175:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4176:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4177:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4178:             if ($secpart eq '') {
                   4179:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4180:                 $sec = 'none';
1.1058    raeburn  4181:                 $value .= $cnum.'/';
1.482     raeburn  4182:             } else {
                   4183:                 $cnum = $cnumpart;
                   4184:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4185:                 $value .= $cnum.'/'.$sec;
                   4186:             }
                   4187:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4188:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4189:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4190:                 }
                   4191:             } else {
                   4192:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4193:             }
1.482     raeburn  4194:         }
                   4195:     } else {
                   4196:         foreach my $key (keys(%env)) {
1.483     albertel 4197: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4198:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4199: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4200: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4201: 	        next if (%roles && !exists($roles{$role}));
                   4202: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4203:                 my $active=1;
                   4204:                 if ($starttime) {
                   4205: 		    if ($now<$starttime) { $active=0; }
                   4206:                 }
                   4207:                 if ($endtime) {
                   4208:                     if ($now>$endtime) { $active=0; }
                   4209:                 }
                   4210:                 if ($active) {
1.1058    raeburn  4211:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4212:                     if ($sec eq '') {
                   4213:                         $sec = 'none';
1.1058    raeburn  4214:                     } else {
                   4215:                         $value .= $sec;
                   4216:                     }
                   4217:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4218:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4219:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4220:                         }
                   4221:                     } else {
                   4222:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4223:                     }
1.474     raeburn  4224:                 }
                   4225:             }
1.51      www      4226:         }
                   4227:     }
1.474     raeburn  4228:     return %courses;
1.51      www      4229: }
1.37      matthew  4230: 
1.54      www      4231: ###############################################
1.474     raeburn  4232: 
                   4233: sub blockcheck {
1.1062    raeburn  4234:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4235: 
                   4236:     if (!defined($udom)) {
                   4237:         $udom = $env{'user.domain'};
                   4238:     }
                   4239:     if (!defined($uname)) {
                   4240:         $uname = $env{'user.name'};
                   4241:     }
                   4242: 
                   4243:     # If uname and udom are for a course, check for blocks in the course.
                   4244: 
                   4245:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4246:         my ($startblock,$endblock,$triggerblock) = 
                   4247:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4248:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4249:     }
1.474     raeburn  4250: 
1.502     raeburn  4251:     my $startblock = 0;
                   4252:     my $endblock = 0;
1.1062    raeburn  4253:     my $triggerblock = '';
1.482     raeburn  4254:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4255: 
1.490     raeburn  4256:     # If uname is for a user, and activity is course-specific, i.e.,
                   4257:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4258: 
1.490     raeburn  4259:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4260:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4261:         foreach my $key (keys(%live_courses)) {
                   4262:             if ($key ne $env{'request.course.id'}) {
                   4263:                 delete($live_courses{$key});
                   4264:             }
                   4265:         }
                   4266:     }
                   4267: 
                   4268:     my $otheruser = 0;
                   4269:     my %own_courses;
                   4270:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4271:         # Resource belongs to user other than current user.
                   4272:         $otheruser = 1;
                   4273:         # Gather courses for current user
                   4274:         %own_courses = 
                   4275:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4276:     }
                   4277: 
                   4278:     # Gather active course roles - course coordinator, instructor, 
                   4279:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4280: 
                   4281:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4282:         my ($cdom,$cnum);
                   4283:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4284:             $cdom = $env{'course.'.$course.'.domain'};
                   4285:             $cnum = $env{'course.'.$course.'.num'};
                   4286:         } else {
1.490     raeburn  4287:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4288:         }
                   4289:         my $no_ownblock = 0;
                   4290:         my $no_userblock = 0;
1.533     raeburn  4291:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4292:             # Check if current user has 'evb' priv for this
                   4293:             if (defined($own_courses{$course})) {
                   4294:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4295:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4296:                     if ($sec ne 'none') {
                   4297:                         $checkrole .= '/'.$sec;
                   4298:                     }
                   4299:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4300:                         $no_ownblock = 1;
                   4301:                         last;
                   4302:                     }
                   4303:                 }
                   4304:             }
                   4305:             # if they have 'evb' priv and are currently not playing student
                   4306:             next if (($no_ownblock) &&
                   4307:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4308:         }
1.474     raeburn  4309:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4310:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4311:             if ($sec ne 'none') {
1.482     raeburn  4312:                 $checkrole .= '/'.$sec;
1.474     raeburn  4313:             }
1.490     raeburn  4314:             if ($otheruser) {
                   4315:                 # Resource belongs to user other than current user.
                   4316:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4317:                 my (%allroles,%userroles);
                   4318:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4319:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4320:                         my ($trole,$tdom,$tnum,$tsec);
                   4321:                         if ($entry =~ /^cr/) {
                   4322:                             ($trole,$tdom,$tnum,$tsec) = 
                   4323:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4324:                         } else {
                   4325:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4326:                         }
                   4327:                         my ($spec,$area,$trest);
                   4328:                         $area = '/'.$tdom.'/'.$tnum;
                   4329:                         $trest = $tnum;
                   4330:                         if ($tsec ne '') {
                   4331:                             $area .= '/'.$tsec;
                   4332:                             $trest .= '/'.$tsec;
                   4333:                         }
                   4334:                         $spec = $trole.'.'.$area;
                   4335:                         if ($trole =~ /^cr/) {
                   4336:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4337:                                                               $tdom,$spec,$trest,$area);
                   4338:                         } else {
                   4339:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4340:                                                                 $tdom,$spec,$trest,$area);
                   4341:                         }
                   4342:                     }
                   4343:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4344:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4345:                         if ($1) {
                   4346:                             $no_userblock = 1;
                   4347:                             last;
                   4348:                         }
1.486     raeburn  4349:                     }
                   4350:                 }
1.490     raeburn  4351:             } else {
                   4352:                 # Resource belongs to current user
                   4353:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4354:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4355:                     $no_ownblock = 1;
                   4356:                     last;
                   4357:                 }
1.474     raeburn  4358:             }
                   4359:         }
                   4360:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4361:         next if (($no_ownblock) &&
1.491     albertel 4362:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4363:         next if ($no_userblock);
1.474     raeburn  4364: 
1.866     kalberla 4365:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4366:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4367:         
1.1062    raeburn  4368:         my ($start,$end,$trigger) = 
                   4369:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4370:         if (($start != 0) && 
                   4371:             (($startblock == 0) || ($startblock > $start))) {
                   4372:             $startblock = $start;
1.1062    raeburn  4373:             if ($trigger ne '') {
                   4374:                 $triggerblock = $trigger;
                   4375:             }
1.502     raeburn  4376:         }
                   4377:         if (($end != 0)  &&
                   4378:             (($endblock == 0) || ($endblock < $end))) {
                   4379:             $endblock = $end;
1.1062    raeburn  4380:             if ($trigger ne '') {
                   4381:                 $triggerblock = $trigger;
                   4382:             }
1.502     raeburn  4383:         }
1.490     raeburn  4384:     }
1.1062    raeburn  4385:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4386: }
                   4387: 
                   4388: sub get_blocks {
1.1062    raeburn  4389:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4390:     my $startblock = 0;
                   4391:     my $endblock = 0;
1.1062    raeburn  4392:     my $triggerblock = '';
1.490     raeburn  4393:     my $course = $cdom.'_'.$cnum;
                   4394:     $setters->{$course} = {};
                   4395:     $setters->{$course}{'staff'} = [];
                   4396:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4397:     $setters->{$course}{'triggers'} = [];
                   4398:     my (@blockers,%triggered);
                   4399:     my $now = time;
                   4400:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4401:     if ($activity eq 'docs') {
                   4402:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4403:         foreach my $block (@blockers) {
                   4404:             if ($block =~ /^firstaccess____(.+)$/) {
                   4405:                 my $item = $1;
                   4406:                 my $type = 'map';
                   4407:                 my $timersymb = $item;
                   4408:                 if ($item eq 'course') {
                   4409:                     $type = 'course';
                   4410:                 } elsif ($item =~ /___\d+___/) {
                   4411:                     $type = 'resource';
                   4412:                 } else {
                   4413:                     $timersymb = &Apache::lonnet::symbread($item);
                   4414:                 }
                   4415:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4416:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4417:                 $triggered{$block} = {
                   4418:                                        start => $start,
                   4419:                                        end   => $end,
                   4420:                                        type  => $type,
                   4421:                                      };
                   4422:             }
                   4423:         }
                   4424:     } else {
                   4425:         foreach my $block (keys(%commblocks)) {
                   4426:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4427:                 my ($start,$end) = ($1,$2);
                   4428:                 if ($start <= time && $end >= time) {
                   4429:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4430:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4431:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4432:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4433:                                     push(@blockers,$block);
                   4434:                                 }
                   4435:                             }
                   4436:                         }
                   4437:                     }
                   4438:                 }
                   4439:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4440:                 my $item = $1;
                   4441:                 my $timersymb = $item; 
                   4442:                 my $type = 'map';
                   4443:                 if ($item eq 'course') {
                   4444:                     $type = 'course';
                   4445:                 } elsif ($item =~ /___\d+___/) {
                   4446:                     $type = 'resource';
                   4447:                 } else {
                   4448:                     $timersymb = &Apache::lonnet::symbread($item);
                   4449:                 }
                   4450:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4451:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4452:                 if ($start && $end) {
                   4453:                     if (($start <= time) && ($end >= time)) {
                   4454:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4455:                             push(@blockers,$block);
                   4456:                             $triggered{$block} = {
                   4457:                                                    start => $start,
                   4458:                                                    end   => $end,
                   4459:                                                    type  => $type,
                   4460:                                                  };
                   4461:                         }
                   4462:                     }
1.490     raeburn  4463:                 }
1.1062    raeburn  4464:             }
                   4465:         }
                   4466:     }
                   4467:     foreach my $blocker (@blockers) {
                   4468:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4469:             &parse_block_record($commblocks{$blocker});
                   4470:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4471:         my ($start,$end,$triggertype);
                   4472:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4473:             ($start,$end) = ($1,$2);
                   4474:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4475:             $start = $triggered{$blocker}{'start'};
                   4476:             $end = $triggered{$blocker}{'end'};
                   4477:             $triggertype = $triggered{$blocker}{'type'};
                   4478:         }
                   4479:         if ($start) {
                   4480:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4481:             if ($triggertype) {
                   4482:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4483:             } else {
                   4484:                 push(@{$$setters{$course}{'triggers'}},0);
                   4485:             }
                   4486:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4487:                 $startblock = $start;
                   4488:                 if ($triggertype) {
                   4489:                     $triggerblock = $blocker;
1.474     raeburn  4490:                 }
                   4491:             }
1.1062    raeburn  4492:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4493:                $endblock = $end;
                   4494:                if ($triggertype) {
                   4495:                    $triggerblock = $blocker;
                   4496:                }
                   4497:             }
1.474     raeburn  4498:         }
                   4499:     }
1.1062    raeburn  4500:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4501: }
                   4502: 
                   4503: sub parse_block_record {
                   4504:     my ($record) = @_;
                   4505:     my ($setuname,$setudom,$title,$blocks);
                   4506:     if (ref($record) eq 'HASH') {
                   4507:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4508:         $title = &unescape($record->{'event'});
                   4509:         $blocks = $record->{'blocks'};
                   4510:     } else {
                   4511:         my @data = split(/:/,$record,3);
                   4512:         if (scalar(@data) eq 2) {
                   4513:             $title = $data[1];
                   4514:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4515:         } else {
                   4516:             ($setuname,$setudom,$title) = @data;
                   4517:         }
                   4518:         $blocks = { 'com' => 'on' };
                   4519:     }
                   4520:     return ($setuname,$setudom,$title,$blocks);
                   4521: }
                   4522: 
1.854     kalberla 4523: sub blocking_status {
1.1062    raeburn  4524:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4525:     my %setters;
1.890     droeschl 4526: 
1.1061    raeburn  4527: # check for active blocking
1.1062    raeburn  4528:     my ($startblock,$endblock,$triggerblock) = 
                   4529:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4530:     my $blocked = 0;
                   4531:     if ($startblock && $endblock) {
                   4532:         $blocked = 1;
                   4533:     }
1.890     droeschl 4534: 
1.1061    raeburn  4535: # caller just wants to know whether a block is active
                   4536:     if (!wantarray) { return $blocked; }
                   4537: 
                   4538: # build a link to a popup window containing the details
                   4539:     my $querystring  = "?activity=$activity";
                   4540: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4541:     if ($activity eq 'port') {
                   4542:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4543:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4544:     } elsif ($activity eq 'docs') {
                   4545:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4546:     }
1.1061    raeburn  4547: 
                   4548:     my $output .= <<'END_MYBLOCK';
                   4549: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4550:     var options = "width=" + w + ",height=" + h + ",";
                   4551:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4552:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4553:     var newWin = window.open(url, wdwName, options);
                   4554:     newWin.focus();
                   4555: }
1.890     droeschl 4556: END_MYBLOCK
1.854     kalberla 4557: 
1.1061    raeburn  4558:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4559:   
1.1061    raeburn  4560:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4561:     my $text = &mt('Communication Blocked');
                   4562:     if ($activity eq 'docs') {
                   4563:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4564:     } elsif ($activity eq 'printout') {
                   4565:         $text = &mt('Printing Blocked');
1.1062    raeburn  4566:     }
1.1061    raeburn  4567:     $output .= <<"END_BLOCK";
1.867     kalberla 4568: <div class='LC_comblock'>
1.869     kalberla 4569:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4570:   title='$text'>
                   4571:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4572:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4573:   title='$text'>$text</a>
1.867     kalberla 4574: </div>
                   4575: 
                   4576: END_BLOCK
1.474     raeburn  4577: 
1.1061    raeburn  4578:     return ($blocked, $output);
1.854     kalberla 4579: }
1.490     raeburn  4580: 
1.60      matthew  4581: ###############################################
                   4582: 
1.682     raeburn  4583: sub check_ip_acc {
                   4584:     my ($acc)=@_;
                   4585:     &Apache::lonxml::debug("acc is $acc");
                   4586:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4587:         return 1;
                   4588:     }
                   4589:     my $allowed=0;
                   4590:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4591: 
                   4592:     my $name;
                   4593:     foreach my $pattern (split(',',$acc)) {
                   4594:         $pattern =~ s/^\s*//;
                   4595:         $pattern =~ s/\s*$//;
                   4596:         if ($pattern =~ /\*$/) {
                   4597:             #35.8.*
                   4598:             $pattern=~s/\*//;
                   4599:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4600:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4601:             #35.8.3.[34-56]
                   4602:             my $low=$2;
                   4603:             my $high=$3;
                   4604:             $pattern=$1;
                   4605:             if ($ip =~ /^\Q$pattern\E/) {
                   4606:                 my $last=(split(/\./,$ip))[3];
                   4607:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4608:             }
                   4609:         } elsif ($pattern =~ /^\*/) {
                   4610:             #*.msu.edu
                   4611:             $pattern=~s/\*//;
                   4612:             if (!defined($name)) {
                   4613:                 use Socket;
                   4614:                 my $netaddr=inet_aton($ip);
                   4615:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4616:             }
                   4617:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4618:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4619:             #127.0.0.1
                   4620:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4621:         } else {
                   4622:             #some.name.com
                   4623:             if (!defined($name)) {
                   4624:                 use Socket;
                   4625:                 my $netaddr=inet_aton($ip);
                   4626:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4627:             }
                   4628:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4629:         }
                   4630:         if ($allowed) { last; }
                   4631:     }
                   4632:     return $allowed;
                   4633: }
                   4634: 
                   4635: ###############################################
                   4636: 
1.60      matthew  4637: =pod
                   4638: 
1.112     bowersj2 4639: =head1 Domain Template Functions
                   4640: 
                   4641: =over 4
                   4642: 
                   4643: =item * &determinedomain()
1.60      matthew  4644: 
                   4645: Inputs: $domain (usually will be undef)
                   4646: 
1.63      www      4647: Returns: Determines which domain should be used for designs
1.60      matthew  4648: 
                   4649: =cut
1.54      www      4650: 
1.60      matthew  4651: ###############################################
1.63      www      4652: sub determinedomain {
                   4653:     my $domain=shift;
1.531     albertel 4654:     if (! $domain) {
1.60      matthew  4655:         # Determine domain if we have not been given one
1.893     raeburn  4656:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4657:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4658:         if ($env{'request.role.domain'}) { 
                   4659:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4660:         }
                   4661:     }
1.63      www      4662:     return $domain;
                   4663: }
                   4664: ###############################################
1.517     raeburn  4665: 
1.518     albertel 4666: sub devalidate_domconfig_cache {
                   4667:     my ($udom)=@_;
                   4668:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4669: }
                   4670: 
                   4671: # ---------------------- Get domain configuration for a domain
                   4672: sub get_domainconf {
                   4673:     my ($udom) = @_;
                   4674:     my $cachetime=1800;
                   4675:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4676:     if (defined($cached)) { return %{$result}; }
                   4677: 
                   4678:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4679: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4680:     my (%designhash,%legacy);
1.518     albertel 4681:     if (keys(%domconfig) > 0) {
                   4682:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4683:             if (keys(%{$domconfig{'login'}})) {
                   4684:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4685:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4686:                         if ($key eq 'loginvia') {
                   4687:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4688:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4689:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4690:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4691:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4692:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4693:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4694: 
                   4695:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4696:                                             } else {
1.1013    raeburn  4697:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4698:                                             }
                   4699:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4700:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4701:                                             }
1.946     raeburn  4702:                                         }
                   4703:                                     }
                   4704:                                 }
                   4705:                             }
                   4706:                         } else {
                   4707:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4708:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4709:                                     $domconfig{'login'}{$key}{$img};
                   4710:                             }
1.699     raeburn  4711:                         }
                   4712:                     } else {
                   4713:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4714:                     }
1.632     raeburn  4715:                 }
                   4716:             } else {
                   4717:                 $legacy{'login'} = 1;
1.518     albertel 4718:             }
1.632     raeburn  4719:         } else {
                   4720:             $legacy{'login'} = 1;
1.518     albertel 4721:         }
                   4722:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4723:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4724:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4725:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4726:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4727:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4728:                         }
1.518     albertel 4729:                     }
                   4730:                 }
1.632     raeburn  4731:             } else {
                   4732:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4733:             }
1.632     raeburn  4734:         } else {
                   4735:             $legacy{'rolecolors'} = 1;
1.518     albertel 4736:         }
1.948     raeburn  4737:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4738:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4739:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4740:             }
                   4741:         }
1.632     raeburn  4742:         if (keys(%legacy) > 0) {
                   4743:             my %legacyhash = &get_legacy_domconf($udom);
                   4744:             foreach my $item (keys(%legacyhash)) {
                   4745:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4746:                     if ($legacy{'login'}) { 
                   4747:                         $designhash{$item} = $legacyhash{$item};
                   4748:                     }
                   4749:                 } else {
                   4750:                     if ($legacy{'rolecolors'}) {
                   4751:                         $designhash{$item} = $legacyhash{$item};
                   4752:                     }
1.518     albertel 4753:                 }
                   4754:             }
                   4755:         }
1.632     raeburn  4756:     } else {
                   4757:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4758:     }
                   4759:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4760: 				  $cachetime);
                   4761:     return %designhash;
                   4762: }
                   4763: 
1.632     raeburn  4764: sub get_legacy_domconf {
                   4765:     my ($udom) = @_;
                   4766:     my %legacyhash;
                   4767:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4768:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4769:     if (-e $designfile) {
                   4770:         if ( open (my $fh,"<$designfile") ) {
                   4771:             while (my $line = <$fh>) {
                   4772:                 next if ($line =~ /^\#/);
                   4773:                 chomp($line);
                   4774:                 my ($key,$val)=(split(/\=/,$line));
                   4775:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4776:             }
                   4777:             close($fh);
                   4778:         }
                   4779:     }
1.1026    raeburn  4780:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4781:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4782:     }
                   4783:     return %legacyhash;
                   4784: }
                   4785: 
1.63      www      4786: =pod
                   4787: 
1.112     bowersj2 4788: =item * &domainlogo()
1.63      www      4789: 
                   4790: Inputs: $domain (usually will be undef)
                   4791: 
                   4792: Returns: A link to a domain logo, if the domain logo exists.
                   4793: If the domain logo does not exist, a description of the domain.
                   4794: 
                   4795: =cut
1.112     bowersj2 4796: 
1.63      www      4797: ###############################################
                   4798: sub domainlogo {
1.517     raeburn  4799:     my $domain = &determinedomain(shift);
1.518     albertel 4800:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4801:     # See if there is a logo
                   4802:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4803:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4804:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4805: 	    if ($imgsrc =~ m{^/res/}) {
                   4806: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4807: 		&Apache::lonnet::repcopy($local_name);
                   4808: 	    }
                   4809: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4810:         } 
                   4811:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4812:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4813:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4814:     } else {
1.60      matthew  4815:         return '';
1.59      www      4816:     }
                   4817: }
1.63      www      4818: ##############################################
                   4819: 
                   4820: =pod
                   4821: 
1.112     bowersj2 4822: =item * &designparm()
1.63      www      4823: 
                   4824: Inputs: $which parameter; $domain (usually will be undef)
                   4825: 
                   4826: Returns: value of designparamter $which
                   4827: 
                   4828: =cut
1.112     bowersj2 4829: 
1.397     albertel 4830: 
1.400     albertel 4831: ##############################################
1.397     albertel 4832: sub designparm {
                   4833:     my ($which,$domain)=@_;
                   4834:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4835:         return $env{'environment.color.'.$which};
1.96      www      4836:     }
1.63      www      4837:     $domain=&determinedomain($domain);
1.1016    raeburn  4838:     my %domdesign;
                   4839:     unless ($domain eq 'public') {
                   4840:         %domdesign = &get_domainconf($domain);
                   4841:     }
1.520     raeburn  4842:     my $output;
1.517     raeburn  4843:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4844:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4845:     } else {
1.520     raeburn  4846:         $output = $defaultdesign{$which};
                   4847:     }
                   4848:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4849:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4850:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4851:             if ($output =~ m{^/res/}) {
                   4852:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4853:                 &Apache::lonnet::repcopy($local_name);
                   4854:             }
1.520     raeburn  4855:             $output = &lonhttpdurl($output);
                   4856:         }
1.63      www      4857:     }
1.520     raeburn  4858:     return $output;
1.63      www      4859: }
1.59      www      4860: 
1.822     bisitz   4861: ##############################################
                   4862: =pod
                   4863: 
1.832     bisitz   4864: =item * &authorspace()
                   4865: 
1.1028    raeburn  4866: Inputs: $url (usually will be undef).
1.832     bisitz   4867: 
1.1075.2.40  raeburn  4868: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  4869:          directory being viewed (or for which action is being taken). 
                   4870:          If $url is provided, and begins /priv/<domain>/<uname>
                   4871:          the path will be that portion of the $context argument.
                   4872:          Otherwise the path will be for the author space of the current
                   4873:          user when the current role is author, or for that of the 
                   4874:          co-author/assistant co-author space when the current role 
                   4875:          is co-author or assistant co-author.
1.832     bisitz   4876: 
                   4877: =cut
                   4878: 
                   4879: sub authorspace {
1.1028    raeburn  4880:     my ($url) = @_;
                   4881:     if ($url ne '') {
                   4882:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4883:            return $1;
                   4884:         }
                   4885:     }
1.832     bisitz   4886:     my $caname = '';
1.1024    www      4887:     my $cadom = '';
1.1028    raeburn  4888:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4889:         ($cadom,$caname) =
1.832     bisitz   4890:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4891:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4892:         $caname = $env{'user.name'};
1.1024    www      4893:         $cadom = $env{'user.domain'};
1.832     bisitz   4894:     }
1.1028    raeburn  4895:     if (($caname ne '') && ($cadom ne '')) {
                   4896:         return "/priv/$cadom/$caname/";
                   4897:     }
                   4898:     return;
1.832     bisitz   4899: }
                   4900: 
                   4901: ##############################################
                   4902: =pod
                   4903: 
1.822     bisitz   4904: =item * &head_subbox()
                   4905: 
                   4906: Inputs: $content (contains HTML code with page functions, etc.)
                   4907: 
                   4908: Returns: HTML div with $content
                   4909:          To be included in page header
                   4910: 
                   4911: =cut
                   4912: 
                   4913: sub head_subbox {
                   4914:     my ($content)=@_;
                   4915:     my $output =
1.993     raeburn  4916:         '<div class="LC_head_subbox">'
1.822     bisitz   4917:        .$content
                   4918:        .'</div>'
                   4919: }
                   4920: 
                   4921: ##############################################
                   4922: =pod
                   4923: 
                   4924: =item * &CSTR_pageheader()
                   4925: 
1.1026    raeburn  4926: Input: (optional) filename from which breadcrumb trail is built.
                   4927:        In most cases no input as needed, as $env{'request.filename'}
                   4928:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4929: 
                   4930: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  4931:          To be included on Authoring Space pages
1.822     bisitz   4932: 
                   4933: =cut
                   4934: 
                   4935: sub CSTR_pageheader {
1.1026    raeburn  4936:     my ($trailfile) = @_;
                   4937:     if ($trailfile eq '') {
                   4938:         $trailfile = $env{'request.filename'};
                   4939:     }
                   4940: 
                   4941: # this is for resources; directories have customtitle, and crumbs
                   4942: # and select recent are created in lonpubdir.pm
                   4943: 
                   4944:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      4945:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  4946:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  4947:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   4948:     $formaction =~ s{/+}{/}g;
1.822     bisitz   4949: 
                   4950:     my $parentpath = '';
                   4951:     my $lastitem = '';
                   4952:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4953:         $parentpath = $1;
                   4954:         $lastitem = $2;
                   4955:     } else {
                   4956:         $lastitem = $thisdisfn;
                   4957:     }
1.921     bisitz   4958: 
                   4959:     my $output =
1.822     bisitz   4960:          '<div>'
                   4961:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  4962:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   4963:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   4964:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      4965:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   4966: 
                   4967:     if ($lastitem) {
                   4968:         $output .=
                   4969:              '<span class="LC_filename">'
                   4970:             .$lastitem
                   4971:             .'</span>';
                   4972:     }
                   4973:     $output .=
                   4974:          '<br />'
1.822     bisitz   4975:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   4976:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   4977:         .'</form>'
                   4978:         .&Apache::lonmenu::constspaceform()
                   4979:         .'</div>';
1.921     bisitz   4980: 
                   4981:     return $output;
1.822     bisitz   4982: }
                   4983: 
1.60      matthew  4984: ###############################################
                   4985: ###############################################
                   4986: 
                   4987: =pod
                   4988: 
1.112     bowersj2 4989: =back
                   4990: 
1.549     albertel 4991: =head1 HTML Helpers
1.112     bowersj2 4992: 
                   4993: =over 4
                   4994: 
                   4995: =item * &bodytag()
1.60      matthew  4996: 
                   4997: Returns a uniform header for LON-CAPA web pages.
                   4998: 
                   4999: Inputs: 
                   5000: 
1.112     bowersj2 5001: =over 4
                   5002: 
                   5003: =item * $title, A title to be displayed on the page.
                   5004: 
                   5005: =item * $function, the current role (can be undef).
                   5006: 
                   5007: =item * $addentries, extra parameters for the <body> tag.
                   5008: 
                   5009: =item * $bodyonly, if defined, only return the <body> tag.
                   5010: 
                   5011: =item * $domain, if defined, force a given domain.
                   5012: 
                   5013: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5014:             text interface only)
1.60      matthew  5015: 
1.814     bisitz   5016: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5017:                      navigational links
1.317     albertel 5018: 
1.338     albertel 5019: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5020: 
1.1075.2.12  raeburn  5021: =item * $no_inline_link, if true and in remote mode, don't show the
                   5022:          'Switch To Inline Menu' link
                   5023: 
1.460     albertel 5024: =item * $args, optional argument valid values are
                   5025:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5026:             inherit_jsmath -> when creating popup window in a page,
                   5027:                               should it have jsmath forced on by the
                   5028:                               current page
1.460     albertel 5029: 
1.1075.2.15  raeburn  5030: =item * $advtoolsref, optional argument, ref to an array containing
                   5031:             inlineremote items to be added in "Functions" menu below
                   5032:             breadcrumbs.
                   5033: 
1.112     bowersj2 5034: =back
                   5035: 
1.60      matthew  5036: Returns: A uniform header for LON-CAPA web pages.  
                   5037: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5038: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5039: other decorations will be returned.
                   5040: 
                   5041: =cut
                   5042: 
1.54      www      5043: sub bodytag {
1.831     bisitz   5044:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5045:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5046: 
1.954     raeburn  5047:     my $public;
                   5048:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5049:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5050:         $public = 1;
                   5051:     }
1.460     albertel 5052:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5053:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5054: 
1.183     matthew  5055:     $function = &get_users_function() if (!$function);
1.339     albertel 5056:     my $img =    &designparm($function.'.img',$domain);
                   5057:     my $font =   &designparm($function.'.font',$domain);
                   5058:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5059: 
1.803     bisitz   5060:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5061: 		   'bgcolor' => $pgbg,
1.339     albertel 5062: 		   'text'    => $font,
                   5063:                    'alink'   => &designparm($function.'.alink',$domain),
                   5064: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5065: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5066:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5067: 
1.63      www      5068:  # role and realm
1.378     raeburn  5069:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5070:     if ($role  eq 'ca') {
1.479     albertel 5071:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5072:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5073:     } 
1.55      www      5074: # realm
1.258     albertel 5075:     if ($env{'request.course.id'}) {
1.378     raeburn  5076:         if ($env{'request.role'} !~ /^cr/) {
                   5077:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5078:         }
1.898     raeburn  5079:         if ($env{'request.course.sec'}) {
                   5080:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5081:         }   
1.359     albertel 5082: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5083:     } else {
                   5084:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5085:     }
1.433     albertel 5086: 
1.359     albertel 5087:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5088: 
1.438     albertel 5089:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5090: 
1.101     www      5091: # construct main body tag
1.359     albertel 5092:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5093: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5094: 
1.1075.2.38  raeburn  5095:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5096: 
                   5097:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5098:         return $bodytag;
1.1075.2.38  raeburn  5099:     }
1.359     albertel 5100: 
1.954     raeburn  5101:     if ($public) {
1.433     albertel 5102: 	undef($role);
                   5103:     }
1.359     albertel 5104:     
1.762     bisitz   5105:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5106:     #
                   5107:     # Extra info if you are the DC
                   5108:     my $dc_info = '';
                   5109:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5110:                         $env{'course.'.$env{'request.course.id'}.
                   5111:                                  '.domain'}.'/'})) {
                   5112:         my $cid = $env{'request.course.id'};
1.917     raeburn  5113:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5114:         $dc_info =~ s/\s+$//;
1.359     albertel 5115:     }
                   5116: 
1.898     raeburn  5117:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.903     droeschl 5118: 
1.1075.2.13  raeburn  5119:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5120: 
1.1075.2.38  raeburn  5121: 
                   5122: 
1.1075.2.21  raeburn  5123:     my $funclist;
                   5124:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5125:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5126:                     Apache::lonmenu::serverform();
                   5127:         my $forbodytag;
                   5128:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5129:                                             $forcereg,$args->{'group'},
                   5130:                                             $args->{'bread_crumbs'},
                   5131:                                             $advtoolsref,'',\$forbodytag);
                   5132:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5133:             $funclist = $forbodytag;
                   5134:         }
                   5135:     } else {
1.903     droeschl 5136: 
                   5137:         #    if ($env{'request.state'} eq 'construct') {
                   5138:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5139:         #    }
                   5140: 
1.1075.2.38  raeburn  5141:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5142:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5143: 
1.1075.2.38  raeburn  5144:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5145: 
1.916     droeschl 5146:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5147:             if ($dc_info) {
                   5148:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5149:             }
1.1075.2.38  raeburn  5150:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5151:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5152:             return $bodytag;
                   5153:         }
1.894     droeschl 5154: 
1.927     raeburn  5155:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5156:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5157:         }
1.916     droeschl 5158: 
1.1075.2.38  raeburn  5159:         $bodytag .= $right;
1.852     droeschl 5160: 
1.917     raeburn  5161:         if ($dc_info) {
                   5162:             $dc_info = &dc_courseid_toggle($dc_info);
                   5163:         }
                   5164:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5165: 
1.1075.2.61  raeburn  5166:         #if directed to not display the secondary menu, don't.
                   5167:         if ($args->{'no_secondary_menu'}) {
                   5168:             return $bodytag;
                   5169:         }
1.903     droeschl 5170:         #don't show menus for public users
1.954     raeburn  5171:         if (!$public){
1.1075.2.52  raeburn  5172:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5173:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5174:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5175:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5176:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5177:                                 $args->{'bread_crumbs'});
                   5178:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5179:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5180:                                                             $args->{'group'});
1.1075.2.15  raeburn  5181:             } else {
1.1075.2.21  raeburn  5182:                 my $forbodytag;
                   5183:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5184:                                                     $forcereg,$args->{'group'},
                   5185:                                                     $args->{'bread_crumbs'},
                   5186:                                                     $advtoolsref,'',\$forbodytag);
                   5187:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5188:                     $bodytag .= $forbodytag;
                   5189:                 }
1.920     raeburn  5190:             }
1.903     droeschl 5191:         }else{
                   5192:             # this is to seperate menu from content when there's no secondary
                   5193:             # menu. Especially needed for public accessible ressources.
                   5194:             $bodytag .= '<hr style="clear:both" />';
                   5195:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5196:         }
1.903     droeschl 5197: 
1.235     raeburn  5198:         return $bodytag;
1.1075.2.12  raeburn  5199:     }
                   5200: 
                   5201: #
                   5202: # Top frame rendering, Remote is up
                   5203: #
                   5204: 
                   5205:     my $imgsrc = $img;
                   5206:     if ($img =~ /^\/adm/) {
                   5207:         $imgsrc = &lonhttpdurl($img);
                   5208:     }
                   5209:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5210: 
1.1075.2.60  raeburn  5211:     my $help=($no_inline_link?''
                   5212:               :&Apache::loncommon::top_nav_help('Help'));
                   5213: 
1.1075.2.12  raeburn  5214:     # Explicit link to get inline menu
                   5215:     my $menu= ($no_inline_link?''
                   5216:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5217: 
                   5218:     if ($dc_info) {
                   5219:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5220:     }
                   5221: 
1.1075.2.38  raeburn  5222:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5223:     unless ($public) {
                   5224:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5225:                                 undef,'LC_menubuttons_link');
                   5226:     }
                   5227: 
1.1075.2.12  raeburn  5228:     unless ($env{'form.inhibitmenu'}) {
                   5229:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5230:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5231:                        <li>$help</li>
1.1075.2.12  raeburn  5232:                        <li>$menu</li>
                   5233:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5234:     }
1.1075.2.13  raeburn  5235:     if ($env{'request.state'} eq 'construct') {
                   5236:         if (!$public){
                   5237:             if ($env{'request.state'} eq 'construct') {
                   5238:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5239:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5240:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5241:                             &Apache::lonmenu::innerregister($forcereg,
                   5242:                                                             $args->{'bread_crumbs'});
                   5243:             }
                   5244:         }
                   5245:     }
1.1075.2.21  raeburn  5246:     return $bodytag."\n".$funclist;
1.182     matthew  5247: }
                   5248: 
1.917     raeburn  5249: sub dc_courseid_toggle {
                   5250:     my ($dc_info) = @_;
1.980     raeburn  5251:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5252:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5253:            &mt('(More ...)').'</a></span>'.
                   5254:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5255: }
                   5256: 
1.330     albertel 5257: sub make_attr_string {
                   5258:     my ($register,$attr_ref) = @_;
                   5259: 
                   5260:     if ($attr_ref && !ref($attr_ref)) {
                   5261: 	die("addentries Must be a hash ref ".
                   5262: 	    join(':',caller(1))." ".
                   5263: 	    join(':',caller(0))." ");
                   5264:     }
                   5265: 
                   5266:     if ($register) {
1.339     albertel 5267: 	my ($on_load,$on_unload);
                   5268: 	foreach my $key (keys(%{$attr_ref})) {
                   5269: 	    if      (lc($key) eq 'onload') {
                   5270: 		$on_load.=$attr_ref->{$key}.';';
                   5271: 		delete($attr_ref->{$key});
                   5272: 
                   5273: 	    } elsif (lc($key) eq 'onunload') {
                   5274: 		$on_unload.=$attr_ref->{$key}.';';
                   5275: 		delete($attr_ref->{$key});
                   5276: 	    }
                   5277: 	}
1.1075.2.12  raeburn  5278:         if ($env{'environment.remote'} eq 'on') {
                   5279:             $attr_ref->{'onload'}  =
                   5280:                 &Apache::lonmenu::loadevents().  $on_load;
                   5281:             $attr_ref->{'onunload'}=
                   5282:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5283:         } else {  
                   5284: 	    $attr_ref->{'onload'}  = $on_load;
                   5285: 	    $attr_ref->{'onunload'}= $on_unload;
                   5286:         }
1.330     albertel 5287:     }
1.339     albertel 5288: 
1.330     albertel 5289:     my $attr_string;
1.1075.2.56  raeburn  5290:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5291: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5292:     }
                   5293:     return $attr_string;
                   5294: }
                   5295: 
                   5296: 
1.182     matthew  5297: ###############################################
1.251     albertel 5298: ###############################################
                   5299: 
                   5300: =pod
                   5301: 
                   5302: =item * &endbodytag()
                   5303: 
                   5304: Returns a uniform footer for LON-CAPA web pages.
                   5305: 
1.635     raeburn  5306: Inputs: 1 - optional reference to an args hash
                   5307: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5308: a 'Continue' link is not displayed if the page contains an
                   5309: internal redirect in the <head></head> section,
                   5310: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5311: 
                   5312: =cut
                   5313: 
                   5314: sub endbodytag {
1.635     raeburn  5315:     my ($args) = @_;
1.1075.2.6  raeburn  5316:     my $endbodytag;
                   5317:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5318:         $endbodytag='</body>';
                   5319:     }
1.269     albertel 5320:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5321:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5322:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5323: 	    $endbodytag=
                   5324: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5325: 	        &mt('Continue').'</a>'.
                   5326: 	        $endbodytag;
                   5327:         }
1.315     albertel 5328:     }
1.251     albertel 5329:     return $endbodytag;
                   5330: }
                   5331: 
1.352     albertel 5332: =pod
                   5333: 
                   5334: =item * &standard_css()
                   5335: 
                   5336: Returns a style sheet
                   5337: 
                   5338: Inputs: (all optional)
                   5339:             domain         -> force to color decorate a page for a specific
                   5340:                                domain
                   5341:             function       -> force usage of a specific rolish color scheme
                   5342:             bgcolor        -> override the default page bgcolor
                   5343: 
                   5344: =cut
                   5345: 
1.343     albertel 5346: sub standard_css {
1.345     albertel 5347:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5348:     $function  = &get_users_function() if (!$function);
                   5349:     my $img    = &designparm($function.'.img',   $domain);
                   5350:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5351:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5352:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5353: #second colour for later usage
1.345     albertel 5354:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5355:     my $pgbg_or_bgcolor =
                   5356: 	         $bgcolor ||
1.352     albertel 5357: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5358:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5359:     my $alink  = &designparm($function.'.alink', $domain);
                   5360:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5361:     my $link   = &designparm($function.'.link',  $domain);
                   5362: 
1.602     albertel 5363:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5364:     my $mono                 = 'monospace';
1.850     bisitz   5365:     my $data_table_head      = $sidebg;
                   5366:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5367:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5368:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5369:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5370:     my $mail_new             = '#FFBB77';
                   5371:     my $mail_new_hover       = '#DD9955';
                   5372:     my $mail_read            = '#BBBB77';
                   5373:     my $mail_read_hover      = '#999944';
                   5374:     my $mail_replied         = '#AAAA88';
                   5375:     my $mail_replied_hover   = '#888855';
                   5376:     my $mail_other           = '#99BBBB';
                   5377:     my $mail_other_hover     = '#669999';
1.391     albertel 5378:     my $table_header         = '#DDDDDD';
1.489     raeburn  5379:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5380:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5381:     my $button_hover         = '#BF2317';
1.392     albertel 5382: 
1.608     albertel 5383:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5384:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5385:                                              : '0 3px 0 4px';
1.448     albertel 5386: 
1.523     albertel 5387: 
1.343     albertel 5388:     return <<END;
1.947     droeschl 5389: 
                   5390: /* needed for iframe to allow 100% height in FF */
                   5391: body, html { 
                   5392:     margin: 0;
                   5393:     padding: 0 0.5%;
                   5394:     height: 99%; /* to avoid scrollbars */
                   5395: }
                   5396: 
1.795     www      5397: body {
1.911     bisitz   5398:   font-family: $sans;
                   5399:   line-height:130%;
                   5400:   font-size:0.83em;
                   5401:   color:$font;
1.795     www      5402: }
                   5403: 
1.959     onken    5404: a:focus,
                   5405: a:focus img {
1.795     www      5406:   color: red;
                   5407: }
1.698     harmsja  5408: 
1.911     bisitz   5409: form, .inline {
                   5410:   display: inline;
1.795     www      5411: }
1.721     harmsja  5412: 
1.795     www      5413: .LC_right {
1.911     bisitz   5414:   text-align:right;
1.795     www      5415: }
                   5416: 
                   5417: .LC_middle {
1.911     bisitz   5418:   vertical-align:middle;
1.795     www      5419: }
1.721     harmsja  5420: 
1.1075.2.38  raeburn  5421: .LC_floatleft {
                   5422:   float: left;
                   5423: }
                   5424: 
                   5425: .LC_floatright {
                   5426:   float: right;
                   5427: }
                   5428: 
1.911     bisitz   5429: .LC_400Box {
                   5430:   width:400px;
                   5431: }
1.721     harmsja  5432: 
1.947     droeschl 5433: .LC_iframecontainer {
                   5434:     width: 98%;
                   5435:     margin: 0;
                   5436:     position: fixed;
                   5437:     top: 8.5em;
                   5438:     bottom: 0;
                   5439: }
                   5440: 
                   5441: .LC_iframecontainer iframe{
                   5442:     border: none;
                   5443:     width: 100%;
                   5444:     height: 100%;
                   5445: }
                   5446: 
1.778     bisitz   5447: .LC_filename {
                   5448:   font-family: $mono;
                   5449:   white-space:pre;
1.921     bisitz   5450:   font-size: 120%;
1.778     bisitz   5451: }
                   5452: 
                   5453: .LC_fileicon {
                   5454:   border: none;
                   5455:   height: 1.3em;
                   5456:   vertical-align: text-bottom;
                   5457:   margin-right: 0.3em;
                   5458:   text-decoration:none;
                   5459: }
                   5460: 
1.1008    www      5461: .LC_setting {
                   5462:   text-decoration:underline;
                   5463: }
                   5464: 
1.350     albertel 5465: .LC_error {
                   5466:   color: red;
                   5467: }
1.795     www      5468: 
1.1075.2.15  raeburn  5469: .LC_warning {
                   5470:   color: darkorange;
                   5471: }
                   5472: 
1.457     albertel 5473: .LC_diff_removed {
1.733     bisitz   5474:   color: red;
1.394     albertel 5475: }
1.532     albertel 5476: 
                   5477: .LC_info,
1.457     albertel 5478: .LC_success,
                   5479: .LC_diff_added {
1.350     albertel 5480:   color: green;
                   5481: }
1.795     www      5482: 
1.802     bisitz   5483: div.LC_confirm_box {
                   5484:   background-color: #FAFAFA;
                   5485:   border: 1px solid $lg_border_color;
                   5486:   margin-right: 0;
                   5487:   padding: 5px;
                   5488: }
                   5489: 
                   5490: div.LC_confirm_box .LC_error img,
                   5491: div.LC_confirm_box .LC_success img {
                   5492:   vertical-align: middle;
                   5493: }
                   5494: 
1.440     albertel 5495: .LC_icon {
1.771     droeschl 5496:   border: none;
1.790     droeschl 5497:   vertical-align: middle;
1.771     droeschl 5498: }
                   5499: 
1.543     albertel 5500: .LC_docs_spacer {
                   5501:   width: 25px;
                   5502:   height: 1px;
1.771     droeschl 5503:   border: none;
1.543     albertel 5504: }
1.346     albertel 5505: 
1.532     albertel 5506: .LC_internal_info {
1.735     bisitz   5507:   color: #999999;
1.532     albertel 5508: }
                   5509: 
1.794     www      5510: .LC_discussion {
1.1050    www      5511:   background: $data_table_dark;
1.911     bisitz   5512:   border: 1px solid black;
                   5513:   margin: 2px;
1.794     www      5514: }
                   5515: 
                   5516: .LC_disc_action_left {
1.1050    www      5517:   background: $sidebg;
1.911     bisitz   5518:   text-align: left;
1.1050    www      5519:   padding: 4px;
                   5520:   margin: 2px;
1.794     www      5521: }
                   5522: 
                   5523: .LC_disc_action_right {
1.1050    www      5524:   background: $sidebg;
1.911     bisitz   5525:   text-align: right;
1.1050    www      5526:   padding: 4px;
                   5527:   margin: 2px;
1.794     www      5528: }
                   5529: 
                   5530: .LC_disc_new_item {
1.911     bisitz   5531:   background: white;
                   5532:   border: 2px solid red;
1.1050    www      5533:   margin: 4px;
                   5534:   padding: 4px;
1.794     www      5535: }
                   5536: 
                   5537: .LC_disc_old_item {
1.911     bisitz   5538:   background: white;
1.1050    www      5539:   margin: 4px;
                   5540:   padding: 4px;
1.794     www      5541: }
                   5542: 
1.458     albertel 5543: table.LC_pastsubmission {
                   5544:   border: 1px solid black;
                   5545:   margin: 2px;
                   5546: }
                   5547: 
1.924     bisitz   5548: table#LC_menubuttons {
1.345     albertel 5549:   width: 100%;
                   5550:   background: $pgbg;
1.392     albertel 5551:   border: 2px;
1.402     albertel 5552:   border-collapse: separate;
1.803     bisitz   5553:   padding: 0;
1.345     albertel 5554: }
1.392     albertel 5555: 
1.801     tempelho 5556: table#LC_title_bar a {
                   5557:   color: $fontmenu;
                   5558: }
1.836     bisitz   5559: 
1.807     droeschl 5560: table#LC_title_bar {
1.819     tempelho 5561:   clear: both;
1.836     bisitz   5562:   display: none;
1.807     droeschl 5563: }
                   5564: 
1.795     www      5565: table#LC_title_bar,
1.933     droeschl 5566: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5567: table#LC_title_bar.LC_with_remote {
1.359     albertel 5568:   width: 100%;
1.392     albertel 5569:   border-color: $pgbg;
                   5570:   border-style: solid;
                   5571:   border-width: $border;
1.379     albertel 5572:   background: $pgbg;
1.801     tempelho 5573:   color: $fontmenu;
1.392     albertel 5574:   border-collapse: collapse;
1.803     bisitz   5575:   padding: 0;
1.819     tempelho 5576:   margin: 0;
1.359     albertel 5577: }
1.795     www      5578: 
1.933     droeschl 5579: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5580:     margin: 0;
                   5581:     padding: 0;
1.933     droeschl 5582:     position: relative;
                   5583:     list-style: none;
1.913     droeschl 5584: }
1.933     droeschl 5585: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5586:     display: inline;
                   5587: }
1.933     droeschl 5588: 
                   5589: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5590:     padding: 0;
1.933     droeschl 5591:     margin: 0;
                   5592:     float: left;
1.913     droeschl 5593: }
1.933     droeschl 5594: .LC_breadcrumb_tools_tools {
                   5595:     padding: 0;
                   5596:     margin: 0;
1.913     droeschl 5597:     float: right;
                   5598: }
                   5599: 
1.359     albertel 5600: table#LC_title_bar td {
                   5601:   background: $tabbg;
                   5602: }
1.795     www      5603: 
1.911     bisitz   5604: table#LC_menubuttons img {
1.803     bisitz   5605:   border: none;
1.346     albertel 5606: }
1.795     www      5607: 
1.842     droeschl 5608: .LC_breadcrumbs_component {
1.911     bisitz   5609:   float: right;
                   5610:   margin: 0 1em;
1.357     albertel 5611: }
1.842     droeschl 5612: .LC_breadcrumbs_component img {
1.911     bisitz   5613:   vertical-align: middle;
1.777     tempelho 5614: }
1.795     www      5615: 
1.383     albertel 5616: td.LC_table_cell_checkbox {
                   5617:   text-align: center;
                   5618: }
1.795     www      5619: 
                   5620: .LC_fontsize_small {
1.911     bisitz   5621:   font-size: 70%;
1.705     tempelho 5622: }
                   5623: 
1.844     bisitz   5624: #LC_breadcrumbs {
1.911     bisitz   5625:   clear:both;
                   5626:   background: $sidebg;
                   5627:   border-bottom: 1px solid $lg_border_color;
                   5628:   line-height: 2.5em;
1.933     droeschl 5629:   overflow: hidden;
1.911     bisitz   5630:   margin: 0;
                   5631:   padding: 0;
1.995     raeburn  5632:   text-align: left;
1.819     tempelho 5633: }
1.862     bisitz   5634: 
1.1075.2.16  raeburn  5635: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5636:   clear:both;
                   5637:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5638:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5639:   margin: 0 0 10px 0;
1.966     bisitz   5640:   padding: 3px;
1.995     raeburn  5641:   text-align: left;
1.822     bisitz   5642: }
                   5643: 
1.795     www      5644: .LC_fontsize_medium {
1.911     bisitz   5645:   font-size: 85%;
1.705     tempelho 5646: }
                   5647: 
1.795     www      5648: .LC_fontsize_large {
1.911     bisitz   5649:   font-size: 120%;
1.705     tempelho 5650: }
                   5651: 
1.346     albertel 5652: .LC_menubuttons_inline_text {
                   5653:   color: $font;
1.698     harmsja  5654:   font-size: 90%;
1.701     harmsja  5655:   padding-left:3px;
1.346     albertel 5656: }
                   5657: 
1.934     droeschl 5658: .LC_menubuttons_inline_text img{
                   5659:   vertical-align: middle;
                   5660: }
                   5661: 
1.1051    www      5662: li.LC_menubuttons_inline_text img {
1.951     onken    5663:   cursor:pointer;
1.1002    droeschl 5664:   text-decoration: none;
1.951     onken    5665: }
                   5666: 
1.526     www      5667: .LC_menubuttons_link {
                   5668:   text-decoration: none;
                   5669: }
1.795     www      5670: 
1.522     albertel 5671: .LC_menubuttons_category {
1.521     www      5672:   color: $font;
1.526     www      5673:   background: $pgbg;
1.521     www      5674:   font-size: larger;
                   5675:   font-weight: bold;
                   5676: }
                   5677: 
1.346     albertel 5678: td.LC_menubuttons_text {
1.911     bisitz   5679:   color: $font;
1.346     albertel 5680: }
1.706     harmsja  5681: 
1.346     albertel 5682: .LC_current_location {
                   5683:   background: $tabbg;
                   5684: }
1.795     www      5685: 
1.938     bisitz   5686: table.LC_data_table {
1.347     albertel 5687:   border: 1px solid #000000;
1.402     albertel 5688:   border-collapse: separate;
1.426     albertel 5689:   border-spacing: 1px;
1.610     albertel 5690:   background: $pgbg;
1.347     albertel 5691: }
1.795     www      5692: 
1.422     albertel 5693: .LC_data_table_dense {
                   5694:   font-size: small;
                   5695: }
1.795     www      5696: 
1.507     raeburn  5697: table.LC_nested_outer {
                   5698:   border: 1px solid #000000;
1.589     raeburn  5699:   border-collapse: collapse;
1.803     bisitz   5700:   border-spacing: 0;
1.507     raeburn  5701:   width: 100%;
                   5702: }
1.795     www      5703: 
1.879     raeburn  5704: table.LC_innerpickbox,
1.507     raeburn  5705: table.LC_nested {
1.803     bisitz   5706:   border: none;
1.589     raeburn  5707:   border-collapse: collapse;
1.803     bisitz   5708:   border-spacing: 0;
1.507     raeburn  5709:   width: 100%;
                   5710: }
1.795     www      5711: 
1.911     bisitz   5712: table.LC_data_table tr th,
                   5713: table.LC_calendar tr th,
1.879     raeburn  5714: table.LC_prior_tries tr th,
                   5715: table.LC_innerpickbox tr th {
1.349     albertel 5716:   font-weight: bold;
                   5717:   background-color: $data_table_head;
1.801     tempelho 5718:   color:$fontmenu;
1.701     harmsja  5719:   font-size:90%;
1.347     albertel 5720: }
1.795     www      5721: 
1.879     raeburn  5722: table.LC_innerpickbox tr th,
                   5723: table.LC_innerpickbox tr td {
                   5724:   vertical-align: top;
                   5725: }
                   5726: 
1.711     raeburn  5727: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5728:   background-color: #CCCCCC;
1.711     raeburn  5729:   font-weight: bold;
                   5730:   text-align: left;
                   5731: }
1.795     www      5732: 
1.912     bisitz   5733: table.LC_data_table tr.LC_odd_row > td {
                   5734:   background-color: $data_table_light;
                   5735:   padding: 2px;
                   5736:   vertical-align: top;
                   5737: }
                   5738: 
1.809     bisitz   5739: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5740:   background-color: $data_table_light;
1.912     bisitz   5741:   vertical-align: top;
                   5742: }
                   5743: 
                   5744: table.LC_data_table tr.LC_even_row > td {
                   5745:   background-color: $data_table_dark;
1.425     albertel 5746:   padding: 2px;
1.900     bisitz   5747:   vertical-align: top;
1.347     albertel 5748: }
1.795     www      5749: 
1.809     bisitz   5750: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5751:   background-color: $data_table_dark;
1.900     bisitz   5752:   vertical-align: top;
1.347     albertel 5753: }
1.795     www      5754: 
1.425     albertel 5755: table.LC_data_table tr.LC_data_table_highlight td {
                   5756:   background-color: $data_table_darker;
                   5757: }
1.795     www      5758: 
1.639     raeburn  5759: table.LC_data_table tr td.LC_leftcol_header {
                   5760:   background-color: $data_table_head;
                   5761:   font-weight: bold;
                   5762: }
1.795     www      5763: 
1.451     albertel 5764: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5765: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5766:   font-weight: bold;
                   5767:   font-style: italic;
                   5768:   text-align: center;
                   5769:   padding: 8px;
1.347     albertel 5770: }
1.795     www      5771: 
1.1075.2.30  raeburn  5772: table.LC_data_table tr.LC_empty_row td,
                   5773: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5774:   background-color: $sidebg;
                   5775: }
                   5776: 
                   5777: table.LC_nested tr.LC_empty_row td {
                   5778:   background-color: #FFFFFF;
                   5779: }
                   5780: 
1.890     droeschl 5781: table.LC_caption {
                   5782: }
                   5783: 
1.507     raeburn  5784: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5785:   padding: 4ex
                   5786: }
1.795     www      5787: 
1.507     raeburn  5788: table.LC_nested_outer tr th {
                   5789:   font-weight: bold;
1.801     tempelho 5790:   color:$fontmenu;
1.507     raeburn  5791:   background-color: $data_table_head;
1.701     harmsja  5792:   font-size: small;
1.507     raeburn  5793:   border-bottom: 1px solid #000000;
                   5794: }
1.795     www      5795: 
1.507     raeburn  5796: table.LC_nested_outer tr td.LC_subheader {
                   5797:   background-color: $data_table_head;
                   5798:   font-weight: bold;
                   5799:   font-size: small;
                   5800:   border-bottom: 1px solid #000000;
                   5801:   text-align: right;
1.451     albertel 5802: }
1.795     www      5803: 
1.507     raeburn  5804: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5805:   background-color: #CCCCCC;
1.451     albertel 5806:   font-weight: bold;
                   5807:   font-size: small;
1.507     raeburn  5808:   text-align: center;
                   5809: }
1.795     www      5810: 
1.589     raeburn  5811: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5812: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5813:   text-align: left;
1.451     albertel 5814: }
1.795     www      5815: 
1.507     raeburn  5816: table.LC_nested td {
1.735     bisitz   5817:   background-color: #FFFFFF;
1.451     albertel 5818:   font-size: small;
1.507     raeburn  5819: }
1.795     www      5820: 
1.507     raeburn  5821: table.LC_nested_outer tr th.LC_right_item,
                   5822: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5823: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5824: table.LC_nested tr td.LC_right_item {
1.451     albertel 5825:   text-align: right;
                   5826: }
                   5827: 
1.507     raeburn  5828: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5829:   background-color: #EEEEEE;
1.451     albertel 5830: }
                   5831: 
1.473     raeburn  5832: table.LC_createuser {
                   5833: }
                   5834: 
                   5835: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5836:   font-size: small;
1.473     raeburn  5837: }
                   5838: 
                   5839: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5840:   background-color: #CCCCCC;
1.473     raeburn  5841:   font-weight: bold;
                   5842:   text-align: center;
                   5843: }
                   5844: 
1.349     albertel 5845: table.LC_calendar {
                   5846:   border: 1px solid #000000;
                   5847:   border-collapse: collapse;
1.917     raeburn  5848:   width: 98%;
1.349     albertel 5849: }
1.795     www      5850: 
1.349     albertel 5851: table.LC_calendar_pickdate {
                   5852:   font-size: xx-small;
                   5853: }
1.795     www      5854: 
1.349     albertel 5855: table.LC_calendar tr td {
                   5856:   border: 1px solid #000000;
                   5857:   vertical-align: top;
1.917     raeburn  5858:   width: 14%;
1.349     albertel 5859: }
1.795     www      5860: 
1.349     albertel 5861: table.LC_calendar tr td.LC_calendar_day_empty {
                   5862:   background-color: $data_table_dark;
                   5863: }
1.795     www      5864: 
1.779     bisitz   5865: table.LC_calendar tr td.LC_calendar_day_current {
                   5866:   background-color: $data_table_highlight;
1.777     tempelho 5867: }
1.795     www      5868: 
1.938     bisitz   5869: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5870:   background-color: $mail_new;
                   5871: }
1.795     www      5872: 
1.938     bisitz   5873: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5874:   background-color: $mail_new_hover;
                   5875: }
1.795     www      5876: 
1.938     bisitz   5877: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5878:   background-color: $mail_read;
                   5879: }
1.795     www      5880: 
1.938     bisitz   5881: /*
                   5882: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5883:   background-color: $mail_read_hover;
                   5884: }
1.938     bisitz   5885: */
1.795     www      5886: 
1.938     bisitz   5887: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5888:   background-color: $mail_replied;
                   5889: }
1.795     www      5890: 
1.938     bisitz   5891: /*
                   5892: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5893:   background-color: $mail_replied_hover;
                   5894: }
1.938     bisitz   5895: */
1.795     www      5896: 
1.938     bisitz   5897: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5898:   background-color: $mail_other;
                   5899: }
1.795     www      5900: 
1.938     bisitz   5901: /*
                   5902: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5903:   background-color: $mail_other_hover;
                   5904: }
1.938     bisitz   5905: */
1.494     raeburn  5906: 
1.777     tempelho 5907: table.LC_data_table tr > td.LC_browser_file,
                   5908: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5909:   background: #AAEE77;
1.389     albertel 5910: }
1.795     www      5911: 
1.777     tempelho 5912: table.LC_data_table tr > td.LC_browser_file_locked,
                   5913: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5914:   background: #FFAA99;
1.387     albertel 5915: }
1.795     www      5916: 
1.777     tempelho 5917: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5918:   background: #888888;
1.779     bisitz   5919: }
1.795     www      5920: 
1.777     tempelho 5921: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5922: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5923:   background: #F8F866;
1.777     tempelho 5924: }
1.795     www      5925: 
1.696     bisitz   5926: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5927:   background: #E0E8FF;
1.387     albertel 5928: }
1.696     bisitz   5929: 
1.707     bisitz   5930: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5931:   /* background: #77FF77; */
1.707     bisitz   5932: }
1.795     www      5933: 
1.707     bisitz   5934: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5935:   border-right: 8px solid #FFFF77;
1.707     bisitz   5936: }
1.795     www      5937: 
1.707     bisitz   5938: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5939:   border-right: 8px solid #FFAA77;
1.707     bisitz   5940: }
1.795     www      5941: 
1.707     bisitz   5942: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5943:   border-right: 8px solid #FF7777;
1.707     bisitz   5944: }
1.795     www      5945: 
1.707     bisitz   5946: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5947:   border-right: 8px solid #AAFF77;
1.707     bisitz   5948: }
1.795     www      5949: 
1.707     bisitz   5950: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5951:   border-right: 8px solid #11CC55;
1.707     bisitz   5952: }
                   5953: 
1.388     albertel 5954: span.LC_current_location {
1.701     harmsja  5955:   font-size:larger;
1.388     albertel 5956:   background: $pgbg;
                   5957: }
1.387     albertel 5958: 
1.1029    www      5959: span.LC_current_nav_location {
                   5960:   font-weight:bold;
                   5961:   background: $sidebg;
                   5962: }
                   5963: 
1.395     albertel 5964: span.LC_parm_menu_item {
                   5965:   font-size: larger;
                   5966: }
1.795     www      5967: 
1.395     albertel 5968: span.LC_parm_scope_all {
                   5969:   color: red;
                   5970: }
1.795     www      5971: 
1.395     albertel 5972: span.LC_parm_scope_folder {
                   5973:   color: green;
                   5974: }
1.795     www      5975: 
1.395     albertel 5976: span.LC_parm_scope_resource {
                   5977:   color: orange;
                   5978: }
1.795     www      5979: 
1.395     albertel 5980: span.LC_parm_part {
                   5981:   color: blue;
                   5982: }
1.795     www      5983: 
1.911     bisitz   5984: span.LC_parm_folder,
                   5985: span.LC_parm_symb {
1.395     albertel 5986:   font-size: x-small;
                   5987:   font-family: $mono;
                   5988:   color: #AAAAAA;
                   5989: }
                   5990: 
1.977     bisitz   5991: ul.LC_parm_parmlist li {
                   5992:   display: inline-block;
                   5993:   padding: 0.3em 0.8em;
                   5994:   vertical-align: top;
                   5995:   width: 150px;
                   5996:   border-top:1px solid $lg_border_color;
                   5997: }
                   5998: 
1.795     www      5999: td.LC_parm_overview_level_menu,
                   6000: td.LC_parm_overview_map_menu,
                   6001: td.LC_parm_overview_parm_selectors,
                   6002: td.LC_parm_overview_restrictions  {
1.396     albertel 6003:   border: 1px solid black;
                   6004:   border-collapse: collapse;
                   6005: }
1.795     www      6006: 
1.396     albertel 6007: table.LC_parm_overview_restrictions td {
                   6008:   border-width: 1px 4px 1px 4px;
                   6009:   border-style: solid;
                   6010:   border-color: $pgbg;
                   6011:   text-align: center;
                   6012: }
1.795     www      6013: 
1.396     albertel 6014: table.LC_parm_overview_restrictions th {
                   6015:   background: $tabbg;
                   6016:   border-width: 1px 4px 1px 4px;
                   6017:   border-style: solid;
                   6018:   border-color: $pgbg;
                   6019: }
1.795     www      6020: 
1.398     albertel 6021: table#LC_helpmenu {
1.803     bisitz   6022:   border: none;
1.398     albertel 6023:   height: 55px;
1.803     bisitz   6024:   border-spacing: 0;
1.398     albertel 6025: }
                   6026: 
                   6027: table#LC_helpmenu fieldset legend {
                   6028:   font-size: larger;
                   6029: }
1.795     www      6030: 
1.397     albertel 6031: table#LC_helpmenu_links {
                   6032:   width: 100%;
                   6033:   border: 1px solid black;
                   6034:   background: $pgbg;
1.803     bisitz   6035:   padding: 0;
1.397     albertel 6036:   border-spacing: 1px;
                   6037: }
1.795     www      6038: 
1.397     albertel 6039: table#LC_helpmenu_links tr td {
                   6040:   padding: 1px;
                   6041:   background: $tabbg;
1.399     albertel 6042:   text-align: center;
                   6043:   font-weight: bold;
1.397     albertel 6044: }
1.396     albertel 6045: 
1.795     www      6046: table#LC_helpmenu_links a:link,
                   6047: table#LC_helpmenu_links a:visited,
1.397     albertel 6048: table#LC_helpmenu_links a:active {
                   6049:   text-decoration: none;
                   6050:   color: $font;
                   6051: }
1.795     www      6052: 
1.397     albertel 6053: table#LC_helpmenu_links a:hover {
                   6054:   text-decoration: underline;
                   6055:   color: $vlink;
                   6056: }
1.396     albertel 6057: 
1.417     albertel 6058: .LC_chrt_popup_exists {
                   6059:   border: 1px solid #339933;
                   6060:   margin: -1px;
                   6061: }
1.795     www      6062: 
1.417     albertel 6063: .LC_chrt_popup_up {
                   6064:   border: 1px solid yellow;
                   6065:   margin: -1px;
                   6066: }
1.795     www      6067: 
1.417     albertel 6068: .LC_chrt_popup {
                   6069:   border: 1px solid #8888FF;
                   6070:   background: #CCCCFF;
                   6071: }
1.795     www      6072: 
1.421     albertel 6073: table.LC_pick_box {
                   6074:   border-collapse: separate;
                   6075:   background: white;
                   6076:   border: 1px solid black;
                   6077:   border-spacing: 1px;
                   6078: }
1.795     www      6079: 
1.421     albertel 6080: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6081:   background: $sidebg;
1.421     albertel 6082:   font-weight: bold;
1.900     bisitz   6083:   text-align: left;
1.740     bisitz   6084:   vertical-align: top;
1.421     albertel 6085:   width: 184px;
                   6086:   padding: 8px;
                   6087: }
1.795     www      6088: 
1.579     raeburn  6089: table.LC_pick_box td.LC_pick_box_value {
                   6090:   text-align: left;
                   6091:   padding: 8px;
                   6092: }
1.795     www      6093: 
1.579     raeburn  6094: table.LC_pick_box td.LC_pick_box_select {
                   6095:   text-align: left;
                   6096:   padding: 8px;
                   6097: }
1.795     www      6098: 
1.424     albertel 6099: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6100:   padding: 0;
1.421     albertel 6101:   height: 1px;
                   6102:   background: black;
                   6103: }
1.795     www      6104: 
1.421     albertel 6105: table.LC_pick_box td.LC_pick_box_submit {
                   6106:   text-align: right;
                   6107: }
1.795     www      6108: 
1.579     raeburn  6109: table.LC_pick_box td.LC_evenrow_value {
                   6110:   text-align: left;
                   6111:   padding: 8px;
                   6112:   background-color: $data_table_light;
                   6113: }
1.795     www      6114: 
1.579     raeburn  6115: table.LC_pick_box td.LC_oddrow_value {
                   6116:   text-align: left;
                   6117:   padding: 8px;
                   6118:   background-color: $data_table_light;
                   6119: }
1.795     www      6120: 
1.579     raeburn  6121: span.LC_helpform_receipt_cat {
                   6122:   font-weight: bold;
                   6123: }
1.795     www      6124: 
1.424     albertel 6125: table.LC_group_priv_box {
                   6126:   background: white;
                   6127:   border: 1px solid black;
                   6128:   border-spacing: 1px;
                   6129: }
1.795     www      6130: 
1.424     albertel 6131: table.LC_group_priv_box td.LC_pick_box_title {
                   6132:   background: $tabbg;
                   6133:   font-weight: bold;
                   6134:   text-align: right;
                   6135:   width: 184px;
                   6136: }
1.795     www      6137: 
1.424     albertel 6138: table.LC_group_priv_box td.LC_groups_fixed {
                   6139:   background: $data_table_light;
                   6140:   text-align: center;
                   6141: }
1.795     www      6142: 
1.424     albertel 6143: table.LC_group_priv_box td.LC_groups_optional {
                   6144:   background: $data_table_dark;
                   6145:   text-align: center;
                   6146: }
1.795     www      6147: 
1.424     albertel 6148: table.LC_group_priv_box td.LC_groups_functionality {
                   6149:   background: $data_table_darker;
                   6150:   text-align: center;
                   6151:   font-weight: bold;
                   6152: }
1.795     www      6153: 
1.424     albertel 6154: table.LC_group_priv td {
                   6155:   text-align: left;
1.803     bisitz   6156:   padding: 0;
1.424     albertel 6157: }
                   6158: 
                   6159: .LC_navbuttons {
                   6160:   margin: 2ex 0ex 2ex 0ex;
                   6161: }
1.795     www      6162: 
1.423     albertel 6163: .LC_topic_bar {
                   6164:   font-weight: bold;
                   6165:   background: $tabbg;
1.918     wenzelju 6166:   margin: 1em 0em 1em 2em;
1.805     bisitz   6167:   padding: 3px;
1.918     wenzelju 6168:   font-size: 1.2em;
1.423     albertel 6169: }
1.795     www      6170: 
1.423     albertel 6171: .LC_topic_bar span {
1.918     wenzelju 6172:   left: 0.5em;
                   6173:   position: absolute;
1.423     albertel 6174:   vertical-align: middle;
1.918     wenzelju 6175:   font-size: 1.2em;
1.423     albertel 6176: }
1.795     www      6177: 
1.423     albertel 6178: table.LC_course_group_status {
                   6179:   margin: 20px;
                   6180: }
1.795     www      6181: 
1.423     albertel 6182: table.LC_status_selector td {
                   6183:   vertical-align: top;
                   6184:   text-align: center;
1.424     albertel 6185:   padding: 4px;
                   6186: }
1.795     www      6187: 
1.599     albertel 6188: div.LC_feedback_link {
1.616     albertel 6189:   clear: both;
1.829     kalberla 6190:   background: $sidebg;
1.779     bisitz   6191:   width: 100%;
1.829     kalberla 6192:   padding-bottom: 10px;
                   6193:   border: 1px $tabbg solid;
1.833     kalberla 6194:   height: 22px;
                   6195:   line-height: 22px;
                   6196:   padding-top: 5px;
                   6197: }
                   6198: 
                   6199: div.LC_feedback_link img {
                   6200:   height: 22px;
1.867     kalberla 6201:   vertical-align:middle;
1.829     kalberla 6202: }
                   6203: 
1.911     bisitz   6204: div.LC_feedback_link a {
1.829     kalberla 6205:   text-decoration: none;
1.489     raeburn  6206: }
1.795     www      6207: 
1.867     kalberla 6208: div.LC_comblock {
1.911     bisitz   6209:   display:inline;
1.867     kalberla 6210:   color:$font;
                   6211:   font-size:90%;
                   6212: }
                   6213: 
                   6214: div.LC_feedback_link div.LC_comblock {
                   6215:   padding-left:5px;
                   6216: }
                   6217: 
                   6218: div.LC_feedback_link div.LC_comblock a {
                   6219:   color:$font;
                   6220: }
                   6221: 
1.489     raeburn  6222: span.LC_feedback_link {
1.858     bisitz   6223:   /* background: $feedback_link_bg; */
1.599     albertel 6224:   font-size: larger;
                   6225: }
1.795     www      6226: 
1.599     albertel 6227: span.LC_message_link {
1.858     bisitz   6228:   /* background: $feedback_link_bg; */
1.599     albertel 6229:   font-size: larger;
                   6230:   position: absolute;
                   6231:   right: 1em;
1.489     raeburn  6232: }
1.421     albertel 6233: 
1.515     albertel 6234: table.LC_prior_tries {
1.524     albertel 6235:   border: 1px solid #000000;
                   6236:   border-collapse: separate;
                   6237:   border-spacing: 1px;
1.515     albertel 6238: }
1.523     albertel 6239: 
1.515     albertel 6240: table.LC_prior_tries td {
1.524     albertel 6241:   padding: 2px;
1.515     albertel 6242: }
1.523     albertel 6243: 
                   6244: .LC_answer_correct {
1.795     www      6245:   background: lightgreen;
                   6246:   color: darkgreen;
                   6247:   padding: 6px;
1.523     albertel 6248: }
1.795     www      6249: 
1.523     albertel 6250: .LC_answer_charged_try {
1.797     www      6251:   background: #FFAAAA;
1.795     www      6252:   color: darkred;
                   6253:   padding: 6px;
1.523     albertel 6254: }
1.795     www      6255: 
1.779     bisitz   6256: .LC_answer_not_charged_try,
1.523     albertel 6257: .LC_answer_no_grade,
                   6258: .LC_answer_late {
1.795     www      6259:   background: lightyellow;
1.523     albertel 6260:   color: black;
1.795     www      6261:   padding: 6px;
1.523     albertel 6262: }
1.795     www      6263: 
1.523     albertel 6264: .LC_answer_previous {
1.795     www      6265:   background: lightblue;
                   6266:   color: darkblue;
                   6267:   padding: 6px;
1.523     albertel 6268: }
1.795     www      6269: 
1.779     bisitz   6270: .LC_answer_no_message {
1.777     tempelho 6271:   background: #FFFFFF;
                   6272:   color: black;
1.795     www      6273:   padding: 6px;
1.779     bisitz   6274: }
1.795     www      6275: 
1.779     bisitz   6276: .LC_answer_unknown {
                   6277:   background: orange;
                   6278:   color: black;
1.795     www      6279:   padding: 6px;
1.777     tempelho 6280: }
1.795     www      6281: 
1.529     albertel 6282: span.LC_prior_numerical,
                   6283: span.LC_prior_string,
                   6284: span.LC_prior_custom,
                   6285: span.LC_prior_reaction,
                   6286: span.LC_prior_math {
1.925     bisitz   6287:   font-family: $mono;
1.523     albertel 6288:   white-space: pre;
                   6289: }
                   6290: 
1.525     albertel 6291: span.LC_prior_string {
1.925     bisitz   6292:   font-family: $mono;
1.525     albertel 6293:   white-space: pre;
                   6294: }
                   6295: 
1.523     albertel 6296: table.LC_prior_option {
                   6297:   width: 100%;
                   6298:   border-collapse: collapse;
                   6299: }
1.795     www      6300: 
1.911     bisitz   6301: table.LC_prior_rank,
1.795     www      6302: table.LC_prior_match {
1.528     albertel 6303:   border-collapse: collapse;
                   6304: }
1.795     www      6305: 
1.528     albertel 6306: table.LC_prior_option tr td,
                   6307: table.LC_prior_rank tr td,
                   6308: table.LC_prior_match tr td {
1.524     albertel 6309:   border: 1px solid #000000;
1.515     albertel 6310: }
                   6311: 
1.855     bisitz   6312: .LC_nobreak {
1.544     albertel 6313:   white-space: nowrap;
1.519     raeburn  6314: }
                   6315: 
1.576     raeburn  6316: span.LC_cusr_emph {
                   6317:   font-style: italic;
                   6318: }
                   6319: 
1.633     raeburn  6320: span.LC_cusr_subheading {
                   6321:   font-weight: normal;
                   6322:   font-size: 85%;
                   6323: }
                   6324: 
1.861     bisitz   6325: div.LC_docs_entry_move {
1.859     bisitz   6326:   border: 1px solid #BBBBBB;
1.545     albertel 6327:   background: #DDDDDD;
1.861     bisitz   6328:   width: 22px;
1.859     bisitz   6329:   padding: 1px;
                   6330:   margin: 0;
1.545     albertel 6331: }
                   6332: 
1.861     bisitz   6333: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6334: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6335:   font-size: x-small;
                   6336: }
1.795     www      6337: 
1.861     bisitz   6338: .LC_docs_entry_parameter {
                   6339:   white-space: nowrap;
                   6340: }
                   6341: 
1.544     albertel 6342: .LC_docs_copy {
1.545     albertel 6343:   color: #000099;
1.544     albertel 6344: }
1.795     www      6345: 
1.544     albertel 6346: .LC_docs_cut {
1.545     albertel 6347:   color: #550044;
1.544     albertel 6348: }
1.795     www      6349: 
1.544     albertel 6350: .LC_docs_rename {
1.545     albertel 6351:   color: #009900;
1.544     albertel 6352: }
1.795     www      6353: 
1.544     albertel 6354: .LC_docs_remove {
1.545     albertel 6355:   color: #990000;
                   6356: }
                   6357: 
1.547     albertel 6358: .LC_docs_reinit_warn,
                   6359: .LC_docs_ext_edit {
                   6360:   font-size: x-small;
                   6361: }
                   6362: 
1.545     albertel 6363: table.LC_docs_adddocs td,
                   6364: table.LC_docs_adddocs th {
                   6365:   border: 1px solid #BBBBBB;
                   6366:   padding: 4px;
                   6367:   background: #DDDDDD;
1.543     albertel 6368: }
                   6369: 
1.584     albertel 6370: table.LC_sty_begin {
                   6371:   background: #BBFFBB;
                   6372: }
1.795     www      6373: 
1.584     albertel 6374: table.LC_sty_end {
                   6375:   background: #FFBBBB;
                   6376: }
                   6377: 
1.589     raeburn  6378: table.LC_double_column {
1.803     bisitz   6379:   border-width: 0;
1.589     raeburn  6380:   border-collapse: collapse;
                   6381:   width: 100%;
                   6382:   padding: 2px;
                   6383: }
                   6384: 
                   6385: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6386:   top: 2px;
1.589     raeburn  6387:   left: 2px;
                   6388:   width: 47%;
                   6389:   vertical-align: top;
                   6390: }
                   6391: 
                   6392: table.LC_double_column tr td.LC_right_col {
                   6393:   top: 2px;
1.779     bisitz   6394:   right: 2px;
1.589     raeburn  6395:   width: 47%;
                   6396:   vertical-align: top;
                   6397: }
                   6398: 
1.591     raeburn  6399: div.LC_left_float {
                   6400:   float: left;
                   6401:   padding-right: 5%;
1.597     albertel 6402:   padding-bottom: 4px;
1.591     raeburn  6403: }
                   6404: 
                   6405: div.LC_clear_float_header {
1.597     albertel 6406:   padding-bottom: 2px;
1.591     raeburn  6407: }
                   6408: 
                   6409: div.LC_clear_float_footer {
1.597     albertel 6410:   padding-top: 10px;
1.591     raeburn  6411:   clear: both;
                   6412: }
                   6413: 
1.597     albertel 6414: div.LC_grade_show_user {
1.941     bisitz   6415: /*  border-left: 5px solid $sidebg; */
                   6416:   border-top: 5px solid #000000;
                   6417:   margin: 50px 0 0 0;
1.936     bisitz   6418:   padding: 15px 0 5px 10px;
1.597     albertel 6419: }
1.795     www      6420: 
1.936     bisitz   6421: div.LC_grade_show_user_odd_row {
1.941     bisitz   6422: /*  border-left: 5px solid #000000; */
                   6423: }
                   6424: 
                   6425: div.LC_grade_show_user div.LC_Box {
                   6426:   margin-right: 50px;
1.597     albertel 6427: }
                   6428: 
                   6429: div.LC_grade_submissions,
                   6430: div.LC_grade_message_center,
1.936     bisitz   6431: div.LC_grade_info_links {
1.597     albertel 6432:   margin: 5px;
                   6433:   width: 99%;
                   6434:   background: #FFFFFF;
                   6435: }
1.795     www      6436: 
1.597     albertel 6437: div.LC_grade_submissions_header,
1.936     bisitz   6438: div.LC_grade_message_center_header {
1.705     tempelho 6439:   font-weight: bold;
                   6440:   font-size: large;
1.597     albertel 6441: }
1.795     www      6442: 
1.597     albertel 6443: div.LC_grade_submissions_body,
1.936     bisitz   6444: div.LC_grade_message_center_body {
1.597     albertel 6445:   border: 1px solid black;
                   6446:   width: 99%;
                   6447:   background: #FFFFFF;
                   6448: }
1.795     www      6449: 
1.613     albertel 6450: table.LC_scantron_action {
                   6451:   width: 100%;
                   6452: }
1.795     www      6453: 
1.613     albertel 6454: table.LC_scantron_action tr th {
1.698     harmsja  6455:   font-weight:bold;
                   6456:   font-style:normal;
1.613     albertel 6457: }
1.795     www      6458: 
1.779     bisitz   6459: .LC_edit_problem_header,
1.614     albertel 6460: div.LC_edit_problem_footer {
1.705     tempelho 6461:   font-weight: normal;
                   6462:   font-size:  medium;
1.602     albertel 6463:   margin: 2px;
1.1060    bisitz   6464:   background-color: $sidebg;
1.600     albertel 6465: }
1.795     www      6466: 
1.600     albertel 6467: div.LC_edit_problem_header,
1.602     albertel 6468: div.LC_edit_problem_header div,
1.614     albertel 6469: div.LC_edit_problem_footer,
                   6470: div.LC_edit_problem_footer div,
1.602     albertel 6471: div.LC_edit_problem_editxml_header,
                   6472: div.LC_edit_problem_editxml_header div {
1.600     albertel 6473:   margin-top: 5px;
                   6474: }
1.795     www      6475: 
1.600     albertel 6476: div.LC_edit_problem_header_title {
1.705     tempelho 6477:   font-weight: bold;
                   6478:   font-size: larger;
1.602     albertel 6479:   background: $tabbg;
                   6480:   padding: 3px;
1.1060    bisitz   6481:   margin: 0 0 5px 0;
1.602     albertel 6482: }
1.795     www      6483: 
1.602     albertel 6484: table.LC_edit_problem_header_title {
                   6485:   width: 100%;
1.600     albertel 6486:   background: $tabbg;
1.602     albertel 6487: }
                   6488: 
                   6489: div.LC_edit_problem_discards {
                   6490:   float: left;
                   6491:   padding-bottom: 5px;
                   6492: }
1.795     www      6493: 
1.602     albertel 6494: div.LC_edit_problem_saves {
                   6495:   float: right;
                   6496:   padding-bottom: 5px;
1.600     albertel 6497: }
1.795     www      6498: 
1.1075.2.34  raeburn  6499: .LC_edit_opt {
                   6500:   padding-left: 1em;
                   6501:   white-space: nowrap;
                   6502: }
                   6503: 
1.1075.2.57  raeburn  6504: .LC_edit_problem_latexhelper{
                   6505:     text-align: right;
                   6506: }
                   6507: 
                   6508: #LC_edit_problem_colorful div{
                   6509:     margin-left: 40px;
                   6510: }
                   6511: 
1.911     bisitz   6512: img.stift {
1.803     bisitz   6513:   border-width: 0;
                   6514:   vertical-align: middle;
1.677     riegler  6515: }
1.680     riegler  6516: 
1.923     bisitz   6517: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6518:   vertical-align: top;
1.777     tempelho 6519: }
1.795     www      6520: 
1.716     raeburn  6521: div.LC_createcourse {
1.911     bisitz   6522:   margin: 10px 10px 10px 10px;
1.716     raeburn  6523: }
                   6524: 
1.917     raeburn  6525: .LC_dccid {
1.1075.2.38  raeburn  6526:   float: right;
1.917     raeburn  6527:   margin: 0.2em 0 0 0;
                   6528:   padding: 0;
                   6529:   font-size: 90%;
                   6530:   display:none;
                   6531: }
                   6532: 
1.897     wenzelju 6533: ol.LC_primary_menu a:hover,
1.721     harmsja  6534: ol#LC_MenuBreadcrumbs a:hover,
                   6535: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6536: ul#LC_secondary_menu a:hover,
1.721     harmsja  6537: .LC_FormSectionClearButton input:hover
1.795     www      6538: ul.LC_TabContent   li:hover a {
1.952     onken    6539:   color:$button_hover;
1.911     bisitz   6540:   text-decoration:none;
1.693     droeschl 6541: }
                   6542: 
1.779     bisitz   6543: h1 {
1.911     bisitz   6544:   padding: 0;
                   6545:   line-height:130%;
1.693     droeschl 6546: }
1.698     harmsja  6547: 
1.911     bisitz   6548: h2,
                   6549: h3,
                   6550: h4,
                   6551: h5,
                   6552: h6 {
                   6553:   margin: 5px 0 5px 0;
                   6554:   padding: 0;
                   6555:   line-height:130%;
1.693     droeschl 6556: }
1.795     www      6557: 
                   6558: .LC_hcell {
1.911     bisitz   6559:   padding:3px 15px 3px 15px;
                   6560:   margin: 0;
                   6561:   background-color:$tabbg;
                   6562:   color:$fontmenu;
                   6563:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6564: }
1.795     www      6565: 
1.840     bisitz   6566: .LC_Box > .LC_hcell {
1.911     bisitz   6567:   margin: 0 -10px 10px -10px;
1.835     bisitz   6568: }
                   6569: 
1.721     harmsja  6570: .LC_noBorder {
1.911     bisitz   6571:   border: 0;
1.698     harmsja  6572: }
1.693     droeschl 6573: 
1.721     harmsja  6574: .LC_FormSectionClearButton input {
1.911     bisitz   6575:   background-color:transparent;
                   6576:   border: none;
                   6577:   cursor:pointer;
                   6578:   text-decoration:underline;
1.693     droeschl 6579: }
1.763     bisitz   6580: 
                   6581: .LC_help_open_topic {
1.911     bisitz   6582:   color: #FFFFFF;
                   6583:   background-color: #EEEEFF;
                   6584:   margin: 1px;
                   6585:   padding: 4px;
                   6586:   border: 1px solid #000033;
                   6587:   white-space: nowrap;
                   6588:   /* vertical-align: middle; */
1.759     neumanie 6589: }
1.693     droeschl 6590: 
1.911     bisitz   6591: dl,
                   6592: ul,
                   6593: div,
                   6594: fieldset {
                   6595:   margin: 10px 10px 10px 0;
                   6596:   /* overflow: hidden; */
1.693     droeschl 6597: }
1.795     www      6598: 
1.838     bisitz   6599: fieldset > legend {
1.911     bisitz   6600:   font-weight: bold;
                   6601:   padding: 0 5px 0 5px;
1.838     bisitz   6602: }
                   6603: 
1.813     bisitz   6604: #LC_nav_bar {
1.911     bisitz   6605:   float: left;
1.995     raeburn  6606:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6607:   margin: 0 0 2px 0;
1.807     droeschl 6608: }
                   6609: 
1.916     droeschl 6610: #LC_realm {
                   6611:   margin: 0.2em 0 0 0;
                   6612:   padding: 0;
                   6613:   font-weight: bold;
                   6614:   text-align: center;
1.995     raeburn  6615:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6616: }
                   6617: 
1.911     bisitz   6618: #LC_nav_bar em {
                   6619:   font-weight: bold;
                   6620:   font-style: normal;
1.807     droeschl 6621: }
                   6622: 
1.897     wenzelju 6623: ol.LC_primary_menu {
1.934     droeschl 6624:   margin: 0;
1.1075.2.2  raeburn  6625:   padding: 0;
1.995     raeburn  6626:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6627: }
                   6628: 
1.852     droeschl 6629: ol#LC_PathBreadcrumbs {
1.911     bisitz   6630:   margin: 0;
1.693     droeschl 6631: }
                   6632: 
1.897     wenzelju 6633: ol.LC_primary_menu li {
1.1075.2.2  raeburn  6634:   color: RGB(80, 80, 80);
                   6635:   vertical-align: middle;
                   6636:   text-align: left;
                   6637:   list-style: none;
                   6638:   float: left;
                   6639: }
                   6640: 
                   6641: ol.LC_primary_menu li a {
                   6642:   display: block;
                   6643:   margin: 0;
                   6644:   padding: 0 5px 0 10px;
                   6645:   text-decoration: none;
                   6646: }
                   6647: 
                   6648: ol.LC_primary_menu li ul {
                   6649:   display: none;
                   6650:   width: 10em;
                   6651:   background-color: $data_table_light;
                   6652: }
                   6653: 
                   6654: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6655:   display: block;
                   6656:   position: absolute;
                   6657:   margin: 0;
                   6658:   padding: 0;
1.1075.2.5  raeburn  6659:   z-index: 2;
1.1075.2.2  raeburn  6660: }
                   6661: 
                   6662: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6663:   font-size: 90%;
1.911     bisitz   6664:   vertical-align: top;
1.1075.2.2  raeburn  6665:   float: none;
1.1075.2.5  raeburn  6666:   border-left: 1px solid black;
                   6667:   border-right: 1px solid black;
1.1075.2.2  raeburn  6668: }
                   6669: 
                   6670: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1075.2.5  raeburn  6671:   background-color:$data_table_light;
1.1075.2.2  raeburn  6672: }
                   6673: 
                   6674: ol.LC_primary_menu li li a:hover {
                   6675:    color:$button_hover;
                   6676:    background-color:$data_table_dark;
1.693     droeschl 6677: }
                   6678: 
1.897     wenzelju 6679: ol.LC_primary_menu li img {
1.911     bisitz   6680:   vertical-align: bottom;
1.934     droeschl 6681:   height: 1.1em;
1.1075.2.3  raeburn  6682:   margin: 0.2em 0 0 0;
1.693     droeschl 6683: }
                   6684: 
1.897     wenzelju 6685: ol.LC_primary_menu a {
1.911     bisitz   6686:   color: RGB(80, 80, 80);
                   6687:   text-decoration: none;
1.693     droeschl 6688: }
1.795     www      6689: 
1.949     droeschl 6690: ol.LC_primary_menu a.LC_new_message {
                   6691:   font-weight:bold;
                   6692:   color: darkred;
                   6693: }
                   6694: 
1.975     raeburn  6695: ol.LC_docs_parameters {
                   6696:   margin-left: 0;
                   6697:   padding: 0;
                   6698:   list-style: none;
                   6699: }
                   6700: 
                   6701: ol.LC_docs_parameters li {
                   6702:   margin: 0;
                   6703:   padding-right: 20px;
                   6704:   display: inline;
                   6705: }
                   6706: 
1.976     raeburn  6707: ol.LC_docs_parameters li:before {
                   6708:   content: "\\002022 \\0020";
                   6709: }
                   6710: 
                   6711: li.LC_docs_parameters_title {
                   6712:   font-weight: bold;
                   6713: }
                   6714: 
                   6715: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6716:   content: "";
                   6717: }
                   6718: 
1.897     wenzelju 6719: ul#LC_secondary_menu {
1.1075.2.23  raeburn  6720:   clear: right;
1.911     bisitz   6721:   color: $fontmenu;
                   6722:   background: $tabbg;
                   6723:   list-style: none;
                   6724:   padding: 0;
                   6725:   margin: 0;
                   6726:   width: 100%;
1.995     raeburn  6727:   text-align: left;
1.1075.2.4  raeburn  6728:   float: left;
1.808     droeschl 6729: }
                   6730: 
1.897     wenzelju 6731: ul#LC_secondary_menu li {
1.911     bisitz   6732:   font-weight: bold;
                   6733:   line-height: 1.8em;
                   6734:   border-right: 1px solid black;
                   6735:   vertical-align: middle;
1.1075.2.4  raeburn  6736:   float: left;
                   6737: }
                   6738: 
                   6739: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6740:   background-color: $data_table_light;
                   6741: }
                   6742: 
                   6743: ul#LC_secondary_menu li a {
                   6744:   padding: 0 0.8em;
                   6745: }
                   6746: 
                   6747: ul#LC_secondary_menu li ul {
                   6748:   display: none;
                   6749: }
                   6750: 
                   6751: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6752:   display: block;
                   6753:   position: absolute;
                   6754:   margin: 0;
                   6755:   padding: 0;
                   6756:   list-style:none;
                   6757:   float: none;
                   6758:   background-color: $data_table_light;
1.1075.2.5  raeburn  6759:   z-index: 2;
1.1075.2.10  raeburn  6760:   margin-left: -1px;
1.1075.2.4  raeburn  6761: }
                   6762: 
                   6763: ul#LC_secondary_menu li ul li {
                   6764:   font-size: 90%;
                   6765:   vertical-align: top;
                   6766:   border-left: 1px solid black;
                   6767:   border-right: 1px solid black;
1.1075.2.33  raeburn  6768:   background-color: $data_table_light;
1.1075.2.4  raeburn  6769:   list-style:none;
                   6770:   float: none;
                   6771: }
                   6772: 
                   6773: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6774:   background-color: $data_table_dark;
1.807     droeschl 6775: }
                   6776: 
1.847     tempelho 6777: ul.LC_TabContent {
1.911     bisitz   6778:   display:block;
                   6779:   background: $sidebg;
                   6780:   border-bottom: solid 1px $lg_border_color;
                   6781:   list-style:none;
1.1020    raeburn  6782:   margin: -1px -10px 0 -10px;
1.911     bisitz   6783:   padding: 0;
1.693     droeschl 6784: }
                   6785: 
1.795     www      6786: ul.LC_TabContent li,
                   6787: ul.LC_TabContentBigger li {
1.911     bisitz   6788:   float:left;
1.741     harmsja  6789: }
1.795     www      6790: 
1.897     wenzelju 6791: ul#LC_secondary_menu li a {
1.911     bisitz   6792:   color: $fontmenu;
                   6793:   text-decoration: none;
1.693     droeschl 6794: }
1.795     www      6795: 
1.721     harmsja  6796: ul.LC_TabContent {
1.952     onken    6797:   min-height:20px;
1.721     harmsja  6798: }
1.795     www      6799: 
                   6800: ul.LC_TabContent li {
1.911     bisitz   6801:   vertical-align:middle;
1.959     onken    6802:   padding: 0 16px 0 10px;
1.911     bisitz   6803:   background-color:$tabbg;
                   6804:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6805:   border-left: solid 1px $font;
1.721     harmsja  6806: }
1.795     www      6807: 
1.847     tempelho 6808: ul.LC_TabContent .right {
1.911     bisitz   6809:   float:right;
1.847     tempelho 6810: }
                   6811: 
1.911     bisitz   6812: ul.LC_TabContent li a,
                   6813: ul.LC_TabContent li {
                   6814:   color:rgb(47,47,47);
                   6815:   text-decoration:none;
                   6816:   font-size:95%;
                   6817:   font-weight:bold;
1.952     onken    6818:   min-height:20px;
                   6819: }
                   6820: 
1.959     onken    6821: ul.LC_TabContent li a:hover,
                   6822: ul.LC_TabContent li a:focus {
1.952     onken    6823:   color: $button_hover;
1.959     onken    6824:   background:none;
                   6825:   outline:none;
1.952     onken    6826: }
                   6827: 
                   6828: ul.LC_TabContent li:hover {
                   6829:   color: $button_hover;
                   6830:   cursor:pointer;
1.721     harmsja  6831: }
1.795     www      6832: 
1.911     bisitz   6833: ul.LC_TabContent li.active {
1.952     onken    6834:   color: $font;
1.911     bisitz   6835:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6836:   border-bottom:solid 1px #FFFFFF;
                   6837:   cursor: default;
1.744     ehlerst  6838: }
1.795     www      6839: 
1.959     onken    6840: ul.LC_TabContent li.active a {
                   6841:   color:$font;
                   6842:   background:#FFFFFF;
                   6843:   outline: none;
                   6844: }
1.1047    raeburn  6845: 
                   6846: ul.LC_TabContent li.goback {
                   6847:   float: left;
                   6848:   border-left: none;
                   6849: }
                   6850: 
1.870     tempelho 6851: #maincoursedoc {
1.911     bisitz   6852:   clear:both;
1.870     tempelho 6853: }
                   6854: 
                   6855: ul.LC_TabContentBigger {
1.911     bisitz   6856:   display:block;
                   6857:   list-style:none;
                   6858:   padding: 0;
1.870     tempelho 6859: }
                   6860: 
1.795     www      6861: ul.LC_TabContentBigger li {
1.911     bisitz   6862:   vertical-align:bottom;
                   6863:   height: 30px;
                   6864:   font-size:110%;
                   6865:   font-weight:bold;
                   6866:   color: #737373;
1.841     tempelho 6867: }
                   6868: 
1.957     onken    6869: ul.LC_TabContentBigger li.active {
                   6870:   position: relative;
                   6871:   top: 1px;
                   6872: }
                   6873: 
1.870     tempelho 6874: ul.LC_TabContentBigger li a {
1.911     bisitz   6875:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6876:   height: 30px;
                   6877:   line-height: 30px;
                   6878:   text-align: center;
                   6879:   display: block;
                   6880:   text-decoration: none;
1.958     onken    6881:   outline: none;  
1.741     harmsja  6882: }
1.795     www      6883: 
1.870     tempelho 6884: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6885:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6886:   color:$font;
1.744     ehlerst  6887: }
1.795     www      6888: 
1.870     tempelho 6889: ul.LC_TabContentBigger li b {
1.911     bisitz   6890:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6891:   display: block;
                   6892:   float: left;
                   6893:   padding: 0 30px;
1.957     onken    6894:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6895: }
                   6896: 
1.956     onken    6897: ul.LC_TabContentBigger li:hover b {
                   6898:   color:$button_hover;
                   6899: }
                   6900: 
1.870     tempelho 6901: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6902:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6903:   color:$font;
1.957     onken    6904:   border: 0;
1.741     harmsja  6905: }
1.693     droeschl 6906: 
1.870     tempelho 6907: 
1.862     bisitz   6908: ul.LC_CourseBreadcrumbs {
                   6909:   background: $sidebg;
1.1020    raeburn  6910:   height: 2em;
1.862     bisitz   6911:   padding-left: 10px;
1.1020    raeburn  6912:   margin: 0;
1.862     bisitz   6913:   list-style-position: inside;
                   6914: }
                   6915: 
1.911     bisitz   6916: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6917: ol#LC_PathBreadcrumbs {
1.911     bisitz   6918:   padding-left: 10px;
                   6919:   margin: 0;
1.933     droeschl 6920:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6921: }
                   6922: 
1.911     bisitz   6923: ol#LC_MenuBreadcrumbs li,
                   6924: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6925: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6926:   display: inline;
1.933     droeschl 6927:   white-space: normal;  
1.693     droeschl 6928: }
                   6929: 
1.823     bisitz   6930: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6931: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6932:   text-decoration: none;
                   6933:   font-size:90%;
1.693     droeschl 6934: }
1.795     www      6935: 
1.969     droeschl 6936: ol#LC_MenuBreadcrumbs h1 {
                   6937:   display: inline;
                   6938:   font-size: 90%;
                   6939:   line-height: 2.5em;
                   6940:   margin: 0;
                   6941:   padding: 0;
                   6942: }
                   6943: 
1.795     www      6944: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6945:   text-decoration:none;
                   6946:   font-size:100%;
                   6947:   font-weight:bold;
1.693     droeschl 6948: }
1.795     www      6949: 
1.840     bisitz   6950: .LC_Box {
1.911     bisitz   6951:   border: solid 1px $lg_border_color;
                   6952:   padding: 0 10px 10px 10px;
1.746     neumanie 6953: }
1.795     www      6954: 
1.1020    raeburn  6955: .LC_DocsBox {
                   6956:   border: solid 1px $lg_border_color;
                   6957:   padding: 0 0 10px 10px;
                   6958: }
                   6959: 
1.795     www      6960: .LC_AboutMe_Image {
1.911     bisitz   6961:   float:left;
                   6962:   margin-right:10px;
1.747     neumanie 6963: }
1.795     www      6964: 
                   6965: .LC_Clear_AboutMe_Image {
1.911     bisitz   6966:   clear:left;
1.747     neumanie 6967: }
1.795     www      6968: 
1.721     harmsja  6969: dl.LC_ListStyleClean dt {
1.911     bisitz   6970:   padding-right: 5px;
                   6971:   display: table-header-group;
1.693     droeschl 6972: }
                   6973: 
1.721     harmsja  6974: dl.LC_ListStyleClean dd {
1.911     bisitz   6975:   display: table-row;
1.693     droeschl 6976: }
                   6977: 
1.721     harmsja  6978: .LC_ListStyleClean,
                   6979: .LC_ListStyleSimple,
                   6980: .LC_ListStyleNormal,
1.795     www      6981: .LC_ListStyleSpecial {
1.911     bisitz   6982:   /* display:block; */
                   6983:   list-style-position: inside;
                   6984:   list-style-type: none;
                   6985:   overflow: hidden;
                   6986:   padding: 0;
1.693     droeschl 6987: }
                   6988: 
1.721     harmsja  6989: .LC_ListStyleSimple li,
                   6990: .LC_ListStyleSimple dd,
                   6991: .LC_ListStyleNormal li,
                   6992: .LC_ListStyleNormal dd,
                   6993: .LC_ListStyleSpecial li,
1.795     www      6994: .LC_ListStyleSpecial dd {
1.911     bisitz   6995:   margin: 0;
                   6996:   padding: 5px 5px 5px 10px;
                   6997:   clear: both;
1.693     droeschl 6998: }
                   6999: 
1.721     harmsja  7000: .LC_ListStyleClean li,
                   7001: .LC_ListStyleClean dd {
1.911     bisitz   7002:   padding-top: 0;
                   7003:   padding-bottom: 0;
1.693     droeschl 7004: }
                   7005: 
1.721     harmsja  7006: .LC_ListStyleSimple dd,
1.795     www      7007: .LC_ListStyleSimple li {
1.911     bisitz   7008:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7009: }
                   7010: 
1.721     harmsja  7011: .LC_ListStyleSpecial li,
                   7012: .LC_ListStyleSpecial dd {
1.911     bisitz   7013:   list-style-type: none;
                   7014:   background-color: RGB(220, 220, 220);
                   7015:   margin-bottom: 4px;
1.693     droeschl 7016: }
                   7017: 
1.721     harmsja  7018: table.LC_SimpleTable {
1.911     bisitz   7019:   margin:5px;
                   7020:   border:solid 1px $lg_border_color;
1.795     www      7021: }
1.693     droeschl 7022: 
1.721     harmsja  7023: table.LC_SimpleTable tr {
1.911     bisitz   7024:   padding: 0;
                   7025:   border:solid 1px $lg_border_color;
1.693     droeschl 7026: }
1.795     www      7027: 
                   7028: table.LC_SimpleTable thead {
1.911     bisitz   7029:   background:rgb(220,220,220);
1.693     droeschl 7030: }
                   7031: 
1.721     harmsja  7032: div.LC_columnSection {
1.911     bisitz   7033:   display: block;
                   7034:   clear: both;
                   7035:   overflow: hidden;
                   7036:   margin: 0;
1.693     droeschl 7037: }
                   7038: 
1.721     harmsja  7039: div.LC_columnSection>* {
1.911     bisitz   7040:   float: left;
                   7041:   margin: 10px 20px 10px 0;
                   7042:   overflow:hidden;
1.693     droeschl 7043: }
1.721     harmsja  7044: 
1.795     www      7045: table em {
1.911     bisitz   7046:   font-weight: bold;
                   7047:   font-style: normal;
1.748     schulted 7048: }
1.795     www      7049: 
1.779     bisitz   7050: table.LC_tableBrowseRes,
1.795     www      7051: table.LC_tableOfContent {
1.911     bisitz   7052:   border:none;
                   7053:   border-spacing: 1px;
                   7054:   padding: 3px;
                   7055:   background-color: #FFFFFF;
                   7056:   font-size: 90%;
1.753     droeschl 7057: }
1.789     droeschl 7058: 
1.911     bisitz   7059: table.LC_tableOfContent {
                   7060:   border-collapse: collapse;
1.789     droeschl 7061: }
                   7062: 
1.771     droeschl 7063: table.LC_tableBrowseRes a,
1.768     schulted 7064: table.LC_tableOfContent a {
1.911     bisitz   7065:   background-color: transparent;
                   7066:   text-decoration: none;
1.753     droeschl 7067: }
                   7068: 
1.795     www      7069: table.LC_tableOfContent img {
1.911     bisitz   7070:   border: none;
                   7071:   height: 1.3em;
                   7072:   vertical-align: text-bottom;
                   7073:   margin-right: 0.3em;
1.753     droeschl 7074: }
1.757     schulted 7075: 
1.795     www      7076: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7077:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7078: }
                   7079: 
1.795     www      7080: a#LC_content_toolbar_everything {
1.911     bisitz   7081:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7082: }
                   7083: 
1.795     www      7084: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7085:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7086: }
                   7087: 
1.795     www      7088: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7089:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7090: }
                   7091: 
1.795     www      7092: a#LC_content_toolbar_changefolder {
1.911     bisitz   7093:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7094: }
                   7095: 
1.795     www      7096: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7097:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7098: }
                   7099: 
1.1043    raeburn  7100: a#LC_content_toolbar_edittoplevel {
                   7101:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7102: }
                   7103: 
1.795     www      7104: ul#LC_toolbar li a:hover {
1.911     bisitz   7105:   background-position: bottom center;
1.757     schulted 7106: }
                   7107: 
1.795     www      7108: ul#LC_toolbar {
1.911     bisitz   7109:   padding: 0;
                   7110:   margin: 2px;
                   7111:   list-style:none;
                   7112:   position:relative;
                   7113:   background-color:white;
1.1075.2.9  raeburn  7114:   overflow: auto;
1.757     schulted 7115: }
                   7116: 
1.795     www      7117: ul#LC_toolbar li {
1.911     bisitz   7118:   border:1px solid white;
                   7119:   padding: 0;
                   7120:   margin: 0;
                   7121:   float: left;
                   7122:   display:inline;
                   7123:   vertical-align:middle;
1.1075.2.9  raeburn  7124:   white-space: nowrap;
1.911     bisitz   7125: }
1.757     schulted 7126: 
1.783     amueller 7127: 
1.795     www      7128: a.LC_toolbarItem {
1.911     bisitz   7129:   display:block;
                   7130:   padding: 0;
                   7131:   margin: 0;
                   7132:   height: 32px;
                   7133:   width: 32px;
                   7134:   color:white;
                   7135:   border: none;
                   7136:   background-repeat:no-repeat;
                   7137:   background-color:transparent;
1.757     schulted 7138: }
                   7139: 
1.915     droeschl 7140: ul.LC_funclist {
                   7141:     margin: 0;
                   7142:     padding: 0.5em 1em 0.5em 0;
                   7143: }
                   7144: 
1.933     droeschl 7145: ul.LC_funclist > li:first-child {
                   7146:     font-weight:bold; 
                   7147:     margin-left:0.8em;
                   7148: }
                   7149: 
1.915     droeschl 7150: ul.LC_funclist + ul.LC_funclist {
                   7151:     /* 
                   7152:        left border as a seperator if we have more than
                   7153:        one list 
                   7154:     */
                   7155:     border-left: 1px solid $sidebg;
                   7156:     /* 
                   7157:        this hides the left border behind the border of the 
                   7158:        outer box if element is wrapped to the next 'line' 
                   7159:     */
                   7160:     margin-left: -1px;
                   7161: }
                   7162: 
1.843     bisitz   7163: ul.LC_funclist li {
1.915     droeschl 7164:   display: inline;
1.782     bisitz   7165:   white-space: nowrap;
1.915     droeschl 7166:   margin: 0 0 0 25px;
                   7167:   line-height: 150%;
1.782     bisitz   7168: }
                   7169: 
1.974     wenzelju 7170: .LC_hidden {
                   7171:   display: none;
                   7172: }
                   7173: 
1.1030    www      7174: .LCmodal-overlay {
                   7175: 		position:fixed;
                   7176: 		top:0;
                   7177: 		right:0;
                   7178: 		bottom:0;
                   7179: 		left:0;
                   7180: 		height:100%;
                   7181: 		width:100%;
                   7182: 		margin:0;
                   7183: 		padding:0;
                   7184: 		background:#999;
                   7185: 		opacity:.75;
                   7186: 		filter: alpha(opacity=75);
                   7187: 		-moz-opacity: 0.75;
                   7188: 		z-index:101;
                   7189: }
                   7190: 
                   7191: * html .LCmodal-overlay {   
                   7192: 		position: absolute;
                   7193: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7194: }
                   7195: 
                   7196: .LCmodal-window {
                   7197: 		position:fixed;
                   7198: 		top:50%;
                   7199: 		left:50%;
                   7200: 		margin:0;
                   7201: 		padding:0;
                   7202: 		z-index:102;
                   7203: 	}
                   7204: 
                   7205: * html .LCmodal-window {
                   7206: 		position:absolute;
                   7207: }
                   7208: 
                   7209: .LCclose-window {
                   7210: 		position:absolute;
                   7211: 		width:32px;
                   7212: 		height:32px;
                   7213: 		right:8px;
                   7214: 		top:8px;
                   7215: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7216: 		text-indent:-99999px;
                   7217: 		overflow:hidden;
                   7218: 		cursor:pointer;
                   7219: }
                   7220: 
1.1075.2.17  raeburn  7221: /*
                   7222:   styles used by TTH when "Default set of options to pass to tth/m
                   7223:   when converting TeX" in course settings has been set
                   7224: 
                   7225:   option passed: -t
                   7226: 
                   7227: */
                   7228: 
                   7229: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7230: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7231: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7232: td div.norm {line-height:normal;}
                   7233: 
                   7234: /*
                   7235:   option passed -y3
                   7236: */
                   7237: 
                   7238: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7239: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7240: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7241: 
1.343     albertel 7242: END
                   7243: }
                   7244: 
1.306     albertel 7245: =pod
                   7246: 
                   7247: =item * &headtag()
                   7248: 
                   7249: Returns a uniform footer for LON-CAPA web pages.
                   7250: 
1.307     albertel 7251: Inputs: $title - optional title for the head
                   7252:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7253:         $args - optional arguments
1.319     albertel 7254:             force_register - if is true call registerurl so the remote is 
                   7255:                              informed
1.415     albertel 7256:             redirect       -> array ref of
                   7257:                                    1- seconds before redirect occurs
                   7258:                                    2- url to redirect to
                   7259:                                    3- whether the side effect should occur
1.315     albertel 7260:                            (side effect of setting 
                   7261:                                $env{'internal.head.redirect'} to the url 
                   7262:                                redirected too)
1.352     albertel 7263:             domain         -> force to color decorate a page for a specific
                   7264:                                domain
                   7265:             function       -> force usage of a specific rolish color scheme
                   7266:             bgcolor        -> override the default page bgcolor
1.460     albertel 7267:             no_auto_mt_title
                   7268:                            -> prevent &mt()ing the title arg
1.464     albertel 7269: 
1.306     albertel 7270: =cut
                   7271: 
                   7272: sub headtag {
1.313     albertel 7273:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7274:     
1.363     albertel 7275:     my $function = $args->{'function'} || &get_users_function();
                   7276:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7277:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7278:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7279:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7280: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7281: 		   #time(),
1.418     albertel 7282: 		   $env{'environment.color.timestamp'},
1.363     albertel 7283: 		   $function,$domain,$bgcolor);
                   7284: 
1.369     www      7285:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7286: 
1.308     albertel 7287:     my $result =
                   7288: 	'<head>'.
1.1075.2.56  raeburn  7289: 	&font_settings($args);
1.319     albertel 7290: 
1.1064    raeburn  7291:     my $inhibitprint = &print_suppression();
                   7292: 
1.461     albertel 7293:     if (!$args->{'frameset'}) {
                   7294: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7295:     }
1.1075.2.12  raeburn  7296:     if ($args->{'force_register'}) {
                   7297:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7298:     }
1.436     albertel 7299:     if (!$args->{'no_nav_bar'} 
                   7300: 	&& !$args->{'only_body'}
                   7301: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7302: 	$result .= &help_menu_js($httphost);
1.1032    www      7303:         $result.=&modal_window();
1.1038    www      7304:         $result.=&togglebox_script();
1.1034    www      7305:         $result.=&wishlist_window();
1.1041    www      7306:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7307:     } else {
                   7308:         if ($args->{'add_modal'}) {
                   7309:            $result.=&modal_window();
                   7310:         }
                   7311:         if ($args->{'add_wishlist'}) {
                   7312:            $result.=&wishlist_window();
                   7313:         }
1.1038    www      7314:         if ($args->{'add_togglebox'}) {
                   7315:            $result.=&togglebox_script();
                   7316:         }
1.1041    www      7317:         if ($args->{'add_progressbar'}) {
                   7318:            $result.=&LCprogressbarUpdate_script();
                   7319:         }
1.436     albertel 7320:     }
1.314     albertel 7321:     if (ref($args->{'redirect'})) {
1.414     albertel 7322: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7323: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7324: 	if (!$inhibit_continue) {
                   7325: 	    $env{'internal.head.redirect'} = $url;
                   7326: 	}
1.313     albertel 7327: 	$result.=<<ADDMETA
                   7328: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7329: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7330: ADDMETA
                   7331:     }
1.306     albertel 7332:     if (!defined($title)) {
                   7333: 	$title = 'The LearningOnline Network with CAPA';
                   7334:     }
1.460     albertel 7335:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7336:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7337: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7338:     if (!$args->{'frameset'}) {
                   7339:         $result .= ' /';
                   7340:     }
                   7341:     $result .= '>'
1.1064    raeburn  7342:         .$inhibitprint
1.414     albertel 7343: 	.$head_extra;
1.1075.2.42  raeburn  7344:     if ($env{'browser.mobile'}) {
                   7345:         $result .= '
                   7346: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7347: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7348:     }
1.962     droeschl 7349:     return $result.'</head>';
1.306     albertel 7350: }
                   7351: 
                   7352: =pod
                   7353: 
1.340     albertel 7354: =item * &font_settings()
                   7355: 
                   7356: Returns neccessary <meta> to set the proper encoding
                   7357: 
1.1075.2.56  raeburn  7358: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7359: 
                   7360: =cut
                   7361: 
                   7362: sub font_settings {
1.1075.2.56  raeburn  7363:     my ($args) = @_;
1.340     albertel 7364:     my $headerstring='';
1.1075.2.56  raeburn  7365:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7366:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7367: 	$headerstring.=
1.1075.2.61  raeburn  7368: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7369:         if (!$args->{'frameset'}) {
                   7370:             $headerstring.= ' /';
                   7371:         }
                   7372:         $headerstring .= '>'."\n";
1.340     albertel 7373:     }
                   7374:     return $headerstring;
                   7375: }
                   7376: 
1.341     albertel 7377: =pod
                   7378: 
1.1064    raeburn  7379: =item * &print_suppression()
                   7380: 
                   7381: In course context returns css which causes the body to be blank when media="print",
                   7382: if printout generation is unavailable for the current resource.
                   7383: 
                   7384: This could be because:
                   7385: 
                   7386: (a) printstartdate is in the future
                   7387: 
                   7388: (b) printenddate is in the past
                   7389: 
                   7390: (c) there is an active exam block with "printout"
                   7391: functionality blocked
                   7392: 
                   7393: Users with pav, pfo or evb privileges are exempt.
                   7394: 
                   7395: Inputs: none
                   7396: 
                   7397: =cut
                   7398: 
                   7399: 
                   7400: sub print_suppression {
                   7401:     my $noprint;
                   7402:     if ($env{'request.course.id'}) {
                   7403:         my $scope = $env{'request.course.id'};
                   7404:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7405:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7406:             return;
                   7407:         }
                   7408:         if ($env{'request.course.sec'} ne '') {
                   7409:             $scope .= "/$env{'request.course.sec'}";
                   7410:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7411:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7412:                 return;
1.1064    raeburn  7413:             }
                   7414:         }
                   7415:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7416:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7417:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7418:         if ($blocked) {
                   7419:             my $checkrole = "cm./$cdom/$cnum";
                   7420:             if ($env{'request.course.sec'} ne '') {
                   7421:                 $checkrole .= "/$env{'request.course.sec'}";
                   7422:             }
                   7423:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7424:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7425:                 $noprint = 1;
                   7426:             }
                   7427:         }
                   7428:         unless ($noprint) {
                   7429:             my $symb = &Apache::lonnet::symbread();
                   7430:             if ($symb ne '') {
                   7431:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7432:                 if (ref($navmap)) {
                   7433:                     my $res = $navmap->getBySymb($symb);
                   7434:                     if (ref($res)) {
                   7435:                         if (!$res->resprintable()) {
                   7436:                             $noprint = 1;
                   7437:                         }
                   7438:                     }
                   7439:                 }
                   7440:             }
                   7441:         }
                   7442:         if ($noprint) {
                   7443:             return <<"ENDSTYLE";
                   7444: <style type="text/css" media="print">
                   7445:     body { display:none }
                   7446: </style>
                   7447: ENDSTYLE
                   7448:         }
                   7449:     }
                   7450:     return;
                   7451: }
                   7452: 
                   7453: =pod
                   7454: 
1.341     albertel 7455: =item * &xml_begin()
                   7456: 
                   7457: Returns the needed doctype and <html>
                   7458: 
                   7459: Inputs: none
                   7460: 
                   7461: =cut
                   7462: 
                   7463: sub xml_begin {
1.1075.2.61  raeburn  7464:     my ($is_frameset) = @_;
1.341     albertel 7465:     my $output='';
                   7466: 
                   7467:     if ($env{'browser.mathml'}) {
                   7468: 	$output='<?xml version="1.0"?>'
                   7469:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7470: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7471:             
                   7472: #	    .'<!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">] >'
                   7473: 	    .'<!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">'
                   7474:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7475: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  7476:     } elsif ($is_frameset) {
                   7477:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7478:                 '<html>'."\n";
1.341     albertel 7479:     } else {
1.1075.2.61  raeburn  7480: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7481:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7482:     }
                   7483:     return $output;
                   7484: }
1.340     albertel 7485: 
                   7486: =pod
                   7487: 
1.306     albertel 7488: =item * &start_page()
                   7489: 
                   7490: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7491: 
1.648     raeburn  7492: Inputs:
                   7493: 
                   7494: =over 4
                   7495: 
                   7496: $title - optional title for the page
                   7497: 
                   7498: $head_extra - optional extra HTML to incude inside the <head>
                   7499: 
                   7500: $args - additional optional args supported are:
                   7501: 
                   7502: =over 8
                   7503: 
                   7504:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7505:                                     arg on
1.814     bisitz   7506:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7507:              add_entries    -> additional attributes to add to the  <body>
                   7508:              domain         -> force to color decorate a page for a 
1.317     albertel 7509:                                     specific domain
1.648     raeburn  7510:              function       -> force usage of a specific rolish color
1.317     albertel 7511:                                     scheme
1.648     raeburn  7512:              redirect       -> see &headtag()
                   7513:              bgcolor        -> override the default page bg color
                   7514:              js_ready       -> return a string ready for being used in 
1.317     albertel 7515:                                     a javascript writeln
1.648     raeburn  7516:              html_encode    -> return a string ready for being used in 
1.320     albertel 7517:                                     a html attribute
1.648     raeburn  7518:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7519:                                     $forcereg arg
1.648     raeburn  7520:              frameset       -> if true will start with a <frameset>
1.330     albertel 7521:                                     rather than <body>
1.648     raeburn  7522:              skip_phases    -> hash ref of 
1.338     albertel 7523:                                     head -> skip the <html><head> generation
                   7524:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  7525:              no_inline_link -> if true and in remote mode, don't show the
                   7526:                                     'Switch To Inline Menu' link
1.648     raeburn  7527:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7528:              inherit_jsmath -> when creating popup window in a page,
                   7529:                                     should it have jsmath forced on by the
                   7530:                                     current page
1.867     kalberla 7531:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7532:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  7533:              group          -> includes the current group, if page is for a
                   7534:                                specific group
1.361     albertel 7535: 
1.648     raeburn  7536: =back
1.460     albertel 7537: 
1.648     raeburn  7538: =back
1.562     albertel 7539: 
1.306     albertel 7540: =cut
                   7541: 
                   7542: sub start_page {
1.309     albertel 7543:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7544:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7545: 
1.315     albertel 7546:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  7547:     my ($result,@advtools);
1.964     droeschl 7548: 
1.338     albertel 7549:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62! raeburn  7550:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 7551:     }
                   7552:     
                   7553:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7554: 	if ($args->{'frameset'}) {
                   7555: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7556: 						$args->{'add_entries'});
                   7557: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7558:         } else {
                   7559:             $result .=
                   7560:                 &bodytag($title, 
                   7561:                          $args->{'function'},       $args->{'add_entries'},
                   7562:                          $args->{'only_body'},      $args->{'domain'},
                   7563:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  7564:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  7565:                          $args,                     \@advtools);
1.831     bisitz   7566:         }
1.330     albertel 7567:     }
1.338     albertel 7568: 
1.315     albertel 7569:     if ($args->{'js_ready'}) {
1.713     kaisler  7570: 		$result = &js_ready($result);
1.315     albertel 7571:     }
1.320     albertel 7572:     if ($args->{'html_encode'}) {
1.713     kaisler  7573: 		$result = &html_encode($result);
                   7574:     }
                   7575: 
1.813     bisitz   7576:     # Preparation for new and consistent functionlist at top of screen
                   7577:     # if ($args->{'functionlist'}) {
                   7578:     #            $result .= &build_functionlist();
                   7579:     #}
                   7580: 
1.964     droeschl 7581:     # Don't add anything more if only_body wanted or in const space
                   7582:     return $result if    $args->{'only_body'} 
                   7583:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7584: 
                   7585:     #Breadcrumbs
1.758     kaisler  7586:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7587: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7588: 		#if any br links exists, add them to the breadcrumbs
                   7589: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7590: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7591: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7592: 			}
                   7593: 		}
1.1075.2.19  raeburn  7594:                 # if @advtools array contains items add then to the breadcrumbs
                   7595:                 if (@advtools > 0) {
                   7596:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7597:                 }
1.758     kaisler  7598: 
                   7599: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7600: 		if(exists($args->{'bread_crumbs_component'})){
                   7601: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7602: 		}else{
                   7603: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7604: 		}
1.1075.2.24  raeburn  7605:     } elsif (($env{'environment.remote'} eq 'on') &&
                   7606:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   7607:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   7608:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  7609:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 7610:     }
1.315     albertel 7611:     return $result;
1.306     albertel 7612: }
                   7613: 
                   7614: sub end_page {
1.315     albertel 7615:     my ($args) = @_;
                   7616:     $env{'internal.end_page'}++;
1.330     albertel 7617:     my $result;
1.335     albertel 7618:     if ($args->{'discussion'}) {
                   7619: 	my ($target,$parser);
                   7620: 	if (ref($args->{'discussion'})) {
                   7621: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7622: 				$args->{'discussion'}{'parser'});
                   7623: 	}
                   7624: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7625:     }
1.330     albertel 7626:     if ($args->{'frameset'}) {
                   7627: 	$result .= '</frameset>';
                   7628:     } else {
1.635     raeburn  7629: 	$result .= &endbodytag($args);
1.330     albertel 7630:     }
1.1075.2.6  raeburn  7631:     unless ($args->{'notbody'}) {
                   7632:         $result .= "\n</html>";
                   7633:     }
1.330     albertel 7634: 
1.315     albertel 7635:     if ($args->{'js_ready'}) {
1.317     albertel 7636: 	$result = &js_ready($result);
1.315     albertel 7637:     }
1.335     albertel 7638: 
1.320     albertel 7639:     if ($args->{'html_encode'}) {
                   7640: 	$result = &html_encode($result);
                   7641:     }
1.335     albertel 7642: 
1.315     albertel 7643:     return $result;
                   7644: }
                   7645: 
1.1034    www      7646: sub wishlist_window {
                   7647:     return(<<'ENDWISHLIST');
1.1046    raeburn  7648: <script type="text/javascript">
1.1034    www      7649: // <![CDATA[
                   7650: // <!-- BEGIN LON-CAPA Internal
                   7651: function set_wishlistlink(title, path) {
                   7652:     if (!title) {
                   7653:         title = document.title;
                   7654:         title = title.replace(/^LON-CAPA /,'');
                   7655:     }
                   7656:     if (!path) {
                   7657:         path = location.pathname;
                   7658:     }
                   7659:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7660:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7661: }
                   7662: // END LON-CAPA Internal -->
                   7663: // ]]>
                   7664: </script>
                   7665: ENDWISHLIST
                   7666: }
                   7667: 
1.1030    www      7668: sub modal_window {
                   7669:     return(<<'ENDMODAL');
1.1046    raeburn  7670: <script type="text/javascript">
1.1030    www      7671: // <![CDATA[
                   7672: // <!-- BEGIN LON-CAPA Internal
                   7673: var modalWindow = {
                   7674: 	parent:"body",
                   7675: 	windowId:null,
                   7676: 	content:null,
                   7677: 	width:null,
                   7678: 	height:null,
                   7679: 	close:function()
                   7680: 	{
                   7681: 	        $(".LCmodal-window").remove();
                   7682: 	        $(".LCmodal-overlay").remove();
                   7683: 	},
                   7684: 	open:function()
                   7685: 	{
                   7686: 		var modal = "";
                   7687: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7688: 		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;\">";
                   7689: 		modal += this.content;
                   7690: 		modal += "</div>";	
                   7691: 
                   7692: 		$(this.parent).append(modal);
                   7693: 
                   7694: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7695: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7696: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7697: 	}
                   7698: };
1.1075.2.42  raeburn  7699: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      7700: 	{
                   7701: 		modalWindow.windowId = "myModal";
                   7702: 		modalWindow.width = width;
                   7703: 		modalWindow.height = height;
1.1075.2.42  raeburn  7704: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'>&lt/iframe>";
1.1030    www      7705: 		modalWindow.open();
                   7706: 	};	
                   7707: // END LON-CAPA Internal -->
                   7708: // ]]>
                   7709: </script>
                   7710: ENDMODAL
                   7711: }
                   7712: 
                   7713: sub modal_link {
1.1075.2.42  raeburn  7714:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      7715:     unless ($width) { $width=480; }
                   7716:     unless ($height) { $height=400; }
1.1031    www      7717:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  7718:     unless ($transparency) { $transparency='true'; }
                   7719: 
1.1074    raeburn  7720:     my $target_attr;
                   7721:     if (defined($target)) {
                   7722:         $target_attr = 'target="'.$target.'"';
                   7723:     }
                   7724:     return <<"ENDLINK";
1.1075.2.42  raeburn  7725: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  7726:            $linktext</a>
                   7727: ENDLINK
1.1030    www      7728: }
                   7729: 
1.1032    www      7730: sub modal_adhoc_script {
                   7731:     my ($funcname,$width,$height,$content)=@_;
                   7732:     return (<<ENDADHOC);
1.1046    raeburn  7733: <script type="text/javascript">
1.1032    www      7734: // <![CDATA[
                   7735:         var $funcname = function()
                   7736:         {
                   7737:                 modalWindow.windowId = "myModal";
                   7738:                 modalWindow.width = $width;
                   7739:                 modalWindow.height = $height;
                   7740:                 modalWindow.content = '$content';
                   7741:                 modalWindow.open();
                   7742:         };  
                   7743: // ]]>
                   7744: </script>
                   7745: ENDADHOC
                   7746: }
                   7747: 
1.1041    www      7748: sub modal_adhoc_inner {
                   7749:     my ($funcname,$width,$height,$content)=@_;
                   7750:     my $innerwidth=$width-20;
                   7751:     $content=&js_ready(
1.1042    www      7752:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  7753:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   7754:                  $content.
1.1041    www      7755:                  &end_scrollbox().
1.1075.2.42  raeburn  7756:                  &end_page()
1.1041    www      7757:              );
                   7758:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7759: }
                   7760: 
                   7761: sub modal_adhoc_window {
                   7762:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7763:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7764:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7765: }
                   7766: 
                   7767: sub modal_adhoc_launch {
                   7768:     my ($funcname,$width,$height,$content)=@_;
                   7769:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7770: <script type="text/javascript">
                   7771: // <![CDATA[
                   7772: $funcname();
                   7773: // ]]>
                   7774: </script>
                   7775: ENDLAUNCH
                   7776: }
                   7777: 
                   7778: sub modal_adhoc_close {
                   7779:     return (<<ENDCLOSE);
                   7780: <script type="text/javascript">
                   7781: // <![CDATA[
                   7782: modalWindow.close();
                   7783: // ]]>
                   7784: </script>
                   7785: ENDCLOSE
                   7786: }
                   7787: 
1.1038    www      7788: sub togglebox_script {
                   7789:    return(<<ENDTOGGLE);
                   7790: <script type="text/javascript"> 
                   7791: // <![CDATA[
                   7792: function LCtoggleDisplay(id,hidetext,showtext) {
                   7793:    link = document.getElementById(id + "link").childNodes[0];
                   7794:    with (document.getElementById(id).style) {
                   7795:       if (display == "none" ) {
                   7796:           display = "inline";
                   7797:           link.nodeValue = hidetext;
                   7798:         } else {
                   7799:           display = "none";
                   7800:           link.nodeValue = showtext;
                   7801:        }
                   7802:    }
                   7803: }
                   7804: // ]]>
                   7805: </script>
                   7806: ENDTOGGLE
                   7807: }
                   7808: 
1.1039    www      7809: sub start_togglebox {
                   7810:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7811:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7812:     unless ($showtext) { $showtext=&mt('show'); }
                   7813:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7814:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7815:     return &start_data_table().
                   7816:            &start_data_table_header_row().
                   7817:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7818:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7819:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7820:            &end_data_table_header_row().
                   7821:            '<tr id="'.$id.'" style="display:none""><td>';
                   7822: }
                   7823: 
                   7824: sub end_togglebox {
                   7825:     return '</td></tr>'.&end_data_table();
                   7826: }
                   7827: 
1.1041    www      7828: sub LCprogressbar_script {
1.1045    www      7829:    my ($id)=@_;
1.1041    www      7830:    return(<<ENDPROGRESS);
                   7831: <script type="text/javascript">
                   7832: // <![CDATA[
1.1045    www      7833: \$('#progressbar$id').progressbar({
1.1041    www      7834:   value: 0,
                   7835:   change: function(event, ui) {
                   7836:     var newVal = \$(this).progressbar('option', 'value');
                   7837:     \$('.pblabel', this).text(LCprogressTxt);
                   7838:   }
                   7839: });
                   7840: // ]]>
                   7841: </script>
                   7842: ENDPROGRESS
                   7843: }
                   7844: 
                   7845: sub LCprogressbarUpdate_script {
                   7846:    return(<<ENDPROGRESSUPDATE);
                   7847: <style type="text/css">
                   7848: .ui-progressbar { position:relative; }
                   7849: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7850: </style>
                   7851: <script type="text/javascript">
                   7852: // <![CDATA[
1.1045    www      7853: var LCprogressTxt='---';
                   7854: 
                   7855: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7856:    LCprogressTxt=progresstext;
1.1045    www      7857:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7858: }
                   7859: // ]]>
                   7860: </script>
                   7861: ENDPROGRESSUPDATE
                   7862: }
                   7863: 
1.1042    www      7864: my $LClastpercent;
1.1045    www      7865: my $LCidcnt;
                   7866: my $LCcurrentid;
1.1042    www      7867: 
1.1041    www      7868: sub LCprogressbar {
1.1042    www      7869:     my ($r)=(@_);
                   7870:     $LClastpercent=0;
1.1045    www      7871:     $LCidcnt++;
                   7872:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7873:     my $starting=&mt('Starting');
                   7874:     my $content=(<<ENDPROGBAR);
1.1045    www      7875:   <div id="progressbar$LCcurrentid">
1.1041    www      7876:     <span class="pblabel">$starting</span>
                   7877:   </div>
                   7878: ENDPROGBAR
1.1045    www      7879:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7880: }
                   7881: 
                   7882: sub LCprogressbarUpdate {
1.1042    www      7883:     my ($r,$val,$text)=@_;
                   7884:     unless ($val) { 
                   7885:        if ($LClastpercent) {
                   7886:            $val=$LClastpercent;
                   7887:        } else {
                   7888:            $val=0;
                   7889:        }
                   7890:     }
1.1041    www      7891:     if ($val<0) { $val=0; }
                   7892:     if ($val>100) { $val=0; }
1.1042    www      7893:     $LClastpercent=$val;
1.1041    www      7894:     unless ($text) { $text=$val.'%'; }
                   7895:     $text=&js_ready($text);
1.1044    www      7896:     &r_print($r,<<ENDUPDATE);
1.1041    www      7897: <script type="text/javascript">
                   7898: // <![CDATA[
1.1045    www      7899: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7900: // ]]>
                   7901: </script>
                   7902: ENDUPDATE
1.1035    www      7903: }
                   7904: 
1.1042    www      7905: sub LCprogressbarClose {
                   7906:     my ($r)=@_;
                   7907:     $LClastpercent=0;
1.1044    www      7908:     &r_print($r,<<ENDCLOSE);
1.1042    www      7909: <script type="text/javascript">
                   7910: // <![CDATA[
1.1045    www      7911: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7912: // ]]>
                   7913: </script>
                   7914: ENDCLOSE
1.1044    www      7915: }
                   7916: 
                   7917: sub r_print {
                   7918:     my ($r,$to_print)=@_;
                   7919:     if ($r) {
                   7920:       $r->print($to_print);
                   7921:       $r->rflush();
                   7922:     } else {
                   7923:       print($to_print);
                   7924:     }
1.1042    www      7925: }
                   7926: 
1.320     albertel 7927: sub html_encode {
                   7928:     my ($result) = @_;
                   7929: 
1.322     albertel 7930:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7931:     
                   7932:     return $result;
                   7933: }
1.1044    www      7934: 
1.317     albertel 7935: sub js_ready {
                   7936:     my ($result) = @_;
                   7937: 
1.323     albertel 7938:     $result =~ s/[\n\r]/ /xmsg;
                   7939:     $result =~ s/\\/\\\\/xmsg;
                   7940:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7941:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7942:     
                   7943:     return $result;
                   7944: }
                   7945: 
1.315     albertel 7946: sub validate_page {
                   7947:     if (  exists($env{'internal.start_page'})
1.316     albertel 7948: 	  &&     $env{'internal.start_page'} > 1) {
                   7949: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7950: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7951: 				 $ENV{'request.filename'});
1.315     albertel 7952:     }
                   7953:     if (  exists($env{'internal.end_page'})
1.316     albertel 7954: 	  &&     $env{'internal.end_page'} > 1) {
                   7955: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7956: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7957: 				 $env{'request.filename'});
1.315     albertel 7958:     }
                   7959:     if (     exists($env{'internal.start_page'})
                   7960: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7961: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7962: 				 $env{'request.filename'});
1.315     albertel 7963:     }
                   7964:     if (   ! exists($env{'internal.start_page'})
                   7965: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7966: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7967: 				 $env{'request.filename'});
1.315     albertel 7968:     }
1.306     albertel 7969: }
1.315     albertel 7970: 
1.996     www      7971: 
                   7972: sub start_scrollbox {
1.1075.2.56  raeburn  7973:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  7974:     unless ($outerwidth) { $outerwidth='520px'; }
                   7975:     unless ($width) { $width='500px'; }
                   7976:     unless ($height) { $height='200px'; }
1.1075    raeburn  7977:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7978:     if ($id ne '') {
1.1075.2.42  raeburn  7979:         $table_id = ' id="table_'.$id.'"';
                   7980:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  7981:     }
1.1075    raeburn  7982:     if ($bgcolor ne '') {
                   7983:         $tdcol = "background-color: $bgcolor;";
                   7984:     }
1.1075.2.42  raeburn  7985:     my $nicescroll_js;
                   7986:     if ($env{'browser.mobile'}) {
                   7987:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   7988:     }
1.1075    raeburn  7989:     return <<"END";
1.1075.2.42  raeburn  7990: $nicescroll_js
                   7991: 
                   7992: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  7993: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  7994: END
1.996     www      7995: }
                   7996: 
                   7997: sub end_scrollbox {
1.1036    www      7998:     return '</div></td></tr></table>';
1.996     www      7999: }
                   8000: 
1.1075.2.42  raeburn  8001: sub nicescroll_javascript {
                   8002:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8003:     my %options;
                   8004:     if (ref($cursor) eq 'HASH') {
                   8005:         %options = %{$cursor};
                   8006:     }
                   8007:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8008:         $options{'railalign'} = 'left';
                   8009:     }
                   8010:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8011:         my $function  = &get_users_function();
                   8012:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8013:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8014:             $options{'cursorcolor'} = '#00F';
                   8015:         }
                   8016:     }
                   8017:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8018:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8019:             $options{'cursoropacity'}='1.0';
                   8020:         }
                   8021:     } else {
                   8022:         $options{'cursoropacity'}='1.0';
                   8023:     }
                   8024:     if ($options{'cursorfixedheight'} eq 'none') {
                   8025:         delete($options{'cursorfixedheight'});
                   8026:     } else {
                   8027:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8028:     }
                   8029:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8030:         delete($options{'railoffset'});
                   8031:     }
                   8032:     my @niceoptions;
                   8033:     while (my($key,$value) = each(%options)) {
                   8034:         if ($value =~ /^\{.+\}$/) {
                   8035:             push(@niceoptions,$key.':'.$value);
                   8036:         } else {
                   8037:             push(@niceoptions,$key.':"'.$value.'"');
                   8038:         }
                   8039:     }
                   8040:     my $nicescroll_js = '
                   8041: $(document).ready(
                   8042:       function() {
                   8043:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8044:       }
                   8045: );
                   8046: ';
                   8047:     if ($framecheck) {
                   8048:         $nicescroll_js .= '
                   8049: function expand_div(caller) {
                   8050:     if (top === self) {
                   8051:         document.getElementById("'.$id.'").style.width = "auto";
                   8052:         document.getElementById("'.$id.'").style.height = "auto";
                   8053:     } else {
                   8054:         try {
                   8055:             if (parent.frames) {
                   8056:                 if (parent.frames.length > 1) {
                   8057:                     var framesrc = parent.frames[1].location.href;
                   8058:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8059:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8060:                         document.getElementById("'.$id.'").style.width = "auto";
                   8061:                         document.getElementById("'.$id.'").style.height = "auto";
                   8062:                     }
                   8063:                 }
                   8064:             }
                   8065:         } catch (e) {
                   8066:             return;
                   8067:         }
                   8068:     }
                   8069:     return;
                   8070: }
                   8071: ';
                   8072:     }
                   8073:     if ($needjsready) {
                   8074:         $nicescroll_js = '
                   8075: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8076:     } else {
                   8077:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8078:     }
                   8079:     return $nicescroll_js;
                   8080: }
                   8081: 
1.318     albertel 8082: sub simple_error_page {
1.1075.2.49  raeburn  8083:     my ($r,$title,$msg,$args) = @_;
                   8084:     if (ref($args) eq 'HASH') {
                   8085:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8086:     } else {
                   8087:         $msg = &mt($msg);
                   8088:     }
                   8089: 
1.318     albertel 8090:     my $page =
                   8091: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8092: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8093: 	&Apache::loncommon::end_page();
                   8094:     if (ref($r)) {
                   8095: 	$r->print($page);
1.327     albertel 8096: 	return;
1.318     albertel 8097:     }
                   8098:     return $page;
                   8099: }
1.347     albertel 8100: 
                   8101: {
1.610     albertel 8102:     my @row_count;
1.961     onken    8103: 
                   8104:     sub start_data_table_count {
                   8105:         unshift(@row_count, 0);
                   8106:         return;
                   8107:     }
                   8108: 
                   8109:     sub end_data_table_count {
                   8110:         shift(@row_count);
                   8111:         return;
                   8112:     }
                   8113: 
1.347     albertel 8114:     sub start_data_table {
1.1018    raeburn  8115: 	my ($add_class,$id) = @_;
1.422     albertel 8116: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8117:         my $table_id;
                   8118:         if (defined($id)) {
                   8119:             $table_id = ' id="'.$id.'"';
                   8120:         }
1.961     onken    8121: 	&start_data_table_count();
1.1018    raeburn  8122: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8123:     }
                   8124: 
                   8125:     sub end_data_table {
1.961     onken    8126: 	&end_data_table_count();
1.389     albertel 8127: 	return '</table>'."\n";;
1.347     albertel 8128:     }
                   8129: 
                   8130:     sub start_data_table_row {
1.974     wenzelju 8131: 	my ($add_class, $id) = @_;
1.610     albertel 8132: 	$row_count[0]++;
                   8133: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8134: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8135:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8136:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8137:     }
1.471     banghart 8138:     
                   8139:     sub continue_data_table_row {
1.974     wenzelju 8140: 	my ($add_class, $id) = @_;
1.610     albertel 8141: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8142: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8143:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8144:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8145:     }
1.347     albertel 8146: 
                   8147:     sub end_data_table_row {
1.389     albertel 8148: 	return '</tr>'."\n";;
1.347     albertel 8149:     }
1.367     www      8150: 
1.421     albertel 8151:     sub start_data_table_empty_row {
1.707     bisitz   8152: #	$row_count[0]++;
1.421     albertel 8153: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8154:     }
                   8155: 
                   8156:     sub end_data_table_empty_row {
                   8157: 	return '</tr>'."\n";;
                   8158:     }
                   8159: 
1.367     www      8160:     sub start_data_table_header_row {
1.389     albertel 8161: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8162:     }
                   8163: 
                   8164:     sub end_data_table_header_row {
1.389     albertel 8165: 	return '</tr>'."\n";;
1.367     www      8166:     }
1.890     droeschl 8167: 
                   8168:     sub data_table_caption {
                   8169:         my $caption = shift;
                   8170:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8171:     }
1.347     albertel 8172: }
                   8173: 
1.548     albertel 8174: =pod
                   8175: 
                   8176: =item * &inhibit_menu_check($arg)
                   8177: 
                   8178: Checks for a inhibitmenu state and generates output to preserve it
                   8179: 
                   8180: Inputs:         $arg - can be any of
                   8181:                      - undef - in which case the return value is a string 
                   8182:                                to add  into arguments list of a uri
                   8183:                      - 'input' - in which case the return value is a HTML
                   8184:                                  <form> <input> field of type hidden to
                   8185:                                  preserve the value
                   8186:                      - a url - in which case the return value is the url with
                   8187:                                the neccesary cgi args added to preserve the
                   8188:                                inhibitmenu state
                   8189:                      - a ref to a url - no return value, but the string is
                   8190:                                         updated to include the neccessary cgi
                   8191:                                         args to preserve the inhibitmenu state
                   8192: 
                   8193: =cut
                   8194: 
                   8195: sub inhibit_menu_check {
                   8196:     my ($arg) = @_;
                   8197:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8198:     if ($arg eq 'input') {
                   8199: 	if ($env{'form.inhibitmenu'}) {
                   8200: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8201: 	} else {
                   8202: 	    return
                   8203: 	}
                   8204:     }
                   8205:     if ($env{'form.inhibitmenu'}) {
                   8206: 	if (ref($arg)) {
                   8207: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8208: 	} elsif ($arg eq '') {
                   8209: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8210: 	} else {
                   8211: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8212: 	}
                   8213:     }
                   8214:     if (!ref($arg)) {
                   8215: 	return $arg;
                   8216:     }
                   8217: }
                   8218: 
1.251     albertel 8219: ###############################################
1.182     matthew  8220: 
                   8221: =pod
                   8222: 
1.549     albertel 8223: =back
                   8224: 
                   8225: =head1 User Information Routines
                   8226: 
                   8227: =over 4
                   8228: 
1.405     albertel 8229: =item * &get_users_function()
1.182     matthew  8230: 
                   8231: Used by &bodytag to determine the current users primary role.
                   8232: Returns either 'student','coordinator','admin', or 'author'.
                   8233: 
                   8234: =cut
                   8235: 
                   8236: ###############################################
                   8237: sub get_users_function {
1.815     tempelho 8238:     my $function = 'norole';
1.818     tempelho 8239:     if ($env{'request.role'}=~/^(st)/) {
                   8240:         $function='student';
                   8241:     }
1.907     raeburn  8242:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8243:         $function='coordinator';
                   8244:     }
1.258     albertel 8245:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8246:         $function='admin';
                   8247:     }
1.826     bisitz   8248:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8249:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8250:         $function='author';
                   8251:     }
                   8252:     return $function;
1.54      www      8253: }
1.99      www      8254: 
                   8255: ###############################################
                   8256: 
1.233     raeburn  8257: =pod
                   8258: 
1.821     raeburn  8259: =item * &show_course()
                   8260: 
                   8261: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8262: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8263: 
                   8264: Inputs:
                   8265: None
                   8266: 
                   8267: Outputs:
                   8268: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8269: 
                   8270: =cut
                   8271: 
                   8272: ###############################################
                   8273: sub show_course {
                   8274:     my $course = !$env{'user.adv'};
                   8275:     if (!$env{'user.adv'}) {
                   8276:         foreach my $env (keys(%env)) {
                   8277:             next if ($env !~ m/^user\.priv\./);
                   8278:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8279:                 $course = 0;
                   8280:                 last;
                   8281:             }
                   8282:         }
                   8283:     }
                   8284:     return $course;
                   8285: }
                   8286: 
                   8287: ###############################################
                   8288: 
                   8289: =pod
                   8290: 
1.542     raeburn  8291: =item * &check_user_status()
1.274     raeburn  8292: 
                   8293: Determines current status of supplied role for a
                   8294: specific user. Roles can be active, previous or future.
                   8295: 
                   8296: Inputs: 
                   8297: user's domain, user's username, course's domain,
1.375     raeburn  8298: course's number, optional section ID.
1.274     raeburn  8299: 
                   8300: Outputs:
                   8301: role status: active, previous or future. 
                   8302: 
                   8303: =cut
                   8304: 
                   8305: sub check_user_status {
1.412     raeburn  8306:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8307:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8308:     my @uroles = keys %userinfo;
                   8309:     my $srchstr;
                   8310:     my $active_chk = 'none';
1.412     raeburn  8311:     my $now = time;
1.274     raeburn  8312:     if (@uroles > 0) {
1.908     raeburn  8313:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8314:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8315:         } else {
1.412     raeburn  8316:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8317:         }
                   8318:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8319:             my $role_end = 0;
                   8320:             my $role_start = 0;
                   8321:             $active_chk = 'active';
1.412     raeburn  8322:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8323:                 $role_end = $1;
                   8324:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8325:                     $role_start = $1;
1.274     raeburn  8326:                 }
                   8327:             }
                   8328:             if ($role_start > 0) {
1.412     raeburn  8329:                 if ($now < $role_start) {
1.274     raeburn  8330:                     $active_chk = 'future';
                   8331:                 }
                   8332:             }
                   8333:             if ($role_end > 0) {
1.412     raeburn  8334:                 if ($now > $role_end) {
1.274     raeburn  8335:                     $active_chk = 'previous';
                   8336:                 }
                   8337:             }
                   8338:         }
                   8339:     }
                   8340:     return $active_chk;
                   8341: }
                   8342: 
                   8343: ###############################################
                   8344: 
                   8345: =pod
                   8346: 
1.405     albertel 8347: =item * &get_sections()
1.233     raeburn  8348: 
                   8349: Determines all the sections for a course including
                   8350: sections with students and sections containing other roles.
1.419     raeburn  8351: Incoming parameters: 
                   8352: 
                   8353: 1. domain
                   8354: 2. course number 
                   8355: 3. reference to array containing roles for which sections should 
                   8356: be gathered (optional).
                   8357: 4. reference to array containing status types for which sections 
                   8358: should be gathered (optional).
                   8359: 
                   8360: If the third argument is undefined, sections are gathered for any role. 
                   8361: If the fourth argument is undefined, sections are gathered for any status.
                   8362: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8363:  
1.374     raeburn  8364: Returns section hash (keys are section IDs, values are
                   8365: number of users in each section), subject to the
1.419     raeburn  8366: optional roles filter, optional status filter 
1.233     raeburn  8367: 
                   8368: =cut
                   8369: 
                   8370: ###############################################
                   8371: sub get_sections {
1.419     raeburn  8372:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8373:     if (!defined($cdom) || !defined($cnum)) {
                   8374:         my $cid =  $env{'request.course.id'};
                   8375: 
                   8376: 	return if (!defined($cid));
                   8377: 
                   8378:         $cdom = $env{'course.'.$cid.'.domain'};
                   8379:         $cnum = $env{'course.'.$cid.'.num'};
                   8380:     }
                   8381: 
                   8382:     my %sectioncount;
1.419     raeburn  8383:     my $now = time;
1.240     albertel 8384: 
1.1075.2.33  raeburn  8385:     my $check_students = 1;
                   8386:     my $only_students = 0;
                   8387:     if (ref($possible_roles) eq 'ARRAY') {
                   8388:         if (grep(/^st$/,@{$possible_roles})) {
                   8389:             if (@{$possible_roles} == 1) {
                   8390:                 $only_students = 1;
                   8391:             }
                   8392:         } else {
                   8393:             $check_students = 0;
                   8394:         }
                   8395:     }
                   8396: 
                   8397:     if ($check_students) {
1.276     albertel 8398: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8399: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8400: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8401:         my $start_index = &Apache::loncoursedata::CL_START();
                   8402:         my $end_index = &Apache::loncoursedata::CL_END();
                   8403:         my $status;
1.366     albertel 8404: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8405: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8406: 				                     $data->[$status_index],
                   8407:                                                      $data->[$start_index],
                   8408:                                                      $data->[$end_index]);
                   8409:             if ($stu_status eq 'Active') {
                   8410:                 $status = 'active';
                   8411:             } elsif ($end < $now) {
                   8412:                 $status = 'previous';
                   8413:             } elsif ($start > $now) {
                   8414:                 $status = 'future';
                   8415:             } 
                   8416: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8417:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8418:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8419: 		    $sectioncount{$section}++;
                   8420:                 }
1.240     albertel 8421: 	    }
                   8422: 	}
                   8423:     }
1.1075.2.33  raeburn  8424:     if ($only_students) {
                   8425:         return %sectioncount;
                   8426:     }
1.240     albertel 8427:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8428:     foreach my $user (sort(keys(%courseroles))) {
                   8429: 	if ($user !~ /^(\w{2})/) { next; }
                   8430: 	my ($role) = ($user =~ /^(\w{2})/);
                   8431: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8432: 	my ($section,$status);
1.240     albertel 8433: 	if ($role eq 'cr' &&
                   8434: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8435: 	    $section=$1;
                   8436: 	}
                   8437: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8438: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8439:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8440:         if ($end == -1 && $start == -1) {
                   8441:             next; #deleted role
                   8442:         }
                   8443:         if (!defined($possible_status)) { 
                   8444:             $sectioncount{$section}++;
                   8445:         } else {
                   8446:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8447:                 $status = 'active';
                   8448:             } elsif ($end < $now) {
                   8449:                 $status = 'future';
                   8450:             } elsif ($start > $now) {
                   8451:                 $status = 'previous';
                   8452:             }
                   8453:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8454:                 $sectioncount{$section}++;
                   8455:             }
                   8456:         }
1.233     raeburn  8457:     }
1.366     albertel 8458:     return %sectioncount;
1.233     raeburn  8459: }
                   8460: 
1.274     raeburn  8461: ###############################################
1.294     raeburn  8462: 
                   8463: =pod
1.405     albertel 8464: 
                   8465: =item * &get_course_users()
                   8466: 
1.275     raeburn  8467: Retrieves usernames:domains for users in the specified course
                   8468: with specific role(s), and access status. 
                   8469: 
                   8470: Incoming parameters:
1.277     albertel 8471: 1. course domain
                   8472: 2. course number
                   8473: 3. access status: users must have - either active, 
1.275     raeburn  8474: previous, future, or all.
1.277     albertel 8475: 4. reference to array of permissible roles
1.288     raeburn  8476: 5. reference to array of section restrictions (optional)
                   8477: 6. reference to results object (hash of hashes).
                   8478: 7. reference to optional userdata hash
1.609     raeburn  8479: 8. reference to optional statushash
1.630     raeburn  8480: 9. flag if privileged users (except those set to unhide in
                   8481:    course settings) should be excluded    
1.609     raeburn  8482: Keys of top level results hash are roles.
1.275     raeburn  8483: Keys of inner hashes are username:domain, with 
                   8484: values set to access type.
1.288     raeburn  8485: Optional userdata hash returns an array with arguments in the 
                   8486: same order as loncoursedata::get_classlist() for student data.
                   8487: 
1.609     raeburn  8488: Optional statushash returns
                   8489: 
1.288     raeburn  8490: Entries for end, start, section and status are blank because
                   8491: of the possibility of multiple values for non-student roles.
                   8492: 
1.275     raeburn  8493: =cut
1.405     albertel 8494: 
1.275     raeburn  8495: ###############################################
1.405     albertel 8496: 
1.275     raeburn  8497: sub get_course_users {
1.630     raeburn  8498:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8499:     my %idx = ();
1.419     raeburn  8500:     my %seclists;
1.288     raeburn  8501: 
                   8502:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8503:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8504:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8505:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8506:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8507:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8508:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8509:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8510: 
1.290     albertel 8511:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8512:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8513:         my $now = time;
1.277     albertel 8514:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8515:             my $match = 0;
1.412     raeburn  8516:             my $secmatch = 0;
1.419     raeburn  8517:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8518:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8519:             if ($section eq '') {
                   8520:                 $section = 'none';
                   8521:             }
1.291     albertel 8522:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8523:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8524:                     $secmatch = 1;
                   8525:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8526:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8527:                         $secmatch = 1;
                   8528:                     }
                   8529:                 } else {  
1.419     raeburn  8530: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8531: 		        $secmatch = 1;
                   8532:                     }
1.290     albertel 8533: 		}
1.412     raeburn  8534:                 if (!$secmatch) {
                   8535:                     next;
                   8536:                 }
1.419     raeburn  8537:             }
1.275     raeburn  8538:             if (defined($$types{'active'})) {
1.288     raeburn  8539:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8540:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8541:                     $match = 1;
1.275     raeburn  8542:                 }
                   8543:             }
                   8544:             if (defined($$types{'previous'})) {
1.609     raeburn  8545:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8546:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8547:                     $match = 1;
1.275     raeburn  8548:                 }
                   8549:             }
                   8550:             if (defined($$types{'future'})) {
1.609     raeburn  8551:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8552:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8553:                     $match = 1;
1.275     raeburn  8554:                 }
                   8555:             }
1.609     raeburn  8556:             if ($match) {
                   8557:                 push(@{$seclists{$student}},$section);
                   8558:                 if (ref($userdata) eq 'HASH') {
                   8559:                     $$userdata{$student} = $$classlist{$student};
                   8560:                 }
                   8561:                 if (ref($statushash) eq 'HASH') {
                   8562:                     $statushash->{$student}{'st'}{$section} = $status;
                   8563:                 }
1.288     raeburn  8564:             }
1.275     raeburn  8565:         }
                   8566:     }
1.412     raeburn  8567:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8568:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8569:         my $now = time;
1.609     raeburn  8570:         my %displaystatus = ( previous => 'Expired',
                   8571:                               active   => 'Active',
                   8572:                               future   => 'Future',
                   8573:                             );
1.1075.2.36  raeburn  8574:         my (%nothide,@possdoms);
1.630     raeburn  8575:         if ($hidepriv) {
                   8576:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8577:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8578:                 if ($user !~ /:/) {
                   8579:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8580:                 } else {
                   8581:                     $nothide{$user} = 1;
                   8582:                 }
                   8583:             }
1.1075.2.36  raeburn  8584:             my @possdoms = ($cdom);
                   8585:             if ($coursehash{'checkforpriv'}) {
                   8586:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8587:             }
1.630     raeburn  8588:         }
1.439     raeburn  8589:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8590:             my $match = 0;
1.412     raeburn  8591:             my $secmatch = 0;
1.439     raeburn  8592:             my $status;
1.412     raeburn  8593:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8594:             $user =~ s/:$//;
1.439     raeburn  8595:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8596:             if ($end == -1 || $start == -1) {
                   8597:                 next;
                   8598:             }
                   8599:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8600:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8601:                 my ($uname,$udom) = split(/:/,$user);
                   8602:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8603:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8604:                         $secmatch = 1;
                   8605:                     } elsif ($usec eq '') {
1.420     albertel 8606:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8607:                             $secmatch = 1;
                   8608:                         }
                   8609:                     } else {
                   8610:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8611:                             $secmatch = 1;
                   8612:                         }
                   8613:                     }
                   8614:                     if (!$secmatch) {
                   8615:                         next;
                   8616:                     }
1.288     raeburn  8617:                 }
1.419     raeburn  8618:                 if ($usec eq '') {
                   8619:                     $usec = 'none';
                   8620:                 }
1.275     raeburn  8621:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8622:                     if ($hidepriv) {
1.1075.2.36  raeburn  8623:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8624:                             (!$nothide{$uname.':'.$udom})) {
                   8625:                             next;
                   8626:                         }
                   8627:                     }
1.503     raeburn  8628:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8629:                         $status = 'previous';
                   8630:                     } elsif ($start > $now) {
                   8631:                         $status = 'future';
                   8632:                     } else {
                   8633:                         $status = 'active';
                   8634:                     }
1.277     albertel 8635:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8636:                         if ($status eq $type) {
1.420     albertel 8637:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8638:                                 push(@{$$users{$role}{$user}},$type);
                   8639:                             }
1.288     raeburn  8640:                             $match = 1;
                   8641:                         }
                   8642:                     }
1.419     raeburn  8643:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8644:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8645: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8646:                         }
1.420     albertel 8647:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8648:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8649:                         }
1.609     raeburn  8650:                         if (ref($statushash) eq 'HASH') {
                   8651:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8652:                         }
1.275     raeburn  8653:                     }
                   8654:                 }
                   8655:             }
                   8656:         }
1.290     albertel 8657:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8658:             if ((defined($cdom)) && (defined($cnum))) {
                   8659:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8660:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8661:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8662:                     next if ($owner eq '');
                   8663:                     my ($ownername,$ownerdom);
                   8664:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8665:                         $ownername = $1;
                   8666:                         $ownerdom = $2;
                   8667:                     } else {
                   8668:                         $ownername = $owner;
                   8669:                         $ownerdom = $cdom;
                   8670:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8671:                     }
                   8672:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8673:                     if (defined($userdata) && 
1.609     raeburn  8674: 			!exists($$userdata{$owner})) {
                   8675: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8676:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8677:                             push(@{$seclists{$owner}},'none');
                   8678:                         }
                   8679:                         if (ref($statushash) eq 'HASH') {
                   8680:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8681:                         }
1.290     albertel 8682: 		    }
1.279     raeburn  8683:                 }
                   8684:             }
                   8685:         }
1.419     raeburn  8686:         foreach my $user (keys(%seclists)) {
                   8687:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8688:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8689:         }
1.275     raeburn  8690:     }
                   8691:     return;
                   8692: }
                   8693: 
1.288     raeburn  8694: sub get_user_info {
                   8695:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8696:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8697: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8698:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8699:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8700:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8701:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8702:     return;
                   8703: }
1.275     raeburn  8704: 
1.472     raeburn  8705: ###############################################
                   8706: 
                   8707: =pod
                   8708: 
                   8709: =item * &get_user_quota()
                   8710: 
1.1075.2.41  raeburn  8711: Retrieves quota assigned for storage of user files.
                   8712: Default is to report quota for portfolio files.
1.472     raeburn  8713: 
                   8714: Incoming parameters:
                   8715: 1. user's username
                   8716: 2. user's domain
1.1075.2.41  raeburn  8717: 3. quota name - portfolio, author, or course
                   8718:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  8719: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  8720:    course
1.472     raeburn  8721: 
                   8722: Returns:
1.1075.2.58  raeburn  8723: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  8724: 2. (Optional) Type of setting: custom or default
                   8725:    (individually assigned or default for user's 
                   8726:    institutional status).
                   8727: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8728:    or student - types as defined in localenroll::inst_usertypes 
                   8729:    for user's domain, which determines default quota for user.
                   8730: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8731: 
                   8732: If a value has been stored in the user's environment, 
1.536     raeburn  8733: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  8734: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8735: 
                   8736: =cut
                   8737: 
                   8738: ###############################################
                   8739: 
                   8740: 
                   8741: sub get_user_quota {
1.1075.2.42  raeburn  8742:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  8743:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8744:     if (!defined($udom)) {
                   8745:         $udom = $env{'user.domain'};
                   8746:     }
                   8747:     if (!defined($uname)) {
                   8748:         $uname = $env{'user.name'};
                   8749:     }
                   8750:     if (($udom eq '' || $uname eq '') ||
                   8751:         ($udom eq 'public') && ($uname eq 'public')) {
                   8752:         $quota = 0;
1.536     raeburn  8753:         $quotatype = 'default';
                   8754:         $defquota = 0; 
1.472     raeburn  8755:     } else {
1.536     raeburn  8756:         my $inststatus;
1.1075.2.41  raeburn  8757:         if ($quotaname eq 'course') {
                   8758:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   8759:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   8760:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   8761:             } else {
                   8762:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   8763:                 $quota = $cenv{'internal.uploadquota'};
                   8764:             }
1.536     raeburn  8765:         } else {
1.1075.2.41  raeburn  8766:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8767:                 if ($quotaname eq 'author') {
                   8768:                     $quota = $env{'environment.authorquota'};
                   8769:                 } else {
                   8770:                     $quota = $env{'environment.portfolioquota'};
                   8771:                 }
                   8772:                 $inststatus = $env{'environment.inststatus'};
                   8773:             } else {
                   8774:                 my %userenv = 
                   8775:                     &Apache::lonnet::get('environment',['portfolioquota',
                   8776:                                          'authorquota','inststatus'],$udom,$uname);
                   8777:                 my ($tmp) = keys(%userenv);
                   8778:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8779:                     if ($quotaname eq 'author') {
                   8780:                         $quota = $userenv{'authorquota'};
                   8781:                     } else {
                   8782:                         $quota = $userenv{'portfolioquota'};
                   8783:                     }
                   8784:                     $inststatus = $userenv{'inststatus'};
                   8785:                 } else {
                   8786:                     undef(%userenv);
                   8787:                 }
                   8788:             }
                   8789:         }
                   8790:         if ($quota eq '' || wantarray) {
                   8791:             if ($quotaname eq 'course') {
                   8792:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  8793:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   8794:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  8795:                     $defquota = $domdefs{$crstype.'quota'};
                   8796:                 }
                   8797:                 if ($defquota eq '') {
                   8798:                     $defquota = 500;
                   8799:                 }
1.1075.2.41  raeburn  8800:             } else {
                   8801:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   8802:             }
                   8803:             if ($quota eq '') {
                   8804:                 $quota = $defquota;
                   8805:                 $quotatype = 'default';
                   8806:             } else {
                   8807:                 $quotatype = 'custom';
                   8808:             }
1.472     raeburn  8809:         }
                   8810:     }
1.536     raeburn  8811:     if (wantarray) {
                   8812:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8813:     } else {
                   8814:         return $quota;
                   8815:     }
1.472     raeburn  8816: }
                   8817: 
                   8818: ###############################################
                   8819: 
                   8820: =pod
                   8821: 
                   8822: =item * &default_quota()
                   8823: 
1.536     raeburn  8824: Retrieves default quota assigned for storage of user portfolio files,
                   8825: given an (optional) user's institutional status.
1.472     raeburn  8826: 
                   8827: Incoming parameters:
1.1075.2.42  raeburn  8828: 
1.472     raeburn  8829: 1. domain
1.536     raeburn  8830: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8831:    status types (e.g., faculty, staff, student etc.)
                   8832:    which apply to the user for whom the default is being retrieved.
                   8833:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  8834:    default quota will be returned.
                   8835: 3.  quota name - portfolio, author, or course
                   8836:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  8837: 
                   8838: Returns:
1.1075.2.42  raeburn  8839: 
1.1075.2.58  raeburn  8840: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  8841: 2. (Optional) institutional type which determined the value of the
                   8842:    default quota.
1.472     raeburn  8843: 
                   8844: If a value has been stored in the domain's configuration db,
                   8845: it will return that, otherwise it returns 20 (for backwards 
                   8846: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  8847: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  8848: 
1.536     raeburn  8849: If the user's status includes multiple types (e.g., staff and student),
                   8850: the largest default quota which applies to the user determines the
                   8851: default quota returned.
                   8852: 
1.472     raeburn  8853: =cut
                   8854: 
                   8855: ###############################################
                   8856: 
                   8857: 
                   8858: sub default_quota {
1.1075.2.41  raeburn  8859:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  8860:     my ($defquota,$settingstatus);
                   8861:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8862:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  8863:     my $key = 'defaultquota';
                   8864:     if ($quotaname eq 'author') {
                   8865:         $key = 'authorquota';
                   8866:     }
1.622     raeburn  8867:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8868:         if ($inststatus ne '') {
1.765     raeburn  8869:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8870:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  8871:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   8872:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  8873:                         if ($defquota eq '') {
1.1075.2.41  raeburn  8874:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8875:                             $settingstatus = $item;
1.1075.2.41  raeburn  8876:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   8877:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  8878:                             $settingstatus = $item;
                   8879:                         }
                   8880:                     }
1.1075.2.41  raeburn  8881:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  8882:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8883:                         if ($defquota eq '') {
                   8884:                             $defquota = $quotahash{'quotas'}{$item};
                   8885:                             $settingstatus = $item;
                   8886:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8887:                             $defquota = $quotahash{'quotas'}{$item};
                   8888:                             $settingstatus = $item;
                   8889:                         }
1.536     raeburn  8890:                     }
                   8891:                 }
                   8892:             }
                   8893:         }
                   8894:         if ($defquota eq '') {
1.1075.2.41  raeburn  8895:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   8896:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   8897:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  8898:                 $defquota = $quotahash{'quotas'}{'default'};
                   8899:             }
1.536     raeburn  8900:             $settingstatus = 'default';
1.1075.2.42  raeburn  8901:             if ($defquota eq '') {
                   8902:                 if ($quotaname eq 'author') {
                   8903:                     $defquota = 500;
                   8904:                 }
                   8905:             }
1.536     raeburn  8906:         }
                   8907:     } else {
                   8908:         $settingstatus = 'default';
1.1075.2.41  raeburn  8909:         if ($quotaname eq 'author') {
                   8910:             $defquota = 500;
                   8911:         } else {
                   8912:             $defquota = 20;
                   8913:         }
1.536     raeburn  8914:     }
                   8915:     if (wantarray) {
                   8916:         return ($defquota,$settingstatus);
1.472     raeburn  8917:     } else {
1.536     raeburn  8918:         return $defquota;
1.472     raeburn  8919:     }
                   8920: }
                   8921: 
1.1075.2.41  raeburn  8922: ###############################################
                   8923: 
                   8924: =pod
                   8925: 
1.1075.2.42  raeburn  8926: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  8927: 
                   8928: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  8929: of existing file within authoring space will cause quota for the authoring
                   8930: space to be exceeded.
                   8931: 
                   8932: Same, if upload of a file directly to a course/community via Course Editor
                   8933: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  8934: 
1.1075.2.61  raeburn  8935: Inputs: 7 
1.1075.2.42  raeburn  8936: 1. username or coursenum
1.1075.2.41  raeburn  8937: 2. domain
1.1075.2.42  raeburn  8938: 3. context ('author' or 'course')
1.1075.2.41  raeburn  8939: 4. filename of file for which action is being requested
                   8940: 5. filesize (kB) of file
                   8941: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  8942: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  8943: 
                   8944: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   8945:          otherwise return null.
                   8946: 
1.1075.2.42  raeburn  8947: =back
                   8948: 
1.1075.2.41  raeburn  8949: =cut
                   8950: 
1.1075.2.42  raeburn  8951: sub excess_filesize_warning {
1.1075.2.59  raeburn  8952:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  8953:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  8954:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  8955:     if ($context eq 'author') {
                   8956:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   8957:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   8958:     } else {
                   8959:         foreach my $subdir ('docs','supplemental') {
                   8960:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   8961:         }
                   8962:     }
1.1075.2.41  raeburn  8963:     $disk_quota = int($disk_quota * 1000);
                   8964:     if (($current_disk_usage + $filesize) > $disk_quota) {
                   8965:         return '<p><span class="LC_warning">'.
                   8966:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
                   8967:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</span>'.
                   8968:                '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   8969:                             $disk_quota,$current_disk_usage).
                   8970:                '</p>';
                   8971:     }
                   8972:     return;
                   8973: }
                   8974: 
                   8975: ###############################################
                   8976: 
                   8977: 
1.384     raeburn  8978: sub get_secgrprole_info {
                   8979:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8980:     my %sections_count = &get_sections($cdom,$cnum);
                   8981:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8982:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8983:     my @groups = sort(keys(%curr_groups));
                   8984:     my $allroles = [];
                   8985:     my $rolehash;
                   8986:     my $accesshash = {
                   8987:                      active => 'Currently has access',
                   8988:                      future => 'Will have future access',
                   8989:                      previous => 'Previously had access',
                   8990:                   };
                   8991:     if ($needroles) {
                   8992:         $rolehash = {'all' => 'all'};
1.385     albertel 8993:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8994: 	if (&Apache::lonnet::error(%user_roles)) {
                   8995: 	    undef(%user_roles);
                   8996: 	}
                   8997:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8998:             my ($role)=split(/\:/,$item,2);
                   8999:             if ($role eq 'cr') { next; }
                   9000:             if ($role =~ /^cr/) {
                   9001:                 $$rolehash{$role} = (split('/',$role))[3];
                   9002:             } else {
                   9003:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9004:             }
                   9005:         }
                   9006:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9007:             push(@{$allroles},$key);
                   9008:         }
                   9009:         push (@{$allroles},'st');
                   9010:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9011:     }
                   9012:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9013: }
                   9014: 
1.555     raeburn  9015: sub user_picker {
1.994     raeburn  9016:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9017:     my $currdom = $dom;
                   9018:     my %curr_selected = (
                   9019:                         srchin => 'dom',
1.580     raeburn  9020:                         srchby => 'lastname',
1.555     raeburn  9021:                       );
                   9022:     my $srchterm;
1.625     raeburn  9023:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9024:         if ($srch->{'srchby'} ne '') {
                   9025:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9026:         }
                   9027:         if ($srch->{'srchin'} ne '') {
                   9028:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9029:         }
                   9030:         if ($srch->{'srchtype'} ne '') {
                   9031:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9032:         }
                   9033:         if ($srch->{'srchdomain'} ne '') {
                   9034:             $currdom = $srch->{'srchdomain'};
                   9035:         }
                   9036:         $srchterm = $srch->{'srchterm'};
                   9037:     }
                   9038:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9039:                     'usr'       => 'Search criteria',
1.563     raeburn  9040:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9041:                     'uname'     => 'username',
                   9042:                     'lastname'  => 'last name',
1.555     raeburn  9043:                     'lastfirst' => 'last name, first name',
1.558     albertel 9044:                     'crs'       => 'in this course',
1.576     raeburn  9045:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9046:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9047:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9048:                     'exact'     => 'is',
                   9049:                     'contains'  => 'contains',
1.569     raeburn  9050:                     'begins'    => 'begins with',
1.571     raeburn  9051:                     'youm'      => "You must include some text to search for.",
                   9052:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9053:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9054:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9055:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9056:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9057:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9058:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9059:                                        );
1.563     raeburn  9060:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9061:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9062: 
                   9063:     my @srchins = ('crs','dom','alc','instd');
                   9064: 
                   9065:     foreach my $option (@srchins) {
                   9066:         # FIXME 'alc' option unavailable until 
                   9067:         #       loncreateuser::print_user_query_page()
                   9068:         #       has been completed.
                   9069:         next if ($option eq 'alc');
1.880     raeburn  9070:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9071:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9072:         if ($curr_selected{'srchin'} eq $option) {
                   9073:             $srchinsel .= ' 
                   9074:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9075:         } else {
                   9076:             $srchinsel .= '
                   9077:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9078:         }
1.555     raeburn  9079:     }
1.563     raeburn  9080:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9081: 
                   9082:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9083:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9084:         if ($curr_selected{'srchby'} eq $option) {
                   9085:             $srchbysel .= '
                   9086:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9087:         } else {
                   9088:             $srchbysel .= '
                   9089:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9090:          }
                   9091:     }
                   9092:     $srchbysel .= "\n  </select>\n";
                   9093: 
                   9094:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9095:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9096:         if ($curr_selected{'srchtype'} eq $option) {
                   9097:             $srchtypesel .= '
                   9098:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9099:         } else {
                   9100:             $srchtypesel .= '
                   9101:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9102:         }
                   9103:     }
                   9104:     $srchtypesel .= "\n  </select>\n";
                   9105: 
1.558     albertel 9106:     my ($newuserscript,$new_user_create);
1.994     raeburn  9107:     my $context_dom = $env{'request.role.domain'};
                   9108:     if ($context eq 'requestcrs') {
                   9109:         if ($env{'form.coursedom'} ne '') { 
                   9110:             $context_dom = $env{'form.coursedom'};
                   9111:         }
                   9112:     }
1.556     raeburn  9113:     if ($forcenewuser) {
1.576     raeburn  9114:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9115:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9116:                 if ($cancreate) {
                   9117:                     $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>';
                   9118:                 } else {
1.799     bisitz   9119:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9120:                     my %usertypetext = (
                   9121:                         official   => 'institutional',
                   9122:                         unofficial => 'non-institutional',
                   9123:                     );
1.799     bisitz   9124:                     $new_user_create = '<p class="LC_warning">'
                   9125:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9126:                                       .' '
                   9127:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9128:                                           ,'<a href="'.$helplink.'">','</a>')
                   9129:                                       .'</p><br />';
1.627     raeburn  9130:                 }
1.576     raeburn  9131:             }
                   9132:         }
                   9133: 
1.556     raeburn  9134:         $newuserscript = <<"ENDSCRIPT";
                   9135: 
1.570     raeburn  9136: function setSearch(createnew,callingForm) {
1.556     raeburn  9137:     if (createnew == 1) {
1.570     raeburn  9138:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9139:             if (callingForm.srchby.options[i].value == 'uname') {
                   9140:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9141:             }
                   9142:         }
1.570     raeburn  9143:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9144:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9145: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9146:             }
                   9147:         }
1.570     raeburn  9148:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9149:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9150:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9151:             }
                   9152:         }
1.570     raeburn  9153:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9154:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9155:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9156:             }
                   9157:         }
                   9158:     }
                   9159: }
                   9160: ENDSCRIPT
1.558     albertel 9161: 
1.556     raeburn  9162:     }
                   9163: 
1.555     raeburn  9164:     my $output = <<"END_BLOCK";
1.556     raeburn  9165: <script type="text/javascript">
1.824     bisitz   9166: // <![CDATA[
1.570     raeburn  9167: function validateEntry(callingForm) {
1.558     albertel 9168: 
1.556     raeburn  9169:     var checkok = 1;
1.558     albertel 9170:     var srchin;
1.570     raeburn  9171:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9172: 	if ( callingForm.srchin[i].checked ) {
                   9173: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9174: 	}
                   9175:     }
                   9176: 
1.570     raeburn  9177:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9178:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9179:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9180:     var srchterm =  callingForm.srchterm.value;
                   9181:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9182:     var msg = "";
                   9183: 
                   9184:     if (srchterm == "") {
                   9185:         checkok = 0;
1.571     raeburn  9186:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9187:     }
                   9188: 
1.569     raeburn  9189:     if (srchtype== 'begins') {
                   9190:         if (srchterm.length < 2) {
                   9191:             checkok = 0;
1.571     raeburn  9192:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9193:         }
                   9194:     }
                   9195: 
1.556     raeburn  9196:     if (srchtype== 'contains') {
                   9197:         if (srchterm.length < 3) {
                   9198:             checkok = 0;
1.571     raeburn  9199:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9200:         }
                   9201:     }
                   9202:     if (srchin == 'instd') {
                   9203:         if (srchdomain == '') {
                   9204:             checkok = 0;
1.571     raeburn  9205:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9206:         }
                   9207:     }
                   9208:     if (srchin == 'dom') {
                   9209:         if (srchdomain == '') {
                   9210:             checkok = 0;
1.571     raeburn  9211:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9212:         }
                   9213:     }
                   9214:     if (srchby == 'lastfirst') {
                   9215:         if (srchterm.indexOf(",") == -1) {
                   9216:             checkok = 0;
1.571     raeburn  9217:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9218:         }
                   9219:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9220:             checkok = 0;
1.571     raeburn  9221:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9222:         }
                   9223:     }
                   9224:     if (checkok == 0) {
1.571     raeburn  9225:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9226:         return;
                   9227:     }
                   9228:     if (checkok == 1) {
1.570     raeburn  9229:         callingForm.submit();
1.556     raeburn  9230:     }
                   9231: }
                   9232: 
                   9233: $newuserscript
                   9234: 
1.824     bisitz   9235: // ]]>
1.556     raeburn  9236: </script>
1.558     albertel 9237: 
                   9238: $new_user_create
                   9239: 
1.555     raeburn  9240: END_BLOCK
1.558     albertel 9241: 
1.876     raeburn  9242:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9243:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9244:                $domform.
                   9245:                &Apache::lonhtmlcommon::row_closure().
                   9246:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9247:                $srchbysel.
                   9248:                $srchtypesel. 
                   9249:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9250:                $srchinsel.
                   9251:                &Apache::lonhtmlcommon::row_closure(1). 
                   9252:                &Apache::lonhtmlcommon::end_pick_box().
                   9253:                '<br />';
1.555     raeburn  9254:     return $output;
                   9255: }
                   9256: 
1.612     raeburn  9257: sub user_rule_check {
1.615     raeburn  9258:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9259:     my $response;
                   9260:     if (ref($usershash) eq 'HASH') {
                   9261:         foreach my $user (keys(%{$usershash})) {
                   9262:             my ($uname,$udom) = split(/:/,$user);
                   9263:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9264:             my ($id,$newuser);
1.612     raeburn  9265:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9266:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9267:                 $id = $usershash->{$user}->{'id'};
                   9268:             }
                   9269:             my $inst_response;
                   9270:             if (ref($checks) eq 'HASH') {
                   9271:                 if (defined($checks->{'username'})) {
1.615     raeburn  9272:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9273:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9274:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9275:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9276:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9277:                 }
1.615     raeburn  9278:             } else {
                   9279:                 ($inst_response,%{$inst_results->{$user}}) =
                   9280:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9281:                 return;
1.612     raeburn  9282:             }
1.615     raeburn  9283:             if (!$got_rules->{$udom}) {
1.612     raeburn  9284:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9285:                                                   ['usercreation'],$udom);
                   9286:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9287:                     foreach my $item ('username','id') {
1.612     raeburn  9288:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9289:                             $$curr_rules{$udom}{$item} = 
                   9290:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9291:                         }
                   9292:                     }
                   9293:                 }
1.615     raeburn  9294:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9295:             }
1.612     raeburn  9296:             foreach my $item (keys(%{$checks})) {
                   9297:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9298:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9299:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9300:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9301:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9302:                                 if ($rule_check{$rule}) {
                   9303:                                     $$rulematch{$user}{$item} = $rule;
                   9304:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9305:                                         if (ref($inst_results) eq 'HASH') {
                   9306:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9307:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9308:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9309:                                                 }
1.612     raeburn  9310:                                             }
                   9311:                                         }
1.615     raeburn  9312:                                     }
                   9313:                                     last;
1.585     raeburn  9314:                                 }
                   9315:                             }
                   9316:                         }
                   9317:                     }
                   9318:                 }
                   9319:             }
                   9320:         }
                   9321:     }
1.612     raeburn  9322:     return;
                   9323: }
                   9324: 
                   9325: sub user_rule_formats {
                   9326:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9327:     my %text = ( 
                   9328:                  'username' => 'Usernames',
                   9329:                  'id'       => 'IDs',
                   9330:                );
                   9331:     my $output;
                   9332:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9333:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9334:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9335:             $output = '<br />'.
                   9336:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9337:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9338:                       ' <ul>';
1.612     raeburn  9339:             foreach my $rule (@{$ruleorder}) {
                   9340:                 if (ref($curr_rules) eq 'ARRAY') {
                   9341:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9342:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9343:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9344:                                         $rules->{$rule}{'desc'}.'</li>';
                   9345:                         }
                   9346:                     }
                   9347:                 }
                   9348:             }
                   9349:             $output .= '</ul>';
                   9350:         }
                   9351:     }
                   9352:     return $output;
                   9353: }
                   9354: 
                   9355: sub instrule_disallow_msg {
1.615     raeburn  9356:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9357:     my $response;
                   9358:     my %text = (
                   9359:                   item   => 'username',
                   9360:                   items  => 'usernames',
                   9361:                   match  => 'matches',
                   9362:                   do     => 'does',
                   9363:                   action => 'a username',
                   9364:                   one    => 'one',
                   9365:                );
                   9366:     if ($count > 1) {
                   9367:         $text{'item'} = 'usernames';
                   9368:         $text{'match'} ='match';
                   9369:         $text{'do'} = 'do';
                   9370:         $text{'action'} = 'usernames',
                   9371:         $text{'one'} = 'ones';
                   9372:     }
                   9373:     if ($checkitem eq 'id') {
                   9374:         $text{'items'} = 'IDs';
                   9375:         $text{'item'} = 'ID';
                   9376:         $text{'action'} = 'an ID';
1.615     raeburn  9377:         if ($count > 1) {
                   9378:             $text{'item'} = 'IDs';
                   9379:             $text{'action'} = 'IDs';
                   9380:         }
1.612     raeburn  9381:     }
1.674     bisitz   9382:     $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  9383:     if ($mode eq 'upload') {
                   9384:         if ($checkitem eq 'username') {
                   9385:             $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'}.");
                   9386:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9387:             $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  9388:         }
1.669     raeburn  9389:     } elsif ($mode eq 'selfcreate') {
                   9390:         if ($checkitem eq 'id') {
                   9391:             $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.");
                   9392:         }
1.615     raeburn  9393:     } else {
                   9394:         if ($checkitem eq 'username') {
                   9395:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9396:         } elsif ($checkitem eq 'id') {
                   9397:             $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.");
                   9398:         }
1.612     raeburn  9399:     }
                   9400:     return $response;
1.585     raeburn  9401: }
                   9402: 
1.624     raeburn  9403: sub personal_data_fieldtitles {
                   9404:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9405:                         id => 'Student/Employee ID',
                   9406:                         permanentemail => 'E-mail address',
                   9407:                         lastname => 'Last Name',
                   9408:                         firstname => 'First Name',
                   9409:                         middlename => 'Middle Name',
                   9410:                         generation => 'Generation',
                   9411:                         gen => 'Generation',
1.765     raeburn  9412:                         inststatus => 'Affiliation',
1.624     raeburn  9413:                    );
                   9414:     return %fieldtitles;
                   9415: }
                   9416: 
1.642     raeburn  9417: sub sorted_inst_types {
                   9418:     my ($dom) = @_;
                   9419:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9420:     my $othertitle = &mt('All users');
                   9421:     if ($env{'request.course.id'}) {
1.668     raeburn  9422:         $othertitle  = &mt('Any users');
1.642     raeburn  9423:     }
                   9424:     my @types;
                   9425:     if (ref($order) eq 'ARRAY') {
                   9426:         @types = @{$order};
                   9427:     }
                   9428:     if (@types == 0) {
                   9429:         if (ref($usertypes) eq 'HASH') {
                   9430:             @types = sort(keys(%{$usertypes}));
                   9431:         }
                   9432:     }
                   9433:     if (keys(%{$usertypes}) > 0) {
                   9434:         $othertitle = &mt('Other users');
                   9435:     }
                   9436:     return ($othertitle,$usertypes,\@types);
                   9437: }
                   9438: 
1.645     raeburn  9439: sub get_institutional_codes {
                   9440:     my ($settings,$allcourses,$LC_code) = @_;
                   9441: # Get complete list of course sections to update
                   9442:     my @currsections = ();
                   9443:     my @currxlists = ();
                   9444:     my $coursecode = $$settings{'internal.coursecode'};
                   9445: 
                   9446:     if ($$settings{'internal.sectionnums'} ne '') {
                   9447:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9448:     }
                   9449: 
                   9450:     if ($$settings{'internal.crosslistings'} ne '') {
                   9451:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9452:     }
                   9453: 
                   9454:     if (@currxlists > 0) {
                   9455:         foreach (@currxlists) {
                   9456:             if (m/^([^:]+):(\w*)$/) {
                   9457:                 unless (grep/^$1$/,@{$allcourses}) {
                   9458:                     push @{$allcourses},$1;
                   9459:                     $$LC_code{$1} = $2;
                   9460:                 }
                   9461:             }
                   9462:         }
                   9463:     }
                   9464:  
                   9465:     if (@currsections > 0) {
                   9466:         foreach (@currsections) {
                   9467:             if (m/^(\w+):(\w*)$/) {
                   9468:                 my $sec = $coursecode.$1;
                   9469:                 my $lc_sec = $2;
                   9470:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9471:                     push @{$allcourses},$sec;
                   9472:                     $$LC_code{$sec} = $lc_sec;
                   9473:                 }
                   9474:             }
                   9475:         }
                   9476:     }
                   9477:     return;
                   9478: }
                   9479: 
1.971     raeburn  9480: sub get_standard_codeitems {
                   9481:     return ('Year','Semester','Department','Number','Section');
                   9482: }
                   9483: 
1.112     bowersj2 9484: =pod
                   9485: 
1.780     raeburn  9486: =head1 Slot Helpers
                   9487: 
                   9488: =over 4
                   9489: 
                   9490: =item * sorted_slots()
                   9491: 
1.1040    raeburn  9492: Sorts an array of slot names in order of an optional sort key,
                   9493: default sort is by slot start time (earliest first). 
1.780     raeburn  9494: 
                   9495: Inputs:
                   9496: 
                   9497: =over 4
                   9498: 
                   9499: slotsarr  - Reference to array of unsorted slot names.
                   9500: 
                   9501: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9502: 
1.1040    raeburn  9503: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9504: 
1.549     albertel 9505: =back
                   9506: 
1.780     raeburn  9507: Returns:
                   9508: 
                   9509: =over 4
                   9510: 
1.1040    raeburn  9511: sorted   - An array of slot names sorted by a specified sort key 
                   9512:            (default sort key is start time of the slot).
1.780     raeburn  9513: 
                   9514: =back
                   9515: 
                   9516: =cut
                   9517: 
                   9518: 
                   9519: sub sorted_slots {
1.1040    raeburn  9520:     my ($slotsarr,$slots,$sortkey) = @_;
                   9521:     if ($sortkey eq '') {
                   9522:         $sortkey = 'starttime';
                   9523:     }
1.780     raeburn  9524:     my @sorted;
                   9525:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9526:         @sorted =
                   9527:             sort {
                   9528:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9529:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9530:                      }
                   9531:                      if (ref($slots->{$a})) { return -1;}
                   9532:                      if (ref($slots->{$b})) { return 1;}
                   9533:                      return 0;
                   9534:                  } @{$slotsarr};
                   9535:     }
                   9536:     return @sorted;
                   9537: }
                   9538: 
1.1040    raeburn  9539: =pod
                   9540: 
                   9541: =item * get_future_slots()
                   9542: 
                   9543: Inputs:
                   9544: 
                   9545: =over 4
                   9546: 
                   9547: cnum - course number
                   9548: 
                   9549: cdom - course domain
                   9550: 
                   9551: now - current UNIX time
                   9552: 
                   9553: symb - optional symb
                   9554: 
                   9555: =back
                   9556: 
                   9557: Returns:
                   9558: 
                   9559: =over 4
                   9560: 
                   9561: sorted_reservable - ref to array of student_schedulable slots currently 
                   9562:                     reservable, ordered by end date of reservation period.
                   9563: 
                   9564: reservable_now - ref to hash of student_schedulable slots currently
                   9565:                  reservable.
                   9566: 
                   9567:     Keys in inner hash are:
                   9568:     (a) symb: either blank or symb to which slot use is restricted.
                   9569:     (b) endreserve: end date of reservation period. 
                   9570: 
                   9571: sorted_future - ref to array of student_schedulable slots reservable in
                   9572:                 the future, ordered by start date of reservation period.
                   9573: 
                   9574: future_reservable - ref to hash of student_schedulable slots reservable
                   9575:                     in the future.
                   9576: 
                   9577:     Keys in inner hash are:
                   9578:     (a) symb: either blank or symb to which slot use is restricted.
                   9579:     (b) startreserve:  start date of reservation period.
                   9580: 
                   9581: =back
                   9582: 
                   9583: =cut
                   9584: 
                   9585: sub get_future_slots {
                   9586:     my ($cnum,$cdom,$now,$symb) = @_;
                   9587:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9588:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9589:     foreach my $slot (keys(%slots)) {
                   9590:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9591:         if ($symb) {
                   9592:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9593:                      ($slots{$slot}->{'symb'} ne $symb));
                   9594:         }
                   9595:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9596:             ($slots{$slot}->{'endtime'} > $now)) {
                   9597:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9598:                 my $userallowed = 0;
                   9599:                 if ($slots{$slot}->{'allowedsections'}) {
                   9600:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9601:                     if (!defined($env{'request.role.sec'})
                   9602:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9603:                         $userallowed=1;
                   9604:                     } else {
                   9605:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9606:                             $userallowed=1;
                   9607:                         }
                   9608:                     }
                   9609:                     unless ($userallowed) {
                   9610:                         if (defined($env{'request.course.groups'})) {
                   9611:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9612:                             foreach my $group (@groups) {
                   9613:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9614:                                     $userallowed=1;
                   9615:                                     last;
                   9616:                                 }
                   9617:                             }
                   9618:                         }
                   9619:                     }
                   9620:                 }
                   9621:                 if ($slots{$slot}->{'allowedusers'}) {
                   9622:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9623:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9624:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9625:                         $userallowed = 1;
                   9626:                     }
                   9627:                 }
                   9628:                 next unless($userallowed);
                   9629:             }
                   9630:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9631:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9632:             my $symb = $slots{$slot}->{'symb'};
                   9633:             if (($startreserve < $now) &&
                   9634:                 (!$endreserve || $endreserve > $now)) {
                   9635:                 my $lastres = $endreserve;
                   9636:                 if (!$lastres) {
                   9637:                     $lastres = $slots{$slot}->{'starttime'};
                   9638:                 }
                   9639:                 $reservable_now{$slot} = {
                   9640:                                            symb       => $symb,
                   9641:                                            endreserve => $lastres
                   9642:                                          };
                   9643:             } elsif (($startreserve > $now) &&
                   9644:                      (!$endreserve || $endreserve > $startreserve)) {
                   9645:                 $future_reservable{$slot} = {
                   9646:                                               symb         => $symb,
                   9647:                                               startreserve => $startreserve
                   9648:                                             };
                   9649:             }
                   9650:         }
                   9651:     }
                   9652:     my @unsorted_reservable = keys(%reservable_now);
                   9653:     if (@unsorted_reservable > 0) {
                   9654:         @sorted_reservable = 
                   9655:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9656:     }
                   9657:     my @unsorted_future = keys(%future_reservable);
                   9658:     if (@unsorted_future > 0) {
                   9659:         @sorted_future =
                   9660:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9661:     }
                   9662:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9663: }
1.780     raeburn  9664: 
                   9665: =pod
                   9666: 
1.1057    foxr     9667: =back
                   9668: 
1.549     albertel 9669: =head1 HTTP Helpers
                   9670: 
                   9671: =over 4
                   9672: 
1.648     raeburn  9673: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9674: 
1.258     albertel 9675: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9676: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9677: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9678: 
                   9679: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9680: $possible_names is an ref to an array of form element names.  As an example:
                   9681: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9682: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9683: 
                   9684: =cut
1.1       albertel 9685: 
1.6       albertel 9686: sub get_unprocessed_cgi {
1.25      albertel 9687:   my ($query,$possible_names)= @_;
1.26      matthew  9688:   # $Apache::lonxml::debug=1;
1.356     albertel 9689:   foreach my $pair (split(/&/,$query)) {
                   9690:     my ($name, $value) = split(/=/,$pair);
1.369     www      9691:     $name = &unescape($name);
1.25      albertel 9692:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9693:       $value =~ tr/+/ /;
                   9694:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9695:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9696:     }
1.16      harris41 9697:   }
1.6       albertel 9698: }
                   9699: 
1.112     bowersj2 9700: =pod
                   9701: 
1.648     raeburn  9702: =item * &cacheheader() 
1.112     bowersj2 9703: 
                   9704: returns cache-controlling header code
                   9705: 
                   9706: =cut
                   9707: 
1.7       albertel 9708: sub cacheheader {
1.258     albertel 9709:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9710:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9711:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9712:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9713:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9714:     return $output;
1.7       albertel 9715: }
                   9716: 
1.112     bowersj2 9717: =pod
                   9718: 
1.648     raeburn  9719: =item * &no_cache($r) 
1.112     bowersj2 9720: 
                   9721: specifies header code to not have cache
                   9722: 
                   9723: =cut
                   9724: 
1.9       albertel 9725: sub no_cache {
1.216     albertel 9726:     my ($r) = @_;
                   9727:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9728: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9729:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9730:     $r->no_cache(1);
                   9731:     $r->header_out("Expires" => $date);
                   9732:     $r->header_out("Pragma" => "no-cache");
1.123     www      9733: }
                   9734: 
                   9735: sub content_type {
1.181     albertel 9736:     my ($r,$type,$charset) = @_;
1.299     foxr     9737:     if ($r) {
                   9738: 	#  Note that printout.pl calls this with undef for $r.
                   9739: 	&no_cache($r);
                   9740:     }
1.258     albertel 9741:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9742:     unless ($charset) {
                   9743: 	$charset=&Apache::lonlocal::current_encoding;
                   9744:     }
                   9745:     if ($charset) { $type.='; charset='.$charset; }
                   9746:     if ($r) {
                   9747: 	$r->content_type($type);
                   9748:     } else {
                   9749: 	print("Content-type: $type\n\n");
                   9750:     }
1.9       albertel 9751: }
1.25      albertel 9752: 
1.112     bowersj2 9753: =pod
                   9754: 
1.648     raeburn  9755: =item * &add_to_env($name,$value) 
1.112     bowersj2 9756: 
1.258     albertel 9757: adds $name to the %env hash with value
1.112     bowersj2 9758: $value, if $name already exists, the entry is converted to an array
                   9759: reference and $value is added to the array.
                   9760: 
                   9761: =cut
                   9762: 
1.25      albertel 9763: sub add_to_env {
                   9764:   my ($name,$value)=@_;
1.258     albertel 9765:   if (defined($env{$name})) {
                   9766:     if (ref($env{$name})) {
1.25      albertel 9767:       #already have multiple values
1.258     albertel 9768:       push(@{ $env{$name} },$value);
1.25      albertel 9769:     } else {
                   9770:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9771:       my $first=$env{$name};
                   9772:       undef($env{$name});
                   9773:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9774:     }
                   9775:   } else {
1.258     albertel 9776:     $env{$name}=$value;
1.25      albertel 9777:   }
1.31      albertel 9778: }
1.149     albertel 9779: 
                   9780: =pod
                   9781: 
1.648     raeburn  9782: =item * &get_env_multiple($name) 
1.149     albertel 9783: 
1.258     albertel 9784: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9785: values may be defined and end up as an array ref.
                   9786: 
                   9787: returns an array of values
                   9788: 
                   9789: =cut
                   9790: 
                   9791: sub get_env_multiple {
                   9792:     my ($name) = @_;
                   9793:     my @values;
1.258     albertel 9794:     if (defined($env{$name})) {
1.149     albertel 9795:         # exists is it an array
1.258     albertel 9796:         if (ref($env{$name})) {
                   9797:             @values=@{ $env{$name} };
1.149     albertel 9798:         } else {
1.258     albertel 9799:             $values[0]=$env{$name};
1.149     albertel 9800:         }
                   9801:     }
                   9802:     return(@values);
                   9803: }
                   9804: 
1.660     raeburn  9805: sub ask_for_embedded_content {
                   9806:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9807:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  9808:         %currsubfile,%unused,$rem);
1.1071    raeburn  9809:     my $counter = 0;
                   9810:     my $numnew = 0;
1.987     raeburn  9811:     my $numremref = 0;
                   9812:     my $numinvalid = 0;
                   9813:     my $numpathchg = 0;
                   9814:     my $numexisting = 0;
1.1071    raeburn  9815:     my $numunused = 0;
                   9816:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  9817:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  9818:     my $heading = &mt('Upload embedded files');
                   9819:     my $buttontext = &mt('Upload');
                   9820: 
1.1075.2.11  raeburn  9821:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  9822:         if ($actionurl eq '/adm/dependencies') {
                   9823:             $navmap = Apache::lonnavmaps::navmap->new();
                   9824:         }
                   9825:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9826:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  9827:     }
1.1075.2.35  raeburn  9828:     if (($actionurl eq '/adm/portfolio') ||
                   9829:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  9830:         my $current_path='/';
                   9831:         if ($env{'form.currentpath'}) {
                   9832:             $current_path = $env{'form.currentpath'};
                   9833:         }
                   9834:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  9835:             $udom = $cdom;
                   9836:             $uname = $cnum;
1.984     raeburn  9837:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9838:         } else {
                   9839:             $udom = $env{'user.domain'};
                   9840:             $uname = $env{'user.name'};
                   9841:             $url = '/userfiles/portfolio';
                   9842:         }
1.987     raeburn  9843:         $toplevel = $url.'/';
1.984     raeburn  9844:         $url .= $current_path;
                   9845:         $getpropath = 1;
1.987     raeburn  9846:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9847:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9848:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9849:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9850:         $toplevel = $url;
1.984     raeburn  9851:         if ($rest ne '') {
1.987     raeburn  9852:             $url .= $rest;
                   9853:         }
                   9854:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9855:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9856:             $url = $args->{'docs_url'};
                   9857:             $toplevel = $url;
1.1075.2.11  raeburn  9858:             if ($args->{'context'} eq 'paste') {
                   9859:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9860:                 ($path) =
                   9861:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9862:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9863:                 $fileloc =~ s{^/}{};
                   9864:             }
1.1071    raeburn  9865:         }
                   9866:     } elsif ($actionurl eq '/adm/dependencies') {
                   9867:         if ($env{'request.course.id'} ne '') {
                   9868:             if (ref($args) eq 'HASH') {
                   9869:                 $url = $args->{'docs_url'};
                   9870:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  9871:                 $toplevel = $url;
                   9872:                 unless ($toplevel =~ m{^/}) {
                   9873:                     $toplevel = "/$url";
                   9874:                 }
1.1075.2.11  raeburn  9875:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  9876:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   9877:                     $path = $1;
                   9878:                 } else {
                   9879:                     ($path) =
                   9880:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9881:                 }
1.1071    raeburn  9882:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9883:                 $fileloc =~ s{^/}{};
                   9884:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9885:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9886:             }
1.987     raeburn  9887:         }
1.1075.2.35  raeburn  9888:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9889:         $udom = $cdom;
                   9890:         $uname = $cnum;
                   9891:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   9892:         $toplevel = $url;
                   9893:         $path = $url;
                   9894:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   9895:         $fileloc =~ s{^/}{};
                   9896:     }
                   9897:     foreach my $file (keys(%{$allfiles})) {
                   9898:         my $embed_file;
                   9899:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   9900:             $embed_file = $1;
                   9901:         } else {
                   9902:             $embed_file = $file;
                   9903:         }
1.1075.2.55  raeburn  9904:         my ($absolutepath,$cleaned_file);
                   9905:         if ($embed_file =~ m{^\w+://}) {
                   9906:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  9907:             $newfiles{$cleaned_file} = 1;
                   9908:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  9909:         } else {
1.1075.2.55  raeburn  9910:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  9911:             if ($embed_file =~ m{^/}) {
                   9912:                 $absolutepath = $embed_file;
                   9913:             }
1.1075.2.47  raeburn  9914:             if ($cleaned_file =~ m{/}) {
                   9915:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  9916:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9917:                 my $item = $fname;
                   9918:                 if ($path ne '') {
                   9919:                     $item = $path.'/'.$fname;
                   9920:                     $subdependencies{$path}{$fname} = 1;
                   9921:                 } else {
                   9922:                     $dependencies{$item} = 1;
                   9923:                 }
                   9924:                 if ($absolutepath) {
                   9925:                     $mapping{$item} = $absolutepath;
                   9926:                 } else {
                   9927:                     $mapping{$item} = $embed_file;
                   9928:                 }
                   9929:             } else {
                   9930:                 $dependencies{$embed_file} = 1;
                   9931:                 if ($absolutepath) {
1.1075.2.47  raeburn  9932:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  9933:                 } else {
1.1075.2.47  raeburn  9934:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  9935:                 }
                   9936:             }
1.984     raeburn  9937:         }
                   9938:     }
1.1071    raeburn  9939:     my $dirptr = 16384;
1.984     raeburn  9940:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9941:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  9942:         if (($actionurl eq '/adm/portfolio') ||
                   9943:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9944:             my ($sublistref,$listerror) =
                   9945:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9946:             if (ref($sublistref) eq 'ARRAY') {
                   9947:                 foreach my $line (@{$sublistref}) {
                   9948:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9949:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9950:                 }
1.984     raeburn  9951:             }
1.987     raeburn  9952:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9953:             if (opendir(my $dir,$url.'/'.$path)) {
                   9954:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9955:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9956:             }
1.1075.2.11  raeburn  9957:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9958:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  9959:                   ($args->{'context'} eq 'paste')) ||
                   9960:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  9961:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  9962:                 my $dir;
                   9963:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   9964:                     $dir = $fileloc;
                   9965:                 } else {
                   9966:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9967:                 }
1.1071    raeburn  9968:                 if ($dir ne '') {
                   9969:                     my ($sublistref,$listerror) =
                   9970:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9971:                     if (ref($sublistref) eq 'ARRAY') {
                   9972:                         foreach my $line (@{$sublistref}) {
                   9973:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9974:                                 undef,$mtime)=split(/\&/,$line,12);
                   9975:                             unless (($testdir&$dirptr) ||
                   9976:                                     ($file_name =~ /^\.\.?$/)) {
                   9977:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9978:                             }
                   9979:                         }
                   9980:                     }
                   9981:                 }
1.984     raeburn  9982:             }
                   9983:         }
                   9984:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9985:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9986:                 my $item = $path.'/'.$file;
                   9987:                 unless ($mapping{$item} eq $item) {
                   9988:                     $pathchanges{$item} = 1;
                   9989:                 }
                   9990:                 $existing{$item} = 1;
                   9991:                 $numexisting ++;
                   9992:             } else {
                   9993:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9994:             }
                   9995:         }
1.1071    raeburn  9996:         if ($actionurl eq '/adm/dependencies') {
                   9997:             foreach my $path (keys(%currsubfile)) {
                   9998:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9999:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10000:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10001:                              next if (($rem ne '') &&
                   10002:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10003:                                        (ref($navmap) &&
                   10004:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10005:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10006:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10007:                              $unused{$path.'/'.$file} = 1; 
                   10008:                          }
                   10009:                     }
                   10010:                 }
                   10011:             }
                   10012:         }
1.984     raeburn  10013:     }
1.987     raeburn  10014:     my %currfile;
1.1075.2.35  raeburn  10015:     if (($actionurl eq '/adm/portfolio') ||
                   10016:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10017:         my ($dirlistref,$listerror) =
                   10018:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10019:         if (ref($dirlistref) eq 'ARRAY') {
                   10020:             foreach my $line (@{$dirlistref}) {
                   10021:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10022:                 $currfile{$file_name} = 1;
                   10023:             }
1.984     raeburn  10024:         }
1.987     raeburn  10025:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10026:         if (opendir(my $dir,$url)) {
1.987     raeburn  10027:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10028:             map {$currfile{$_} = 1;} @dir_list;
                   10029:         }
1.1075.2.11  raeburn  10030:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10031:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10032:               ($args->{'context'} eq 'paste')) ||
                   10033:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10034:         if ($env{'request.course.id'} ne '') {
                   10035:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10036:             if ($dir ne '') {
                   10037:                 my ($dirlistref,$listerror) =
                   10038:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10039:                 if (ref($dirlistref) eq 'ARRAY') {
                   10040:                     foreach my $line (@{$dirlistref}) {
                   10041:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10042:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10043:                         unless (($testdir&$dirptr) ||
                   10044:                                 ($file_name =~ /^\.\.?$/)) {
                   10045:                             $currfile{$file_name} = [$size,$mtime];
                   10046:                         }
                   10047:                     }
                   10048:                 }
                   10049:             }
                   10050:         }
1.984     raeburn  10051:     }
                   10052:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10053:         if (exists($currfile{$file})) {
1.987     raeburn  10054:             unless ($mapping{$file} eq $file) {
                   10055:                 $pathchanges{$file} = 1;
                   10056:             }
                   10057:             $existing{$file} = 1;
                   10058:             $numexisting ++;
                   10059:         } else {
1.984     raeburn  10060:             $newfiles{$file} = 1;
                   10061:         }
                   10062:     }
1.1071    raeburn  10063:     foreach my $file (keys(%currfile)) {
                   10064:         unless (($file eq $filename) ||
                   10065:                 ($file eq $filename.'.bak') ||
                   10066:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10067:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10068:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10069:                     next if (($rem ne '') &&
                   10070:                              (($env{"httpref.$rem".$file} ne '') ||
                   10071:                               (ref($navmap) &&
                   10072:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10073:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10074:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10075:                 }
1.1075.2.11  raeburn  10076:             }
1.1071    raeburn  10077:             $unused{$file} = 1;
                   10078:         }
                   10079:     }
1.1075.2.11  raeburn  10080:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10081:         ($args->{'context'} eq 'paste')) {
                   10082:         $counter = scalar(keys(%existing));
                   10083:         $numpathchg = scalar(keys(%pathchanges));
                   10084:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10085:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10086:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10087:         $counter = scalar(keys(%existing));
                   10088:         $numpathchg = scalar(keys(%pathchanges));
                   10089:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10090:     }
1.984     raeburn  10091:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10092:         if ($actionurl eq '/adm/dependencies') {
                   10093:             next if ($embed_file =~ m{^\w+://});
                   10094:         }
1.660     raeburn  10095:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10096:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10097:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10098:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10099:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10100:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10101:         }
1.1075.2.35  raeburn  10102:         $upload_output .= '</td>';
1.1071    raeburn  10103:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10104:             $upload_output.='<td align="right">'.
                   10105:                             '<span class="LC_info LC_fontsize_medium">'.
                   10106:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10107:             $numremref++;
1.660     raeburn  10108:         } elsif ($args->{'error_on_invalid_names'}
                   10109:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10110:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10111:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10112:             $numinvalid++;
1.660     raeburn  10113:         } else {
1.1075.2.35  raeburn  10114:             $upload_output .= '<td>'.
                   10115:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10116:                                                      $embed_file,\%mapping,
1.1071    raeburn  10117:                                                      $allfiles,$codebase,'upload');
                   10118:             $counter ++;
                   10119:             $numnew ++;
1.987     raeburn  10120:         }
                   10121:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10122:     }
                   10123:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10124:         if ($actionurl eq '/adm/dependencies') {
                   10125:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10126:             $modify_output .= &start_data_table_row().
                   10127:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10128:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10129:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10130:                               '<td>'.$size.'</td>'.
                   10131:                               '<td>'.$mtime.'</td>'.
                   10132:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10133:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10134:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10135:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10136:                               &embedded_file_element('upload_embedded',$counter,
                   10137:                                                      $embed_file,\%mapping,
                   10138:                                                      $allfiles,$codebase,'modify').
                   10139:                               '</div></td>'.
                   10140:                               &end_data_table_row()."\n";
                   10141:             $counter ++;
                   10142:         } else {
                   10143:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10144:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10145:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10146:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10147:                               &Apache::loncommon::end_data_table_row()."\n";
                   10148:         }
                   10149:     }
                   10150:     my $delidx = $counter;
                   10151:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10152:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10153:         $delete_output .= &start_data_table_row().
                   10154:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10155:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10156:                           '<td>'.$size.'</td>'.
                   10157:                           '<td>'.$mtime.'</td>'.
                   10158:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10159:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10160:                           &embedded_file_element('upload_embedded',$delidx,
                   10161:                                                  $oldfile,\%mapping,$allfiles,
                   10162:                                                  $codebase,'delete').'</td>'.
                   10163:                           &end_data_table_row()."\n"; 
                   10164:         $numunused ++;
                   10165:         $delidx ++;
1.987     raeburn  10166:     }
                   10167:     if ($upload_output) {
                   10168:         $upload_output = &start_data_table().
                   10169:                          $upload_output.
                   10170:                          &end_data_table()."\n";
                   10171:     }
1.1071    raeburn  10172:     if ($modify_output) {
                   10173:         $modify_output = &start_data_table().
                   10174:                          &start_data_table_header_row().
                   10175:                          '<th>'.&mt('File').'</th>'.
                   10176:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10177:                          '<th>'.&mt('Modified').'</th>'.
                   10178:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10179:                          &end_data_table_header_row().
                   10180:                          $modify_output.
                   10181:                          &end_data_table()."\n";
                   10182:     }
                   10183:     if ($delete_output) {
                   10184:         $delete_output = &start_data_table().
                   10185:                          &start_data_table_header_row().
                   10186:                          '<th>'.&mt('File').'</th>'.
                   10187:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10188:                          '<th>'.&mt('Modified').'</th>'.
                   10189:                          '<th>'.&mt('Delete?').'</th>'.
                   10190:                          &end_data_table_header_row().
                   10191:                          $delete_output.
                   10192:                          &end_data_table()."\n";
                   10193:     }
1.987     raeburn  10194:     my $applies = 0;
                   10195:     if ($numremref) {
                   10196:         $applies ++;
                   10197:     }
                   10198:     if ($numinvalid) {
                   10199:         $applies ++;
                   10200:     }
                   10201:     if ($numexisting) {
                   10202:         $applies ++;
                   10203:     }
1.1071    raeburn  10204:     if ($counter || $numunused) {
1.987     raeburn  10205:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10206:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10207:                   $state.'<h3>'.$heading.'</h3>'; 
                   10208:         if ($actionurl eq '/adm/dependencies') {
                   10209:             if ($numnew) {
                   10210:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10211:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10212:                            $upload_output.'<br />'."\n";
                   10213:             }
                   10214:             if ($numexisting) {
                   10215:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10216:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10217:                            $modify_output.'<br />'."\n";
                   10218:                            $buttontext = &mt('Save changes');
                   10219:             }
                   10220:             if ($numunused) {
                   10221:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10222:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10223:                            $delete_output.'<br />'."\n";
                   10224:                            $buttontext = &mt('Save changes');
                   10225:             }
                   10226:         } else {
                   10227:             $output .= $upload_output.'<br />'."\n";
                   10228:         }
                   10229:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10230:                    $counter.'" />'."\n";
                   10231:         if ($actionurl eq '/adm/dependencies') { 
                   10232:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10233:                        $numnew.'" />'."\n";
                   10234:         } elsif ($actionurl eq '') {
1.987     raeburn  10235:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10236:         }
                   10237:     } elsif ($applies) {
                   10238:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10239:         if ($applies > 1) {
                   10240:             $output .=  
1.1075.2.35  raeburn  10241:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10242:             if ($numremref) {
                   10243:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10244:             }
                   10245:             if ($numinvalid) {
                   10246:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10247:             }
                   10248:             if ($numexisting) {
                   10249:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10250:             }
                   10251:             $output .= '</ul><br />';
                   10252:         } elsif ($numremref) {
                   10253:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10254:         } elsif ($numinvalid) {
                   10255:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10256:         } elsif ($numexisting) {
                   10257:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10258:         }
                   10259:         $output .= $upload_output.'<br />';
                   10260:     }
                   10261:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10262:     $chgcount = $counter;
1.987     raeburn  10263:     if (keys(%pathchanges) > 0) {
                   10264:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10265:             if ($counter) {
1.987     raeburn  10266:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10267:                                                   $embed_file,\%mapping,
1.1071    raeburn  10268:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10269:             } else {
                   10270:                 $pathchange_output .= 
                   10271:                     &start_data_table_row().
                   10272:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10273:                     $chgcount.'" checked="checked" /></td>'.
                   10274:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10275:                     '<td>'.$embed_file.
                   10276:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10277:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10278:                     '</td>'.&end_data_table_row();
1.660     raeburn  10279:             }
1.987     raeburn  10280:             $numpathchg ++;
                   10281:             $chgcount ++;
1.660     raeburn  10282:         }
                   10283:     }
1.1075.2.35  raeburn  10284:     if (($counter) || ($numunused)) {
1.987     raeburn  10285:         if ($numpathchg) {
                   10286:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10287:                        $numpathchg.'" />'."\n";
                   10288:         }
                   10289:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10290:             ($actionurl eq '/adm/imsimport')) {
                   10291:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10292:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10293:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10294:         } elsif ($actionurl eq '/adm/dependencies') {
                   10295:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10296:         }
1.1075.2.35  raeburn  10297:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10298:     } elsif ($numpathchg) {
                   10299:         my %pathchange = ();
                   10300:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10301:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10302:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10303:         }
1.987     raeburn  10304:     }
1.1071    raeburn  10305:     return ($output,$counter,$numpathchg);
1.987     raeburn  10306: }
                   10307: 
1.1075.2.47  raeburn  10308: =pod
                   10309: 
                   10310: =item * clean_path($name)
                   10311: 
                   10312: Performs clean-up of directories, subdirectories and filename in an
                   10313: embedded object, referenced in an HTML file which is being uploaded
                   10314: to a course or portfolio, where
                   10315: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10316: checked.
                   10317: 
                   10318: Clean-up is similar to replacements in lonnet::clean_filename()
                   10319: except each / between sub-directory and next level is preserved.
                   10320: 
                   10321: =cut
                   10322: 
                   10323: sub clean_path {
                   10324:     my ($embed_file) = @_;
                   10325:     $embed_file =~s{^/+}{};
                   10326:     my @contents;
                   10327:     if ($embed_file =~ m{/}) {
                   10328:         @contents = split(/\//,$embed_file);
                   10329:     } else {
                   10330:         @contents = ($embed_file);
                   10331:     }
                   10332:     my $lastidx = scalar(@contents)-1;
                   10333:     for (my $i=0; $i<=$lastidx; $i++) {
                   10334:         $contents[$i]=~s{\\}{/}g;
                   10335:         $contents[$i]=~s/\s+/\_/g;
                   10336:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10337:         if ($i == $lastidx) {
                   10338:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10339:         }
                   10340:     }
                   10341:     if ($lastidx > 0) {
                   10342:         return join('/',@contents);
                   10343:     } else {
                   10344:         return $contents[0];
                   10345:     }
                   10346: }
                   10347: 
1.987     raeburn  10348: sub embedded_file_element {
1.1071    raeburn  10349:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10350:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10351:                    (ref($codebase) eq 'HASH'));
                   10352:     my $output;
1.1071    raeburn  10353:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10354:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10355:     }
                   10356:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10357:                &escape($embed_file).'" />';
                   10358:     unless (($context eq 'upload_embedded') && 
                   10359:             ($mapping->{$embed_file} eq $embed_file)) {
                   10360:         $output .='
                   10361:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10362:     }
                   10363:     my $attrib;
                   10364:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10365:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10366:     }
                   10367:     $output .=
                   10368:         "\n\t\t".
                   10369:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10370:         $attrib.'" />';
                   10371:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10372:         $output .=
                   10373:             "\n\t\t".
                   10374:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10375:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10376:     }
1.987     raeburn  10377:     return $output;
1.660     raeburn  10378: }
                   10379: 
1.1071    raeburn  10380: sub get_dependency_details {
                   10381:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10382:     my ($size,$mtime,$showsize,$showmtime);
                   10383:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10384:         if ($embed_file =~ m{/}) {
                   10385:             my ($path,$fname) = split(/\//,$embed_file);
                   10386:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10387:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10388:             }
                   10389:         } else {
                   10390:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10391:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10392:             }
                   10393:         }
                   10394:         $showsize = $size/1024.0;
                   10395:         $showsize = sprintf("%.1f",$showsize);
                   10396:         if ($mtime > 0) {
                   10397:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10398:         }
                   10399:     }
                   10400:     return ($showsize,$showmtime);
                   10401: }
                   10402: 
                   10403: sub ask_embedded_js {
                   10404:     return <<"END";
                   10405: <script type="text/javascript"">
                   10406: // <![CDATA[
                   10407: function toggleBrowse(counter) {
                   10408:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10409:     var fileid = document.getElementById('embedded_item_'+counter);
                   10410:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10411:     if (chkboxid.checked == true) {
                   10412:         uploaddivid.style.display='block';
                   10413:     } else {
                   10414:         uploaddivid.style.display='none';
                   10415:         fileid.value = '';
                   10416:     }
                   10417: }
                   10418: // ]]>
                   10419: </script>
                   10420: 
                   10421: END
                   10422: }
                   10423: 
1.661     raeburn  10424: sub upload_embedded {
                   10425:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10426:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10427:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10428:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10429:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10430:         my $orig_uploaded_filename =
                   10431:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10432:         foreach my $type ('orig','ref','attrib','codebase') {
                   10433:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10434:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10435:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10436:             }
                   10437:         }
1.661     raeburn  10438:         my ($path,$fname) =
                   10439:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10440:         # no path, whole string is fname
                   10441:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10442:         $fname = &Apache::lonnet::clean_filename($fname);
                   10443:         # See if there is anything left
                   10444:         next if ($fname eq '');
                   10445: 
                   10446:         # Check if file already exists as a file or directory.
                   10447:         my ($state,$msg);
                   10448:         if ($context eq 'portfolio') {
                   10449:             my $port_path = $dirpath;
                   10450:             if ($group ne '') {
                   10451:                 $port_path = "groups/$group/$port_path";
                   10452:             }
1.987     raeburn  10453:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10454:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10455:                                               $dir_root,$port_path,$disk_quota,
                   10456:                                               $current_disk_usage,$uname,$udom);
                   10457:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10458:                 || $state eq 'file_locked') {
1.661     raeburn  10459:                 $output .= $msg;
                   10460:                 next;
                   10461:             }
                   10462:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10463:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10464:             if ($state eq 'exists') {
                   10465:                 $output .= $msg;
                   10466:                 next;
                   10467:             }
                   10468:         }
                   10469:         # Check if extension is valid
                   10470:         if (($fname =~ /\.(\w+)$/) &&
                   10471:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  10472:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10473:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10474:             next;
                   10475:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10476:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10477:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10478:             next;
                   10479:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  10480:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10481:             next;
                   10482:         }
                   10483:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  10484:         my $subdir = $path;
                   10485:         $subdir =~ s{/+$}{};
1.661     raeburn  10486:         if ($context eq 'portfolio') {
1.984     raeburn  10487:             my $result;
                   10488:             if ($state eq 'existingfile') {
                   10489:                 $result=
                   10490:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  10491:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10492:             } else {
1.984     raeburn  10493:                 $result=
                   10494:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10495:                                                     $dirpath.
1.1075.2.35  raeburn  10496:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10497:                 if ($result !~ m|^/uploaded/|) {
                   10498:                     $output .= '<span class="LC_error">'
                   10499:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10500:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10501:                                .'</span><br />';
                   10502:                     next;
                   10503:                 } else {
1.987     raeburn  10504:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10505:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10506:                 }
1.661     raeburn  10507:             }
1.1075.2.35  raeburn  10508:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   10509:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10510:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10511:             my $result =
1.1075.2.35  raeburn  10512:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10513:             if ($result !~ m|^/uploaded/|) {
                   10514:                 $output .= '<span class="LC_error">'
                   10515:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10516:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10517:                            .'</span><br />';
                   10518:                     next;
                   10519:             } else {
                   10520:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10521:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  10522:                 if ($context eq 'syllabus') {
                   10523:                     &Apache::lonnet::make_public_indefinitely($result);
                   10524:                 }
1.987     raeburn  10525:             }
1.661     raeburn  10526:         } else {
                   10527: # Save the file
                   10528:             my $target = $env{'form.embedded_item_'.$i};
                   10529:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10530:             my $dest = $fullpath.$fname;
                   10531:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10532:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10533:             my $count;
                   10534:             my $filepath = $dir_root;
1.1027    raeburn  10535:             foreach my $subdir (@parts) {
                   10536:                 $filepath .= "/$subdir";
                   10537:                 if (!-e $filepath) {
1.661     raeburn  10538:                     mkdir($filepath,0770);
                   10539:                 }
                   10540:             }
                   10541:             my $fh;
                   10542:             if (!open($fh,'>'.$dest)) {
                   10543:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10544:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10545:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10546:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10547:                            '</span><br />';
                   10548:             } else {
                   10549:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10550:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10551:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10552:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10553:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10554:                               '</span><br />';
                   10555:                 } else {
1.987     raeburn  10556:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10557:                                $url.'</span>').'<br />';
                   10558:                     unless ($context eq 'testbank') {
                   10559:                         $footer .= &mt('View embedded file: [_1]',
                   10560:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10561:                     }
                   10562:                 }
                   10563:                 close($fh);
                   10564:             }
                   10565:         }
                   10566:         if ($env{'form.embedded_ref_'.$i}) {
                   10567:             $pathchange{$i} = 1;
                   10568:         }
                   10569:     }
                   10570:     if ($output) {
                   10571:         $output = '<p>'.$output.'</p>';
                   10572:     }
                   10573:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10574:     $returnflag = 'ok';
1.1071    raeburn  10575:     my $numpathchgs = scalar(keys(%pathchange));
                   10576:     if ($numpathchgs > 0) {
1.987     raeburn  10577:         if ($context eq 'portfolio') {
                   10578:             $output .= '<p>'.&mt('or').'</p>';
                   10579:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10580:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10581:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10582:             $returnflag = 'modify_orightml';
                   10583:         }
                   10584:     }
1.1071    raeburn  10585:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10586: }
                   10587: 
                   10588: sub modify_html_form {
                   10589:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10590:     my $end = 0;
                   10591:     my $modifyform;
                   10592:     if ($context eq 'upload_embedded') {
                   10593:         return unless (ref($pathchange) eq 'HASH');
                   10594:         if ($env{'form.number_embedded_items'}) {
                   10595:             $end += $env{'form.number_embedded_items'};
                   10596:         }
                   10597:         if ($env{'form.number_pathchange_items'}) {
                   10598:             $end += $env{'form.number_pathchange_items'};
                   10599:         }
                   10600:         if ($end) {
                   10601:             for (my $i=0; $i<$end; $i++) {
                   10602:                 if ($i < $env{'form.number_embedded_items'}) {
                   10603:                     next unless($pathchange->{$i});
                   10604:                 }
                   10605:                 $modifyform .=
                   10606:                     &start_data_table_row().
                   10607:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10608:                     'checked="checked" /></td>'.
                   10609:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10610:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10611:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10612:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10613:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10614:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10615:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10616:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10617:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10618:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10619:                     &end_data_table_row();
1.1071    raeburn  10620:             }
1.987     raeburn  10621:         }
                   10622:     } else {
                   10623:         $modifyform = $pathchgtable;
                   10624:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10625:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10626:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10627:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10628:         }
                   10629:     }
                   10630:     if ($modifyform) {
1.1071    raeburn  10631:         if ($actionurl eq '/adm/dependencies') {
                   10632:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10633:         }
1.987     raeburn  10634:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10635:                '<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".
                   10636:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10637:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10638:                '</ol></p>'."\n".'<p>'.
                   10639:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10640:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10641:                &start_data_table()."\n".
                   10642:                &start_data_table_header_row().
                   10643:                '<th>'.&mt('Change?').'</th>'.
                   10644:                '<th>'.&mt('Current reference').'</th>'.
                   10645:                '<th>'.&mt('Required reference').'</th>'.
                   10646:                &end_data_table_header_row()."\n".
                   10647:                $modifyform.
                   10648:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10649:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10650:                '</form>'."\n";
                   10651:     }
                   10652:     return;
                   10653: }
                   10654: 
                   10655: sub modify_html_refs {
1.1075.2.35  raeburn  10656:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10657:     my $container;
                   10658:     if ($context eq 'portfolio') {
                   10659:         $container = $env{'form.container'};
                   10660:     } elsif ($context eq 'coursedoc') {
                   10661:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10662:     } elsif ($context eq 'manage_dependencies') {
                   10663:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10664:         $container = "/$container";
1.1075.2.35  raeburn  10665:     } elsif ($context eq 'syllabus') {
                   10666:         $container = $url;
1.987     raeburn  10667:     } else {
1.1027    raeburn  10668:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10669:     }
                   10670:     my (%allfiles,%codebase,$output,$content);
                   10671:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  10672:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  10673:         if (wantarray) {
                   10674:             return ('',0,0); 
                   10675:         } else {
                   10676:             return;
                   10677:         }
                   10678:     }
                   10679:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10680:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10681:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10682:             if (wantarray) {
                   10683:                 return ('',0,0);
                   10684:             } else {
                   10685:                 return;
                   10686:             }
                   10687:         } 
1.987     raeburn  10688:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10689:         if ($content eq '-1') {
                   10690:             if (wantarray) {
                   10691:                 return ('',0,0);
                   10692:             } else {
                   10693:                 return;
                   10694:             }
                   10695:         }
1.987     raeburn  10696:     } else {
1.1071    raeburn  10697:         unless ($container =~ /^\Q$dir_root\E/) {
                   10698:             if (wantarray) {
                   10699:                 return ('',0,0);
                   10700:             } else {
                   10701:                 return;
                   10702:             }
                   10703:         } 
1.987     raeburn  10704:         if (open(my $fh,"<$container")) {
                   10705:             $content = join('', <$fh>);
                   10706:             close($fh);
                   10707:         } else {
1.1071    raeburn  10708:             if (wantarray) {
                   10709:                 return ('',0,0);
                   10710:             } else {
                   10711:                 return;
                   10712:             }
1.987     raeburn  10713:         }
                   10714:     }
                   10715:     my ($count,$codebasecount) = (0,0);
                   10716:     my $mm = new File::MMagic;
                   10717:     my $mime_type = $mm->checktype_contents($content);
                   10718:     if ($mime_type eq 'text/html') {
                   10719:         my $parse_result = 
                   10720:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10721:                                                     \%codebase,\$content);
                   10722:         if ($parse_result eq 'ok') {
                   10723:             foreach my $i (@changes) {
                   10724:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10725:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10726:                 if ($allfiles{$ref}) {
                   10727:                     my $newname =  $orig;
                   10728:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10729:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10730:                     if ($attrib_regexp =~ /:/) {
                   10731:                         $attrib_regexp =~ s/\:/|/g;
                   10732:                     }
                   10733:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10734:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10735:                         $count += $numchg;
1.1075.2.35  raeburn  10736:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  10737:                         delete($allfiles{$ref});
1.987     raeburn  10738:                     }
                   10739:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10740:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10741:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10742:                         $codebasecount ++;
                   10743:                     }
                   10744:                 }
                   10745:             }
1.1075.2.35  raeburn  10746:             my $skiprewrites;
1.987     raeburn  10747:             if ($count || $codebasecount) {
                   10748:                 my $saveresult;
1.1071    raeburn  10749:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10750:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  10751:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10752:                     if ($url eq $container) {
                   10753:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10754:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10755:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10756:                                             $fname.'</span>').'</p>';
1.987     raeburn  10757:                     } else {
                   10758:                          $output = '<p class="LC_error">'.
                   10759:                                    &mt('Error: update failed for: [_1].',
                   10760:                                    '<span class="LC_filename">'.
                   10761:                                    $container.'</span>').'</p>';
                   10762:                     }
1.1075.2.35  raeburn  10763:                     if ($context eq 'syllabus') {
                   10764:                         unless ($saveresult eq 'ok') {
                   10765:                             $skiprewrites = 1;
                   10766:                         }
                   10767:                     }
1.987     raeburn  10768:                 } else {
                   10769:                     if (open(my $fh,">$container")) {
                   10770:                         print $fh $content;
                   10771:                         close($fh);
                   10772:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10773:                                   $count,'<span class="LC_filename">'.
                   10774:                                   $container.'</span>').'</p>';
1.661     raeburn  10775:                     } else {
1.987     raeburn  10776:                          $output = '<p class="LC_error">'.
                   10777:                                    &mt('Error: could not update [_1].',
                   10778:                                    '<span class="LC_filename">'.
                   10779:                                    $container.'</span>').'</p>';
1.661     raeburn  10780:                     }
                   10781:                 }
                   10782:             }
1.1075.2.35  raeburn  10783:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   10784:                 my ($actionurl,$state);
                   10785:                 $actionurl = "/public/$udom/$uname/syllabus";
                   10786:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   10787:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   10788:                                               \%codebase,
                   10789:                                               {'context' => 'rewrites',
                   10790:                                                'ignore_remote_references' => 1,});
                   10791:                 if (ref($mapping) eq 'HASH') {
                   10792:                     my $rewrites = 0;
                   10793:                     foreach my $key (keys(%{$mapping})) {
                   10794:                         next if ($key =~ m{^https?://});
                   10795:                         my $ref = $mapping->{$key};
                   10796:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   10797:                         my $attrib;
                   10798:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   10799:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   10800:                         }
                   10801:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10802:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10803:                             $rewrites += $numchg;
                   10804:                         }
                   10805:                     }
                   10806:                     if ($rewrites) {
                   10807:                         my $saveresult;
                   10808:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10809:                         if ($url eq $container) {
                   10810:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   10811:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   10812:                                             $count,'<span class="LC_filename">'.
                   10813:                                             $fname.'</span>').'</p>';
                   10814:                         } else {
                   10815:                             $output .= '<p class="LC_error">'.
                   10816:                                        &mt('Error: could not update links in [_1].',
                   10817:                                        '<span class="LC_filename">'.
                   10818:                                        $container.'</span>').'</p>';
                   10819: 
                   10820:                         }
                   10821:                     }
                   10822:                 }
                   10823:             }
1.987     raeburn  10824:         } else {
                   10825:             &logthis('Failed to parse '.$container.
                   10826:                      ' to modify references: '.$parse_result);
1.661     raeburn  10827:         }
                   10828:     }
1.1071    raeburn  10829:     if (wantarray) {
                   10830:         return ($output,$count,$codebasecount);
                   10831:     } else {
                   10832:         return $output;
                   10833:     }
1.661     raeburn  10834: }
                   10835: 
                   10836: sub check_for_existing {
                   10837:     my ($path,$fname,$element) = @_;
                   10838:     my ($state,$msg);
                   10839:     if (-d $path.'/'.$fname) {
                   10840:         $state = 'exists';
                   10841:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10842:     } elsif (-e $path.'/'.$fname) {
                   10843:         $state = 'exists';
                   10844:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10845:     }
                   10846:     if ($state eq 'exists') {
                   10847:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10848:     }
                   10849:     return ($state,$msg);
                   10850: }
                   10851: 
                   10852: sub check_for_upload {
                   10853:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10854:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10855:     my $filesize = length($env{'form.'.$element});
                   10856:     if (!$filesize) {
                   10857:         my $msg = '<span class="LC_error">'.
                   10858:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10859:                       '<span class="LC_filename">'.$fname.'</span>',
                   10860:                       $filesize).'<br />'.
1.1007    raeburn  10861:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10862:                   '</span>';
                   10863:         return ('zero_bytes',$msg);
                   10864:     }
                   10865:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10866:     my $getpropath = 1;
1.1021    raeburn  10867:     my ($dirlistref,$listerror) =
                   10868:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10869:     my $found_file = 0;
                   10870:     my $locked_file = 0;
1.991     raeburn  10871:     my @lockers;
                   10872:     my $navmap;
                   10873:     if ($env{'request.course.id'}) {
                   10874:         $navmap = Apache::lonnavmaps::navmap->new();
                   10875:     }
1.1021    raeburn  10876:     if (ref($dirlistref) eq 'ARRAY') {
                   10877:         foreach my $line (@{$dirlistref}) {
                   10878:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10879:             if ($file_name eq $fname){
                   10880:                 $file_name = $path.$file_name;
                   10881:                 if ($group ne '') {
                   10882:                     $file_name = $group.$file_name;
                   10883:                 }
                   10884:                 $found_file = 1;
                   10885:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10886:                     foreach my $lock (@lockers) {
                   10887:                         if (ref($lock) eq 'ARRAY') {
                   10888:                             my ($symb,$crsid) = @{$lock};
                   10889:                             if ($crsid eq $env{'request.course.id'}) {
                   10890:                                 if (ref($navmap)) {
                   10891:                                     my $res = $navmap->getBySymb($symb);
                   10892:                                     foreach my $part (@{$res->parts()}) { 
                   10893:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10894:                                         unless (($slot_status == $res->RESERVED) ||
                   10895:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10896:                                             $locked_file = 1;
                   10897:                                         }
1.991     raeburn  10898:                                     }
1.1021    raeburn  10899:                                 } else {
                   10900:                                     $locked_file = 1;
1.991     raeburn  10901:                                 }
                   10902:                             } else {
                   10903:                                 $locked_file = 1;
                   10904:                             }
                   10905:                         }
1.1021    raeburn  10906:                    }
                   10907:                 } else {
                   10908:                     my @info = split(/\&/,$rest);
                   10909:                     my $currsize = $info[6]/1000;
                   10910:                     if ($currsize < $filesize) {
                   10911:                         my $extra = $filesize - $currsize;
                   10912:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10913:                             my $msg = '<span class="LC_error">'.
                   10914:                                       &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.',
                   10915:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10916:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10917:                                                    $disk_quota,$current_disk_usage);
                   10918:                             return ('will_exceed_quota',$msg);
                   10919:                         }
1.984     raeburn  10920:                     }
                   10921:                 }
1.661     raeburn  10922:             }
                   10923:         }
                   10924:     }
                   10925:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10926:         my $msg = '<span class="LC_error">'.
                   10927:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10928:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10929:         return ('will_exceed_quota',$msg);
                   10930:     } elsif ($found_file) {
                   10931:         if ($locked_file) {
                   10932:             my $msg = '<span class="LC_error">';
                   10933:             $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>');
                   10934:             $msg .= '</span><br />';
                   10935:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10936:             return ('file_locked',$msg);
                   10937:         } else {
                   10938:             my $msg = '<span class="LC_error">';
1.984     raeburn  10939:             $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  10940:             $msg .= '</span>';
1.984     raeburn  10941:             return ('existingfile',$msg);
1.661     raeburn  10942:         }
                   10943:     }
                   10944: }
                   10945: 
1.987     raeburn  10946: sub check_for_traversal {
                   10947:     my ($path,$url,$toplevel) = @_;
                   10948:     my @parts=split(/\//,$path);
                   10949:     my $cleanpath;
                   10950:     my $fullpath = $url;
                   10951:     for (my $i=0;$i<@parts;$i++) {
                   10952:         next if ($parts[$i] eq '.');
                   10953:         if ($parts[$i] eq '..') {
                   10954:             $fullpath =~ s{([^/]+/)$}{};
                   10955:         } else {
                   10956:             $fullpath .= $parts[$i].'/';
                   10957:         }
                   10958:     }
                   10959:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10960:         $cleanpath = $1;
                   10961:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10962:         my $curr_toprel = $1;
                   10963:         my @parts = split(/\//,$curr_toprel);
                   10964:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10965:         my @urlparts = split(/\//,$url_toprel);
                   10966:         my $doubledots;
                   10967:         my $startdiff = -1;
                   10968:         for (my $i=0; $i<@urlparts; $i++) {
                   10969:             if ($startdiff == -1) {
                   10970:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10971:                     $startdiff = $i;
                   10972:                     $doubledots .= '../';
                   10973:                 }
                   10974:             } else {
                   10975:                 $doubledots .= '../';
                   10976:             }
                   10977:         }
                   10978:         if ($startdiff > -1) {
                   10979:             $cleanpath = $doubledots;
                   10980:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10981:                 $cleanpath .= $parts[$i].'/';
                   10982:             }
                   10983:         }
                   10984:     }
                   10985:     $cleanpath =~ s{(/)$}{};
                   10986:     return $cleanpath;
                   10987: }
1.31      albertel 10988: 
1.1053    raeburn  10989: sub is_archive_file {
                   10990:     my ($mimetype) = @_;
                   10991:     if (($mimetype eq 'application/octet-stream') ||
                   10992:         ($mimetype eq 'application/x-stuffit') ||
                   10993:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10994:         return 1;
                   10995:     }
                   10996:     return;
                   10997: }
                   10998: 
                   10999: sub decompress_form {
1.1065    raeburn  11000:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11001:     my %lt = &Apache::lonlocal::texthash (
                   11002:         this => 'This file is an archive file.',
1.1067    raeburn  11003:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11004:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11005:         youm => 'You may wish to extract its contents.',
                   11006:         extr => 'Extract contents',
1.1067    raeburn  11007:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11008:         proa => 'Process automatically?',
1.1053    raeburn  11009:         yes  => 'Yes',
                   11010:         no   => 'No',
1.1067    raeburn  11011:         fold => 'Title for folder containing movie',
                   11012:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11013:     );
1.1065    raeburn  11014:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11015:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11016:     my $info = &list_archive_contents($fileloc,\@paths);
                   11017:     if (@paths) {
                   11018:         foreach my $path (@paths) {
                   11019:             $path =~ s{^/}{};
1.1067    raeburn  11020:             if ($path =~ m{^([^/]+)/$}) {
                   11021:                 $topdir = $1;
                   11022:             }
1.1065    raeburn  11023:             if ($path =~ m{^([^/]+)/}) {
                   11024:                 $toplevel{$1} = $path;
                   11025:             } else {
                   11026:                 $toplevel{$path} = $path;
                   11027:             }
                   11028:         }
                   11029:     }
1.1067    raeburn  11030:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11031:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11032:                         "$topdir/media/",
                   11033:                         "$topdir/media/$topdir.mp4",
                   11034:                         "$topdir/media/FirstFrame.png",
                   11035:                         "$topdir/media/player.swf",
                   11036:                         "$topdir/media/swfobject.js",
                   11037:                         "$topdir/media/expressInstall.swf");
1.1075.2.59  raeburn  11038:         my @camtasia8 = ("$topdir/","$topdir/$topdir.html",
                   11039:                          "$topdir/$topdir.mp4",
                   11040:                          "$topdir/$topdir\_config.xml",
                   11041:                          "$topdir/$topdir\_controller.swf",
                   11042:                          "$topdir/$topdir\_embed.css",
                   11043:                          "$topdir/$topdir\_First_Frame.png",
                   11044:                          "$topdir/$topdir\_player.html",
                   11045:                          "$topdir/$topdir\_Thumbnails.png",
                   11046:                          "$topdir/playerProductInstall.swf",
                   11047:                          "$topdir/scripts/",
                   11048:                          "$topdir/scripts/config_xml.js",
                   11049:                          "$topdir/scripts/handlebars.js",
                   11050:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11051:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11052:                          "$topdir/scripts/modernizr.js",
                   11053:                          "$topdir/scripts/player-min.js",
                   11054:                          "$topdir/scripts/swfobject.js",
                   11055:                          "$topdir/skins/",
                   11056:                          "$topdir/skins/configuration_express.xml",
                   11057:                          "$topdir/skins/express_show/",
                   11058:                          "$topdir/skins/express_show/player-min.css",
                   11059:                          "$topdir/skins/express_show/spritesheet.png");
                   11060:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11061:         if (@diffs == 0) {
1.1075.2.59  raeburn  11062:             $is_camtasia = 6;
                   11063:         } else {
                   11064:             @diffs = &compare_arrays(\@paths,\@camtasia8);
                   11065:             if (@diffs == 0) {
                   11066:                 $is_camtasia = 8;
                   11067:             }
1.1067    raeburn  11068:         }
                   11069:     }
                   11070:     my $output;
                   11071:     if ($is_camtasia) {
                   11072:         $output = <<"ENDCAM";
                   11073: <script type="text/javascript" language="Javascript">
                   11074: // <![CDATA[
                   11075: 
                   11076: function camtasiaToggle() {
                   11077:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11078:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11079:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11080:                 document.getElementById('camtasia_titles').style.display='block';
                   11081:             } else {
                   11082:                 document.getElementById('camtasia_titles').style.display='none';
                   11083:             }
                   11084:         }
                   11085:     }
                   11086:     return;
                   11087: }
                   11088: 
                   11089: // ]]>
                   11090: </script>
                   11091: <p>$lt{'camt'}</p>
                   11092: ENDCAM
1.1065    raeburn  11093:     } else {
1.1067    raeburn  11094:         $output = '<p>'.$lt{'this'};
                   11095:         if ($info eq '') {
                   11096:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11097:         } else {
                   11098:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11099:                        '<div><pre>'.$info.'</pre></div>';
                   11100:         }
1.1065    raeburn  11101:     }
1.1067    raeburn  11102:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11103:     my $duplicates;
                   11104:     my $num = 0;
                   11105:     if (ref($dirlist) eq 'ARRAY') {
                   11106:         foreach my $item (@{$dirlist}) {
                   11107:             if (ref($item) eq 'ARRAY') {
                   11108:                 if (exists($toplevel{$item->[0]})) {
                   11109:                     $duplicates .= 
                   11110:                         &start_data_table_row().
                   11111:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11112:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11113:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11114:                         'value="1" />'.&mt('Yes').'</label>'.
                   11115:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11116:                         '<td>'.$item->[0].'</td>';
                   11117:                     if ($item->[2]) {
                   11118:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11119:                     } else {
                   11120:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11121:                     }
                   11122:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11123:                                    '<td>'.
                   11124:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11125:                                    '</td>'.
                   11126:                                    &end_data_table_row();
                   11127:                     $num ++;
                   11128:                 }
                   11129:             }
                   11130:         }
                   11131:     }
                   11132:     my $itemcount;
                   11133:     if (@paths > 0) {
                   11134:         $itemcount = scalar(@paths);
                   11135:     } else {
                   11136:         $itemcount = 1;
                   11137:     }
1.1067    raeburn  11138:     if ($is_camtasia) {
                   11139:         $output .= $lt{'auto'}.'<br />'.
                   11140:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11141:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11142:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11143:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11144:                    $lt{'no'}.'</label></span><br />'.
                   11145:                    '<div id="camtasia_titles" style="display:block">'.
                   11146:                    &Apache::lonhtmlcommon::start_pick_box().
                   11147:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11148:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11149:                    &Apache::lonhtmlcommon::row_closure().
                   11150:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11151:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11152:                    &Apache::lonhtmlcommon::row_closure(1).
                   11153:                    &Apache::lonhtmlcommon::end_pick_box().
                   11154:                    '</div>';
                   11155:     }
1.1065    raeburn  11156:     $output .= 
                   11157:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11158:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11159:         "\n";
1.1065    raeburn  11160:     if ($duplicates ne '') {
                   11161:         $output .= '<p><span class="LC_warning">'.
                   11162:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11163:                    &start_data_table().
                   11164:                    &start_data_table_header_row().
                   11165:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11166:                    '<th>'.&mt('Name').'</th>'.
                   11167:                    '<th>'.&mt('Type').'</th>'.
                   11168:                    '<th>'.&mt('Size').'</th>'.
                   11169:                    '<th>'.&mt('Last modified').'</th>'.
                   11170:                    &end_data_table_header_row().
                   11171:                    $duplicates.
                   11172:                    &end_data_table().
                   11173:                    '</p>';
                   11174:     }
1.1067    raeburn  11175:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11176:     if (ref($hiddenelements) eq 'HASH') {
                   11177:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11178:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11179:         }
                   11180:     }
                   11181:     $output .= <<"END";
1.1067    raeburn  11182: <br />
1.1053    raeburn  11183: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11184: </form>
                   11185: $noextract
                   11186: END
                   11187:     return $output;
                   11188: }
                   11189: 
1.1065    raeburn  11190: sub decompression_utility {
                   11191:     my ($program) = @_;
                   11192:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11193:     my $location;
                   11194:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11195:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11196:                          '/usr/sbin/') {
                   11197:             if (-x $dir.$program) {
                   11198:                 $location = $dir.$program;
                   11199:                 last;
                   11200:             }
                   11201:         }
                   11202:     }
                   11203:     return $location;
                   11204: }
                   11205: 
                   11206: sub list_archive_contents {
                   11207:     my ($file,$pathsref) = @_;
                   11208:     my (@cmd,$output);
                   11209:     my $needsregexp;
                   11210:     if ($file =~ /\.zip$/) {
                   11211:         @cmd = (&decompression_utility('unzip'),"-l");
                   11212:         $needsregexp = 1;
                   11213:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11214:              ($file =~ /\.tgz$/)) {
                   11215:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11216:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11217:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11218:     } elsif ($file =~ m|\.tar$|) {
                   11219:         @cmd = (&decompression_utility('tar'),"-tf");
                   11220:     }
                   11221:     if (@cmd) {
                   11222:         undef($!);
                   11223:         undef($@);
                   11224:         if (open(my $fh,"-|", @cmd, $file)) {
                   11225:             while (my $line = <$fh>) {
                   11226:                 $output .= $line;
                   11227:                 chomp($line);
                   11228:                 my $item;
                   11229:                 if ($needsregexp) {
                   11230:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11231:                 } else {
                   11232:                     $item = $line;
                   11233:                 }
                   11234:                 if ($item ne '') {
                   11235:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11236:                         push(@{$pathsref},$item);
                   11237:                     } 
                   11238:                 }
                   11239:             }
                   11240:             close($fh);
                   11241:         }
                   11242:     }
                   11243:     return $output;
                   11244: }
                   11245: 
1.1053    raeburn  11246: sub decompress_uploaded_file {
                   11247:     my ($file,$dir) = @_;
                   11248:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11249:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11250:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11251:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11252:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11253:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11254:     my $decompressed = $env{'cgi.decompressed'};
                   11255:     &Apache::lonnet::delenv('cgi.file');
                   11256:     &Apache::lonnet::delenv('cgi.dir');
                   11257:     &Apache::lonnet::delenv('cgi.decompressed');
                   11258:     return ($decompressed,$result);
                   11259: }
                   11260: 
1.1055    raeburn  11261: sub process_decompression {
                   11262:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11263:     my ($dir,$error,$warning,$output);
                   11264:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
1.1075.2.34  raeburn  11265:         $error = &mt('Filename not a supported archive file type.').
                   11266:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11267:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11268:     } else {
                   11269:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11270:         if ($docuhome eq 'no_host') {
                   11271:             $error = &mt('Could not determine home server for course.');
                   11272:         } else {
                   11273:             my @ids=&Apache::lonnet::current_machine_ids();
                   11274:             my $currdir = "$dir_root/$destination";
                   11275:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11276:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11277:                        "$dir_root/$destination";
                   11278:             } else {
                   11279:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11280:                        "$dir_root/$docudom/$docuname/$destination";
                   11281:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11282:                     $error = &mt('Archive file not found.');
                   11283:                 }
                   11284:             }
1.1065    raeburn  11285:             my (@to_overwrite,@to_skip);
                   11286:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11287:                 my $total = $env{'form.archive_overwrite_total'};
                   11288:                 for (my $i=0; $i<$total; $i++) {
                   11289:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11290:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11291:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11292:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11293:                     }
                   11294:                 }
                   11295:             }
                   11296:             my $numskip = scalar(@to_skip);
                   11297:             if (($numskip > 0) && 
                   11298:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11299:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11300:             } elsif ($dir eq '') {
1.1055    raeburn  11301:                 $error = &mt('Directory containing archive file unavailable.');
                   11302:             } elsif (!$error) {
1.1065    raeburn  11303:                 my ($decompressed,$display);
                   11304:                 if ($numskip > 0) {
                   11305:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11306:                     mkdir("$dir/$tempdir",0755);
                   11307:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11308:                     ($decompressed,$display) = 
                   11309:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11310:                     foreach my $item (@to_skip) {
                   11311:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11312:                             if (-f "$dir/$tempdir/$item") { 
                   11313:                                 unlink("$dir/$tempdir/$item");
                   11314:                             } elsif (-d "$dir/$tempdir/$item") {
                   11315:                                 system("rm -rf $dir/$tempdir/$item");
                   11316:                             }
                   11317:                         }
                   11318:                     }
                   11319:                     system("mv $dir/$tempdir/* $dir");
                   11320:                     rmdir("$dir/$tempdir");   
                   11321:                 } else {
                   11322:                     ($decompressed,$display) = 
                   11323:                         &decompress_uploaded_file($file,$dir);
                   11324:                 }
1.1055    raeburn  11325:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11326:                     $output = '<p class="LC_info">'.
                   11327:                               &mt('Files extracted successfully from archive.').
                   11328:                               '</p>'."\n";
1.1055    raeburn  11329:                     my ($warning,$result,@contents);
                   11330:                     my ($newdirlistref,$newlisterror) =
                   11331:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11332:                                                  $docuname,1);
                   11333:                     my (%is_dir,%changes,@newitems);
                   11334:                     my $dirptr = 16384;
1.1065    raeburn  11335:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11336:                         foreach my $dir_line (@{$newdirlistref}) {
                   11337:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11338:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11339:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11340:                                 push(@newitems,$item);
                   11341:                                 if ($dirptr&$testdir) {
                   11342:                                     $is_dir{$item} = 1;
                   11343:                                 }
                   11344:                                 $changes{$item} = 1;
                   11345:                             }
                   11346:                         }
                   11347:                     }
                   11348:                     if (keys(%changes) > 0) {
                   11349:                         foreach my $item (sort(@newitems)) {
                   11350:                             if ($changes{$item}) {
                   11351:                                 push(@contents,$item);
                   11352:                             }
                   11353:                         }
                   11354:                     }
                   11355:                     if (@contents > 0) {
1.1067    raeburn  11356:                         my $wantform;
                   11357:                         unless ($env{'form.autoextract_camtasia'}) {
                   11358:                             $wantform = 1;
                   11359:                         }
1.1056    raeburn  11360:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11361:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11362:                                                                 $currdir,\%is_dir,
                   11363:                                                                 \%children,\%parent,
1.1056    raeburn  11364:                                                                 \@contents,\%dirorder,
                   11365:                                                                 \%titles,$wantform);
1.1055    raeburn  11366:                         if ($datatable ne '') {
                   11367:                             $output .= &archive_options_form('decompressed',$datatable,
                   11368:                                                              $count,$hiddenelem);
1.1065    raeburn  11369:                             my $startcount = 6;
1.1055    raeburn  11370:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11371:                                                            \%titles,\%children);
1.1055    raeburn  11372:                         }
1.1067    raeburn  11373:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  11374:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11375:                             my %displayed;
                   11376:                             my $total = 1;
                   11377:                             $env{'form.archive_directory'} = [];
                   11378:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11379:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11380:                                 $path =~ s{/$}{};
                   11381:                                 my $item;
                   11382:                                 if ($path ne '') {
                   11383:                                     $item = "$path/$titles{$i}";
                   11384:                                 } else {
                   11385:                                     $item = $titles{$i};
                   11386:                                 }
                   11387:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11388:                                 if ($item eq $contents[0]) {
                   11389:                                     push(@{$env{'form.archive_directory'}},$i);
                   11390:                                     $env{'form.archive_'.$i} = 'display';
                   11391:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11392:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  11393:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11394:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  11395:                                     $env{'form.archive_'.$i} = 'display';
                   11396:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11397:                                     $displayed{'web'} = $i;
                   11398:                                 } else {
1.1075.2.59  raeburn  11399:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11400:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11401:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11402:                                         push(@{$env{'form.archive_directory'}},$i);
                   11403:                                     }
                   11404:                                     $env{'form.archive_'.$i} = 'dependency';
                   11405:                                 }
                   11406:                                 $total ++;
                   11407:                             }
                   11408:                             for (my $i=1; $i<$total; $i++) {
                   11409:                                 next if ($i == $displayed{'web'});
                   11410:                                 next if ($i == $displayed{'folder'});
                   11411:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11412:                             }
                   11413:                             $env{'form.phase'} = 'decompress_cleanup';
                   11414:                             $env{'form.archivedelete'} = 1;
                   11415:                             $env{'form.archive_count'} = $total-1;
                   11416:                             $output .=
                   11417:                                 &process_extracted_files('coursedocs',$docudom,
                   11418:                                                          $docuname,$destination,
                   11419:                                                          $dir_root,$hiddenelem);
                   11420:                         }
1.1055    raeburn  11421:                     } else {
                   11422:                         $warning = &mt('No new items extracted from archive file.');
                   11423:                     }
                   11424:                 } else {
                   11425:                     $output = $display;
                   11426:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11427:                 }
                   11428:             }
                   11429:         }
                   11430:     }
                   11431:     if ($error) {
                   11432:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11433:                    $error.'</p>'."\n";
                   11434:     }
                   11435:     if ($warning) {
                   11436:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11437:     }
                   11438:     return $output;
                   11439: }
                   11440: 
                   11441: sub get_extracted {
1.1056    raeburn  11442:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11443:         $titles,$wantform) = @_;
1.1055    raeburn  11444:     my $count = 0;
                   11445:     my $depth = 0;
                   11446:     my $datatable;
1.1056    raeburn  11447:     my @hierarchy;
1.1055    raeburn  11448:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11449:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11450:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11451:     foreach my $item (@{$contents}) {
                   11452:         $count ++;
1.1056    raeburn  11453:         @{$dirorder->{$count}} = @hierarchy;
                   11454:         $titles->{$count} = $item;
1.1055    raeburn  11455:         &archive_hierarchy($depth,$count,$parent,$children);
                   11456:         if ($wantform) {
                   11457:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11458:                                        $currdir,$depth,$count);
                   11459:         }
                   11460:         if ($is_dir->{$item}) {
                   11461:             $depth ++;
1.1056    raeburn  11462:             push(@hierarchy,$count);
                   11463:             $parent->{$depth} = $count;
1.1055    raeburn  11464:             $datatable .=
                   11465:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11466:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11467:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11468:             $depth --;
1.1056    raeburn  11469:             pop(@hierarchy);
1.1055    raeburn  11470:         }
                   11471:     }
                   11472:     return ($count,$datatable);
                   11473: }
                   11474: 
                   11475: sub recurse_extracted_archive {
1.1056    raeburn  11476:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11477:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11478:     my $result='';
1.1056    raeburn  11479:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11480:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11481:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11482:         return $result;
                   11483:     }
                   11484:     my $dirptr = 16384;
                   11485:     my ($newdirlistref,$newlisterror) =
                   11486:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11487:     if (ref($newdirlistref) eq 'ARRAY') {
                   11488:         foreach my $dir_line (@{$newdirlistref}) {
                   11489:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11490:             unless ($item =~ /^\.+$/) {
                   11491:                 $$count ++;
1.1056    raeburn  11492:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11493:                 $titles->{$$count} = $item;
1.1055    raeburn  11494:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11495: 
1.1055    raeburn  11496:                 my $is_dir;
                   11497:                 if ($dirptr&$testdir) {
                   11498:                     $is_dir = 1;
                   11499:                 }
                   11500:                 if ($wantform) {
                   11501:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11502:                 }
                   11503:                 if ($is_dir) {
                   11504:                     $$depth ++;
1.1056    raeburn  11505:                     push(@{$hierarchy},$$count);
                   11506:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11507:                     $result .=
                   11508:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11509:                                                    $docuname,$depth,$count,
1.1056    raeburn  11510:                                                    $hierarchy,$dirorder,$children,
                   11511:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11512:                     $$depth --;
1.1056    raeburn  11513:                     pop(@{$hierarchy});
1.1055    raeburn  11514:                 }
                   11515:             }
                   11516:         }
                   11517:     }
                   11518:     return $result;
                   11519: }
                   11520: 
                   11521: sub archive_hierarchy {
                   11522:     my ($depth,$count,$parent,$children) =@_;
                   11523:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11524:         if (exists($parent->{$depth})) {
                   11525:              $children->{$parent->{$depth}} .= $count.':';
                   11526:         }
                   11527:     }
                   11528:     return;
                   11529: }
                   11530: 
                   11531: sub archive_row {
                   11532:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11533:     my ($name) = ($item =~ m{([^/]+)$});
                   11534:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11535:                                        'display'    => 'Add as file',
1.1055    raeburn  11536:                                        'dependency' => 'Include as dependency',
                   11537:                                        'discard'    => 'Discard',
                   11538:                                       );
                   11539:     if ($is_dir) {
1.1059    raeburn  11540:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11541:     }
1.1056    raeburn  11542:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11543:     my $offset = 0;
1.1055    raeburn  11544:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11545:         $offset ++;
1.1065    raeburn  11546:         if ($action ne 'display') {
                   11547:             $offset ++;
                   11548:         }  
1.1055    raeburn  11549:         $output .= '<td><span class="LC_nobreak">'.
                   11550:                    '<label><input type="radio" name="archive_'.$count.
                   11551:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11552:         my $text = $choices{$action};
                   11553:         if ($is_dir) {
                   11554:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11555:             if ($action eq 'display') {
1.1059    raeburn  11556:                 $text = &mt('Add as folder');
1.1055    raeburn  11557:             }
1.1056    raeburn  11558:         } else {
                   11559:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11560: 
                   11561:         }
                   11562:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11563:         if ($action eq 'dependency') {
                   11564:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11565:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11566:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11567:                        '<option value=""></option>'."\n".
                   11568:                        '</select>'."\n".
                   11569:                        '</div>';
1.1059    raeburn  11570:         } elsif ($action eq 'display') {
                   11571:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11572:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11573:                        '</div>';
1.1055    raeburn  11574:         }
1.1056    raeburn  11575:         $output .= '</td>';
1.1055    raeburn  11576:     }
                   11577:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11578:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11579:     for (my $i=0; $i<$depth; $i++) {
                   11580:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11581:     }
                   11582:     if ($is_dir) {
                   11583:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11584:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11585:     } else {
                   11586:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11587:     }
                   11588:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11589:                &end_data_table_row();
                   11590:     return $output;
                   11591: }
                   11592: 
                   11593: sub archive_options_form {
1.1065    raeburn  11594:     my ($form,$display,$count,$hiddenelem) = @_;
                   11595:     my %lt = &Apache::lonlocal::texthash(
                   11596:                perm => 'Permanently remove archive file?',
                   11597:                hows => 'How should each extracted item be incorporated in the course?',
                   11598:                cont => 'Content actions for all',
                   11599:                addf => 'Add as folder/file',
                   11600:                incd => 'Include as dependency for a displayed file',
                   11601:                disc => 'Discard',
                   11602:                no   => 'No',
                   11603:                yes  => 'Yes',
                   11604:                save => 'Save',
                   11605:     );
                   11606:     my $output = <<"END";
                   11607: <form name="$form" method="post" action="">
                   11608: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11609: <label>
                   11610:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11611: </label>
                   11612: &nbsp;
                   11613: <label>
                   11614:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11615: </span>
                   11616: </p>
                   11617: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11618: <br />$lt{'hows'}
                   11619: <div class="LC_columnSection">
                   11620:   <fieldset>
                   11621:     <legend>$lt{'cont'}</legend>
                   11622:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11623:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11624:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11625:   </fieldset>
                   11626: </div>
                   11627: END
                   11628:     return $output.
1.1055    raeburn  11629:            &start_data_table()."\n".
1.1065    raeburn  11630:            $display."\n".
1.1055    raeburn  11631:            &end_data_table()."\n".
                   11632:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11633:            $hiddenelem.
1.1065    raeburn  11634:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11635:            '</form>';
                   11636: }
                   11637: 
                   11638: sub archive_javascript {
1.1056    raeburn  11639:     my ($startcount,$numitems,$titles,$children) = @_;
                   11640:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11641:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11642:     my $scripttag = <<START;
                   11643: <script type="text/javascript">
                   11644: // <![CDATA[
                   11645: 
                   11646: function checkAll(form,prefix) {
                   11647:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11648:     for (var i=0; i < form.elements.length; i++) {
                   11649:         var id = form.elements[i].id;
                   11650:         if ((id != '') && (id != undefined)) {
                   11651:             if (idstr.test(id)) {
                   11652:                 if (form.elements[i].type == 'radio') {
                   11653:                     form.elements[i].checked = true;
1.1056    raeburn  11654:                     var nostart = i-$startcount;
1.1059    raeburn  11655:                     var offset = nostart%7;
                   11656:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11657:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11658:                 }
                   11659:             }
                   11660:         }
                   11661:     }
                   11662: }
                   11663: 
                   11664: function propagateCheck(form,count) {
                   11665:     if (count > 0) {
1.1059    raeburn  11666:         var startelement = $startcount + ((count-1) * 7);
                   11667:         for (var j=1; j<6; j++) {
                   11668:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11669:                 var item = startelement + j; 
                   11670:                 if (form.elements[item].type == 'radio') {
                   11671:                     if (form.elements[item].checked) {
                   11672:                         containerCheck(form,count,j);
                   11673:                         break;
                   11674:                     }
1.1055    raeburn  11675:                 }
                   11676:             }
                   11677:         }
                   11678:     }
                   11679: }
                   11680: 
                   11681: numitems = $numitems
1.1056    raeburn  11682: var titles = new Array(numitems);
                   11683: var parents = new Array(numitems);
1.1055    raeburn  11684: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11685:     parents[i] = new Array;
1.1055    raeburn  11686: }
1.1059    raeburn  11687: var maintitle = '$maintitle';
1.1055    raeburn  11688: 
                   11689: START
                   11690: 
1.1056    raeburn  11691:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11692:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11693:         for (my $i=0; $i<@contents; $i ++) {
                   11694:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11695:         }
                   11696:     }
                   11697: 
1.1056    raeburn  11698:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11699:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11700:     }
                   11701: 
1.1055    raeburn  11702:     $scripttag .= <<END;
                   11703: 
                   11704: function containerCheck(form,count,offset) {
                   11705:     if (count > 0) {
1.1056    raeburn  11706:         dependencyCheck(form,count,offset);
1.1059    raeburn  11707:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11708:         form.elements[item].checked = true;
                   11709:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11710:             if (parents[count].length > 0) {
                   11711:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11712:                     containerCheck(form,parents[count][j],offset);
                   11713:                 }
                   11714:             }
                   11715:         }
                   11716:     }
                   11717: }
                   11718: 
                   11719: function dependencyCheck(form,count,offset) {
                   11720:     if (count > 0) {
1.1059    raeburn  11721:         var chosen = (offset+$startcount)+7*(count-1);
                   11722:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11723:         var currtype = form.elements[depitem].type;
                   11724:         if (form.elements[chosen].value == 'dependency') {
                   11725:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11726:             form.elements[depitem].options.length = 0;
                   11727:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  11728:             for (var i=1; i<=numitems; i++) {
                   11729:                 if (i == count) {
                   11730:                     continue;
                   11731:                 }
1.1059    raeburn  11732:                 var startelement = $startcount + (i-1) * 7;
                   11733:                 for (var j=1; j<6; j++) {
                   11734:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11735:                         var item = startelement + j;
                   11736:                         if (form.elements[item].type == 'radio') {
                   11737:                             if (form.elements[item].checked) {
                   11738:                                 if (form.elements[item].value == 'display') {
                   11739:                                     var n = form.elements[depitem].options.length;
                   11740:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11741:                                 }
                   11742:                             }
                   11743:                         }
                   11744:                     }
                   11745:                 }
                   11746:             }
                   11747:         } else {
                   11748:             document.getElementById('arc_depon_'+count).style.display='none';
                   11749:             form.elements[depitem].options.length = 0;
                   11750:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11751:         }
1.1059    raeburn  11752:         titleCheck(form,count,offset);
1.1056    raeburn  11753:     }
                   11754: }
                   11755: 
                   11756: function propagateSelect(form,count,offset) {
                   11757:     if (count > 0) {
1.1065    raeburn  11758:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11759:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11760:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11761:             if (parents[count].length > 0) {
                   11762:                 for (var j=0; j<parents[count].length; j++) {
                   11763:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11764:                 }
                   11765:             }
                   11766:         }
                   11767:     }
                   11768: }
1.1056    raeburn  11769: 
                   11770: function containerSelect(form,count,offset,picked) {
                   11771:     if (count > 0) {
1.1065    raeburn  11772:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11773:         if (form.elements[item].type == 'radio') {
                   11774:             if (form.elements[item].value == 'dependency') {
                   11775:                 if (form.elements[item+1].type == 'select-one') {
                   11776:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11777:                         if (form.elements[item+1].options[i].value == picked) {
                   11778:                             form.elements[item+1].selectedIndex = i;
                   11779:                             break;
                   11780:                         }
                   11781:                     }
                   11782:                 }
                   11783:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11784:                     if (parents[count].length > 0) {
                   11785:                         for (var j=0; j<parents[count].length; j++) {
                   11786:                             containerSelect(form,parents[count][j],offset,picked);
                   11787:                         }
                   11788:                     }
                   11789:                 }
                   11790:             }
                   11791:         }
                   11792:     }
                   11793: }
                   11794: 
1.1059    raeburn  11795: function titleCheck(form,count,offset) {
                   11796:     if (count > 0) {
                   11797:         var chosen = (offset+$startcount)+7*(count-1);
                   11798:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11799:         var currtype = form.elements[depitem].type;
                   11800:         if (form.elements[chosen].value == 'display') {
                   11801:             document.getElementById('arc_title_'+count).style.display='block';
                   11802:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11803:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11804:             }
                   11805:         } else {
                   11806:             document.getElementById('arc_title_'+count).style.display='none';
                   11807:             if (currtype == 'text') { 
                   11808:                 document.getElementById('archive_title_'+count).value='';
                   11809:             }
                   11810:         }
                   11811:     }
                   11812:     return;
                   11813: }
                   11814: 
1.1055    raeburn  11815: // ]]>
                   11816: </script>
                   11817: END
                   11818:     return $scripttag;
                   11819: }
                   11820: 
                   11821: sub process_extracted_files {
1.1067    raeburn  11822:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11823:     my $numitems = $env{'form.archive_count'};
                   11824:     return unless ($numitems);
                   11825:     my @ids=&Apache::lonnet::current_machine_ids();
                   11826:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11827:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11828:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11829:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11830:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11831:         $pathtocheck = "$dir_root/$destination";
                   11832:         $dir = $dir_root;
                   11833:         $ishome = 1;
                   11834:     } else {
                   11835:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11836:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11837:         $dir = "$dir_root/$docudom/$docuname";    
                   11838:     }
                   11839:     my $currdir = "$dir_root/$destination";
                   11840:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11841:     if ($env{'form.folderpath'}) {
                   11842:         my @items = split('&',$env{'form.folderpath'});
                   11843:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  11844:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   11845:             $containers{'0'}='page';
                   11846:         } else {
                   11847:             $containers{'0'}='sequence';
                   11848:         }
1.1055    raeburn  11849:     }
                   11850:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11851:     if ($numitems) {
                   11852:         for (my $i=1; $i<=$numitems; $i++) {
                   11853:             my $path = $env{'form.archive_content_'.$i};
                   11854:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11855:                 my $item = $1;
                   11856:                 $toplevelitems{$item} = $i;
                   11857:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11858:                     $is_dir{$item} = 1;
                   11859:                 }
                   11860:             }
                   11861:         }
                   11862:     }
1.1067    raeburn  11863:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11864:     if (keys(%toplevelitems) > 0) {
                   11865:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11866:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11867:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11868:     }
1.1066    raeburn  11869:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11870:     if ($numitems) {
                   11871:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  11872:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11873:             my $path = $env{'form.archive_content_'.$i};
                   11874:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11875:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11876:                     if ($prefix ne '' && $path ne '') {
                   11877:                         if (-e $prefix.$path) {
1.1066    raeburn  11878:                             if ((@archdirs > 0) && 
                   11879:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11880:                                 $todeletedir{$prefix.$path} = 1;
                   11881:                             } else {
                   11882:                                 $todelete{$prefix.$path} = 1;
                   11883:                             }
1.1055    raeburn  11884:                         }
                   11885:                     }
                   11886:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11887:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11888:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11889:                     $docstitle = $env{'form.archive_title_'.$i};
                   11890:                     if ($docstitle eq '') {
                   11891:                         $docstitle = $title;
                   11892:                     }
1.1055    raeburn  11893:                     $outer = 0;
1.1056    raeburn  11894:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11895:                         if (@{$dirorder{$i}} > 0) {
                   11896:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11897:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11898:                                     $outer = $item;
                   11899:                                     last;
                   11900:                                 }
                   11901:                             }
                   11902:                         }
                   11903:                     }
                   11904:                     my ($errtext,$fatal) = 
                   11905:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11906:                                                '/'.$folders{$outer}.'.'.
                   11907:                                                $containers{$outer});
                   11908:                     next if ($fatal);
                   11909:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11910:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11911:                             $mapinner{$i} = time;
1.1055    raeburn  11912:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11913:                             $containers{$i} = 'sequence';
                   11914:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11915:                                       $folders{$i}.'.'.$containers{$i};
                   11916:                             my $newidx = &LONCAPA::map::getresidx();
                   11917:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11918:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11919:                             push(@LONCAPA::map::order,$newidx);
                   11920:                             my ($outtext,$errtext) =
                   11921:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11922:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  11923:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11924:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11925:                             unless ($errtext) {
                   11926:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11927:                             }
1.1055    raeburn  11928:                         }
                   11929:                     } else {
                   11930:                         if ($context eq 'coursedocs') {
                   11931:                             my $newidx=&LONCAPA::map::getresidx();
                   11932:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11933:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11934:                                       $title;
                   11935:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11936:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11937:                             }
                   11938:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11939:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11940:                             }
                   11941:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11942:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11943:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11944:                                 unless ($ishome) {
                   11945:                                     my $fetch = "$newdest{$i}/$title";
                   11946:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11947:                                     $prompttofetch{$fetch} = 1;
                   11948:                                 }
1.1055    raeburn  11949:                             }
                   11950:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11951:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11952:                             push(@LONCAPA::map::order, $newidx);
                   11953:                             my ($outtext,$errtext)=
                   11954:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11955:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  11956:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11957:                             unless ($errtext) {
                   11958:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11959:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11960:                                 }
                   11961:                             }
1.1055    raeburn  11962:                         }
                   11963:                     }
1.1075.2.11  raeburn  11964:                 }
                   11965:             } else {
                   11966:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   11967:             }
                   11968:         }
                   11969:         for (my $i=1; $i<=$numitems; $i++) {
                   11970:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11971:             my $path = $env{'form.archive_content_'.$i};
                   11972:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11973:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11974:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11975:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11976:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11977:                         my ($itemidx,$fullpath,$relpath);
                   11978:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11979:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11980:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  11981:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11982:                                     $itemidx = $j;
1.1056    raeburn  11983:                                 }
                   11984:                             }
1.1075.2.11  raeburn  11985:                         }
                   11986:                         if ($itemidx eq '') {
                   11987:                             $itemidx =  0;
                   11988:                         }
                   11989:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11990:                             if ($mapinner{$referrer{$i}}) {
                   11991:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11992:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11993:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11994:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11995:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11996:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11997:                                             if (!-e $fullpath) {
                   11998:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11999:                                             }
                   12000:                                         }
1.1075.2.11  raeburn  12001:                                     } else {
                   12002:                                         last;
1.1056    raeburn  12003:                                     }
1.1075.2.11  raeburn  12004:                                 }
                   12005:                             }
                   12006:                         } elsif ($newdest{$referrer{$i}}) {
                   12007:                             $fullpath = $newdest{$referrer{$i}};
                   12008:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12009:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12010:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12011:                                     last;
                   12012:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12013:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12014:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12015:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12016:                                         if (!-e $fullpath) {
                   12017:                                             mkdir($fullpath,0755);
1.1056    raeburn  12018:                                         }
                   12019:                                     }
1.1075.2.11  raeburn  12020:                                 } else {
                   12021:                                     last;
1.1056    raeburn  12022:                                 }
1.1075.2.11  raeburn  12023:                             }
                   12024:                         }
                   12025:                         if ($fullpath ne '') {
                   12026:                             if (-e "$prefix$path") {
                   12027:                                 system("mv $prefix$path $fullpath/$title");
                   12028:                             }
                   12029:                             if (-e "$fullpath/$title") {
                   12030:                                 my $showpath;
                   12031:                                 if ($relpath ne '') {
                   12032:                                     $showpath = "$relpath/$title";
                   12033:                                 } else {
                   12034:                                     $showpath = "/$title";
1.1056    raeburn  12035:                                 }
1.1075.2.11  raeburn  12036:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12037:                             }
                   12038:                             unless ($ishome) {
                   12039:                                 my $fetch = "$fullpath/$title";
                   12040:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12041:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12042:                             }
                   12043:                         }
                   12044:                     }
1.1075.2.11  raeburn  12045:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12046:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12047:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12048:                 }
                   12049:             } else {
1.1075.2.11  raeburn  12050:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12051:             }
                   12052:         }
                   12053:         if (keys(%todelete)) {
                   12054:             foreach my $key (keys(%todelete)) {
                   12055:                 unlink($key);
1.1066    raeburn  12056:             }
                   12057:         }
                   12058:         if (keys(%todeletedir)) {
                   12059:             foreach my $key (keys(%todeletedir)) {
                   12060:                 rmdir($key);
                   12061:             }
                   12062:         }
                   12063:         foreach my $dir (sort(keys(%is_dir))) {
                   12064:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12065:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12066:             }
                   12067:         }
1.1067    raeburn  12068:         if ($result ne '') {
                   12069:             $output .= '<ul>'."\n".
                   12070:                        $result."\n".
                   12071:                        '</ul>';
                   12072:         }
                   12073:         unless ($ishome) {
                   12074:             my $replicationfail;
                   12075:             foreach my $item (keys(%prompttofetch)) {
                   12076:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12077:                 unless ($fetchresult eq 'ok') {
                   12078:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12079:                 }
                   12080:             }
                   12081:             if ($replicationfail) {
                   12082:                 $output .= '<p class="LC_error">'.
                   12083:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12084:                            $replicationfail.
                   12085:                            '</ul></p>';
                   12086:             }
                   12087:         }
1.1055    raeburn  12088:     } else {
                   12089:         $warning = &mt('No items found in archive.');
                   12090:     }
                   12091:     if ($error) {
                   12092:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12093:                    $error.'</p>'."\n";
                   12094:     }
                   12095:     if ($warning) {
                   12096:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12097:     }
                   12098:     return $output;
                   12099: }
                   12100: 
1.1066    raeburn  12101: sub cleanup_empty_dirs {
                   12102:     my ($path) = @_;
                   12103:     if (($path ne '') && (-d $path)) {
                   12104:         if (opendir(my $dirh,$path)) {
                   12105:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12106:             my $numitems = 0;
                   12107:             foreach my $item (@dircontents) {
                   12108:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12109:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12110:                     if (-e "$path/$item") {
                   12111:                         $numitems ++;
                   12112:                     }
                   12113:                 } else {
                   12114:                     $numitems ++;
                   12115:                 }
                   12116:             }
                   12117:             if ($numitems == 0) {
                   12118:                 rmdir($path);
                   12119:             }
                   12120:             closedir($dirh);
                   12121:         }
                   12122:     }
                   12123:     return;
                   12124: }
                   12125: 
1.41      ng       12126: =pod
1.45      matthew  12127: 
1.1075.2.56  raeburn  12128: =item * &get_folder_hierarchy()
1.1068    raeburn  12129: 
                   12130: Provides hierarchy of names of folders/sub-folders containing the current
                   12131: item,
                   12132: 
                   12133: Inputs: 3
                   12134:      - $navmap - navmaps object
                   12135: 
                   12136:      - $map - url for map (either the trigger itself, or map containing
                   12137:                            the resource, which is the trigger).
                   12138: 
                   12139:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12140: 
                   12141: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12142: 
                   12143: =cut
                   12144: 
                   12145: sub get_folder_hierarchy {
                   12146:     my ($navmap,$map,$showitem) = @_;
                   12147:     my @pathitems;
                   12148:     if (ref($navmap)) {
                   12149:         my $mapres = $navmap->getResourceByUrl($map);
                   12150:         if (ref($mapres)) {
                   12151:             my $pcslist = $mapres->map_hierarchy();
                   12152:             if ($pcslist ne '') {
                   12153:                 my @pcs = split(/,/,$pcslist);
                   12154:                 foreach my $pc (@pcs) {
                   12155:                     if ($pc == 1) {
1.1075.2.38  raeburn  12156:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12157:                     } else {
                   12158:                         my $res = $navmap->getByMapPc($pc);
                   12159:                         if (ref($res)) {
                   12160:                             my $title = $res->compTitle();
                   12161:                             $title =~ s/\W+/_/g;
                   12162:                             if ($title ne '') {
                   12163:                                 push(@pathitems,$title);
                   12164:                             }
                   12165:                         }
                   12166:                     }
                   12167:                 }
                   12168:             }
1.1071    raeburn  12169:             if ($showitem) {
                   12170:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12171:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12172:                 } else {
                   12173:                     my $maptitle = $mapres->compTitle();
                   12174:                     $maptitle =~ s/\W+/_/g;
                   12175:                     if ($maptitle ne '') {
                   12176:                         push(@pathitems,$maptitle);
                   12177:                     }
1.1068    raeburn  12178:                 }
                   12179:             }
                   12180:         }
                   12181:     }
                   12182:     return @pathitems;
                   12183: }
                   12184: 
                   12185: =pod
                   12186: 
1.1015    raeburn  12187: =item * &get_turnedin_filepath()
                   12188: 
                   12189: Determines path in a user's portfolio file for storage of files uploaded
                   12190: to a specific essayresponse or dropbox item.
                   12191: 
                   12192: Inputs: 3 required + 1 optional.
                   12193: $symb is symb for resource, $uname and $udom are for current user (required).
                   12194: $caller is optional (can be "submission", if routine is called when storing
                   12195: an upoaded file when "Submit Answer" button was pressed).
                   12196: 
                   12197: Returns array containing $path and $multiresp. 
                   12198: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12199: than one file upload item.  Callers of routine should append partid as a 
                   12200: subdirectory to $path in cases where $multiresp is 1.
                   12201: 
                   12202: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12203: 
                   12204: =cut
                   12205: 
                   12206: sub get_turnedin_filepath {
                   12207:     my ($symb,$uname,$udom,$caller) = @_;
                   12208:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12209:     my $turnindir;
                   12210:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12211:     $turnindir = $userhash{'turnindir'};
                   12212:     my ($path,$multiresp);
                   12213:     if ($turnindir eq '') {
                   12214:         if ($caller eq 'submission') {
                   12215:             $turnindir = &mt('turned in');
                   12216:             $turnindir =~ s/\W+/_/g;
                   12217:             my %newhash = (
                   12218:                             'turnindir' => $turnindir,
                   12219:                           );
                   12220:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12221:         }
                   12222:     }
                   12223:     if ($turnindir ne '') {
                   12224:         $path = '/'.$turnindir.'/';
                   12225:         my ($multipart,$turnin,@pathitems);
                   12226:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12227:         if (defined($navmap)) {
                   12228:             my $mapres = $navmap->getResourceByUrl($map);
                   12229:             if (ref($mapres)) {
                   12230:                 my $pcslist = $mapres->map_hierarchy();
                   12231:                 if ($pcslist ne '') {
                   12232:                     foreach my $pc (split(/,/,$pcslist)) {
                   12233:                         my $res = $navmap->getByMapPc($pc);
                   12234:                         if (ref($res)) {
                   12235:                             my $title = $res->compTitle();
                   12236:                             $title =~ s/\W+/_/g;
                   12237:                             if ($title ne '') {
1.1075.2.48  raeburn  12238:                                 if (($pc > 1) && (length($title) > 12)) {
                   12239:                                     $title = substr($title,0,12);
                   12240:                                 }
1.1015    raeburn  12241:                                 push(@pathitems,$title);
                   12242:                             }
                   12243:                         }
                   12244:                     }
                   12245:                 }
                   12246:                 my $maptitle = $mapres->compTitle();
                   12247:                 $maptitle =~ s/\W+/_/g;
                   12248:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12249:                     if (length($maptitle) > 12) {
                   12250:                         $maptitle = substr($maptitle,0,12);
                   12251:                     }
1.1015    raeburn  12252:                     push(@pathitems,$maptitle);
                   12253:                 }
                   12254:                 unless ($env{'request.state'} eq 'construct') {
                   12255:                     my $res = $navmap->getBySymb($symb);
                   12256:                     if (ref($res)) {
                   12257:                         my $partlist = $res->parts();
                   12258:                         my $totaluploads = 0;
                   12259:                         if (ref($partlist) eq 'ARRAY') {
                   12260:                             foreach my $part (@{$partlist}) {
                   12261:                                 my @types = $res->responseType($part);
                   12262:                                 my @ids = $res->responseIds($part);
                   12263:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12264:                                     if ($types[$i] eq 'essay') {
                   12265:                                         my $partid = $part.'_'.$ids[$i];
                   12266:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12267:                                             $totaluploads ++;
                   12268:                                         }
                   12269:                                     }
                   12270:                                 }
                   12271:                             }
                   12272:                             if ($totaluploads > 1) {
                   12273:                                 $multiresp = 1;
                   12274:                             }
                   12275:                         }
                   12276:                     }
                   12277:                 }
                   12278:             } else {
                   12279:                 return;
                   12280:             }
                   12281:         } else {
                   12282:             return;
                   12283:         }
                   12284:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12285:         $restitle =~ s/\W+/_/g;
                   12286:         if ($restitle eq '') {
                   12287:             $restitle = ($resurl =~ m{/[^/]+$});
                   12288:             if ($restitle eq '') {
                   12289:                 $restitle = time;
                   12290:             }
                   12291:         }
1.1075.2.48  raeburn  12292:         if (length($restitle) > 12) {
                   12293:             $restitle = substr($restitle,0,12);
                   12294:         }
1.1015    raeburn  12295:         push(@pathitems,$restitle);
                   12296:         $path .= join('/',@pathitems);
                   12297:     }
                   12298:     return ($path,$multiresp);
                   12299: }
                   12300: 
                   12301: =pod
                   12302: 
1.464     albertel 12303: =back
1.41      ng       12304: 
1.112     bowersj2 12305: =head1 CSV Upload/Handling functions
1.38      albertel 12306: 
1.41      ng       12307: =over 4
                   12308: 
1.648     raeburn  12309: =item * &upfile_store($r)
1.41      ng       12310: 
                   12311: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12312: needs $env{'form.upfile'}
1.41      ng       12313: returns $datatoken to be put into hidden field
                   12314: 
                   12315: =cut
1.31      albertel 12316: 
                   12317: sub upfile_store {
                   12318:     my $r=shift;
1.258     albertel 12319:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12320:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12321:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12322:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12323: 
1.258     albertel 12324:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12325: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12326:     {
1.158     raeburn  12327:         my $datafile = $r->dir_config('lonDaemons').
                   12328:                            '/tmp/'.$datatoken.'.tmp';
                   12329:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12330:             print $fh $env{'form.upfile'};
1.158     raeburn  12331:             close($fh);
                   12332:         }
1.31      albertel 12333:     }
                   12334:     return $datatoken;
                   12335: }
                   12336: 
1.56      matthew  12337: =pod
                   12338: 
1.648     raeburn  12339: =item * &load_tmp_file($r)
1.41      ng       12340: 
                   12341: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12342: needs $env{'form.datatoken'},
                   12343: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12344: 
                   12345: =cut
1.31      albertel 12346: 
                   12347: sub load_tmp_file {
                   12348:     my $r=shift;
                   12349:     my @studentdata=();
                   12350:     {
1.158     raeburn  12351:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12352:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12353:         if ( open(my $fh,"<$studentfile") ) {
                   12354:             @studentdata=<$fh>;
                   12355:             close($fh);
                   12356:         }
1.31      albertel 12357:     }
1.258     albertel 12358:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12359: }
                   12360: 
1.56      matthew  12361: =pod
                   12362: 
1.648     raeburn  12363: =item * &upfile_record_sep()
1.41      ng       12364: 
                   12365: Separate uploaded file into records
                   12366: returns array of records,
1.258     albertel 12367: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12368: 
                   12369: =cut
1.31      albertel 12370: 
                   12371: sub upfile_record_sep {
1.258     albertel 12372:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12373:     } else {
1.248     albertel 12374: 	my @records;
1.258     albertel 12375: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12376: 	    if ($line=~/^\s*$/) { next; }
                   12377: 	    push(@records,$line);
                   12378: 	}
                   12379: 	return @records;
1.31      albertel 12380:     }
                   12381: }
                   12382: 
1.56      matthew  12383: =pod
                   12384: 
1.648     raeburn  12385: =item * &record_sep($record)
1.41      ng       12386: 
1.258     albertel 12387: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12388: 
                   12389: =cut
                   12390: 
1.263     www      12391: sub takeleft {
                   12392:     my $index=shift;
                   12393:     return substr('0000'.$index,-4,4);
                   12394: }
                   12395: 
1.31      albertel 12396: sub record_sep {
                   12397:     my $record=shift;
                   12398:     my %components=();
1.258     albertel 12399:     if ($env{'form.upfiletype'} eq 'xml') {
                   12400:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12401:         my $i=0;
1.356     albertel 12402:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12403:             $field=~s/^(\"|\')//;
                   12404:             $field=~s/(\"|\')$//;
1.263     www      12405:             $components{&takeleft($i)}=$field;
1.31      albertel 12406:             $i++;
                   12407:         }
1.258     albertel 12408:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12409:         my $i=0;
1.356     albertel 12410:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12411:             $field=~s/^(\"|\')//;
                   12412:             $field=~s/(\"|\')$//;
1.263     www      12413:             $components{&takeleft($i)}=$field;
1.31      albertel 12414:             $i++;
                   12415:         }
                   12416:     } else {
1.561     www      12417:         my $separator=',';
1.480     banghart 12418:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12419:             $separator=';';
1.480     banghart 12420:         }
1.31      albertel 12421:         my $i=0;
1.561     www      12422: # the character we are looking for to indicate the end of a quote or a record 
                   12423:         my $looking_for=$separator;
                   12424: # do not add the characters to the fields
                   12425:         my $ignore=0;
                   12426: # we just encountered a separator (or the beginning of the record)
                   12427:         my $just_found_separator=1;
                   12428: # store the field we are working on here
                   12429:         my $field='';
                   12430: # work our way through all characters in record
                   12431:         foreach my $character ($record=~/(.)/g) {
                   12432:             if ($character eq $looking_for) {
                   12433:                if ($character ne $separator) {
                   12434: # Found the end of a quote, again looking for separator
                   12435:                   $looking_for=$separator;
                   12436:                   $ignore=1;
                   12437:                } else {
                   12438: # Found a separator, store away what we got
                   12439:                   $components{&takeleft($i)}=$field;
                   12440: 	          $i++;
                   12441:                   $just_found_separator=1;
                   12442:                   $ignore=0;
                   12443:                   $field='';
                   12444:                }
                   12445:                next;
                   12446:             }
                   12447: # single or double quotation marks after a separator indicate beginning of a quote
                   12448: # we are now looking for the end of the quote and need to ignore separators
                   12449:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12450:                $looking_for=$character;
                   12451:                next;
                   12452:             }
                   12453: # ignore would be true after we reached the end of a quote
                   12454:             if ($ignore) { next; }
                   12455:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12456:             $field.=$character;
                   12457:             $just_found_separator=0; 
1.31      albertel 12458:         }
1.561     www      12459: # catch the very last entry, since we never encountered the separator
                   12460:         $components{&takeleft($i)}=$field;
1.31      albertel 12461:     }
                   12462:     return %components;
                   12463: }
                   12464: 
1.144     matthew  12465: ######################################################
                   12466: ######################################################
                   12467: 
1.56      matthew  12468: =pod
                   12469: 
1.648     raeburn  12470: =item * &upfile_select_html()
1.41      ng       12471: 
1.144     matthew  12472: Return HTML code to select a file from the users machine and specify 
                   12473: the file type.
1.41      ng       12474: 
                   12475: =cut
                   12476: 
1.144     matthew  12477: ######################################################
                   12478: ######################################################
1.31      albertel 12479: sub upfile_select_html {
1.144     matthew  12480:     my %Types = (
                   12481:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12482:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12483:                  space => &mt('Space separated'),
                   12484:                  tab   => &mt('Tabulator separated'),
                   12485: #                 xml   => &mt('HTML/XML'),
                   12486:                  );
                   12487:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12488:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12489:     foreach my $type (sort(keys(%Types))) {
                   12490:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12491:     }
                   12492:     $Str .= "</select>\n";
                   12493:     return $Str;
1.31      albertel 12494: }
                   12495: 
1.301     albertel 12496: sub get_samples {
                   12497:     my ($records,$toget) = @_;
                   12498:     my @samples=({});
                   12499:     my $got=0;
                   12500:     foreach my $rec (@$records) {
                   12501: 	my %temp = &record_sep($rec);
                   12502: 	if (! grep(/\S/, values(%temp))) { next; }
                   12503: 	if (%temp) {
                   12504: 	    $samples[$got]=\%temp;
                   12505: 	    $got++;
                   12506: 	    if ($got == $toget) { last; }
                   12507: 	}
                   12508:     }
                   12509:     return \@samples;
                   12510: }
                   12511: 
1.144     matthew  12512: ######################################################
                   12513: ######################################################
                   12514: 
1.56      matthew  12515: =pod
                   12516: 
1.648     raeburn  12517: =item * &csv_print_samples($r,$records)
1.41      ng       12518: 
                   12519: Prints a table of sample values from each column uploaded $r is an
                   12520: Apache Request ref, $records is an arrayref from
                   12521: &Apache::loncommon::upfile_record_sep
                   12522: 
                   12523: =cut
                   12524: 
1.144     matthew  12525: ######################################################
                   12526: ######################################################
1.31      albertel 12527: sub csv_print_samples {
                   12528:     my ($r,$records) = @_;
1.662     bisitz   12529:     my $samples = &get_samples($records,5);
1.301     albertel 12530: 
1.594     raeburn  12531:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12532:               &start_data_table_header_row());
1.356     albertel 12533:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12534:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12535:     $r->print(&end_data_table_header_row());
1.301     albertel 12536:     foreach my $hash (@$samples) {
1.594     raeburn  12537: 	$r->print(&start_data_table_row());
1.356     albertel 12538: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12539: 	    $r->print('<td>');
1.356     albertel 12540: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12541: 	    $r->print('</td>');
                   12542: 	}
1.594     raeburn  12543: 	$r->print(&end_data_table_row());
1.31      albertel 12544:     }
1.594     raeburn  12545:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12546: }
                   12547: 
1.144     matthew  12548: ######################################################
                   12549: ######################################################
                   12550: 
1.56      matthew  12551: =pod
                   12552: 
1.648     raeburn  12553: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12554: 
                   12555: Prints a table to create associations between values and table columns.
1.144     matthew  12556: 
1.41      ng       12557: $r is an Apache Request ref,
                   12558: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12559: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12560: 
                   12561: =cut
                   12562: 
1.144     matthew  12563: ######################################################
                   12564: ######################################################
1.31      albertel 12565: sub csv_print_select_table {
                   12566:     my ($r,$records,$d) = @_;
1.301     albertel 12567:     my $i=0;
                   12568:     my $samples = &get_samples($records,1);
1.144     matthew  12569:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12570: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12571:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12572:               '<th>'.&mt('Column').'</th>'.
                   12573:               &end_data_table_header_row()."\n");
1.356     albertel 12574:     foreach my $array_ref (@$d) {
                   12575: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12576: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12577: 
1.875     bisitz   12578: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12579: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12580: 	$r->print('<option value="none"></option>');
1.356     albertel 12581: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12582: 	    $r->print('<option value="'.$sample.'"'.
                   12583:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12584:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12585: 	}
1.594     raeburn  12586: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12587: 	$i++;
                   12588:     }
1.594     raeburn  12589:     $r->print(&end_data_table());
1.31      albertel 12590:     $i--;
                   12591:     return $i;
                   12592: }
1.56      matthew  12593: 
1.144     matthew  12594: ######################################################
                   12595: ######################################################
                   12596: 
1.56      matthew  12597: =pod
1.31      albertel 12598: 
1.648     raeburn  12599: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12600: 
                   12601: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12602: 
                   12603: $r is an Apache Request ref,
                   12604: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12605: $d is an array of 2 element arrays (internal name, displayed name)
                   12606: 
                   12607: =cut
                   12608: 
1.144     matthew  12609: ######################################################
                   12610: ######################################################
1.31      albertel 12611: sub csv_samples_select_table {
                   12612:     my ($r,$records,$d) = @_;
                   12613:     my $i=0;
1.144     matthew  12614:     #
1.662     bisitz   12615:     my $max_samples = 5;
                   12616:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12617:     $r->print(&start_data_table().
                   12618:               &start_data_table_header_row().'<th>'.
                   12619:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12620:               &end_data_table_header_row());
1.301     albertel 12621: 
                   12622:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12623: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12624: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12625: 	foreach my $option (@$d) {
                   12626: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12627: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12628:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12629:                       $display.'</option>');
1.31      albertel 12630: 	}
                   12631: 	$r->print('</select></td><td>');
1.662     bisitz   12632: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12633: 	    if (defined($samples->[$line]{$key})) { 
                   12634: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12635: 	    }
                   12636: 	}
1.594     raeburn  12637: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12638: 	$i++;
                   12639:     }
1.594     raeburn  12640:     $r->print(&end_data_table());
1.31      albertel 12641:     $i--;
                   12642:     return($i);
1.115     matthew  12643: }
                   12644: 
1.144     matthew  12645: ######################################################
                   12646: ######################################################
                   12647: 
1.115     matthew  12648: =pod
                   12649: 
1.648     raeburn  12650: =item * &clean_excel_name($name)
1.115     matthew  12651: 
                   12652: Returns a replacement for $name which does not contain any illegal characters.
                   12653: 
                   12654: =cut
                   12655: 
1.144     matthew  12656: ######################################################
                   12657: ######################################################
1.115     matthew  12658: sub clean_excel_name {
                   12659:     my ($name) = @_;
                   12660:     $name =~ s/[:\*\?\/\\]//g;
                   12661:     if (length($name) > 31) {
                   12662:         $name = substr($name,0,31);
                   12663:     }
                   12664:     return $name;
1.25      albertel 12665: }
1.84      albertel 12666: 
1.85      albertel 12667: =pod
                   12668: 
1.648     raeburn  12669: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12670: 
                   12671: Returns either 1 or undef
                   12672: 
                   12673: 1 if the part is to be hidden, undef if it is to be shown
                   12674: 
                   12675: Arguments are:
                   12676: 
                   12677: $id the id of the part to be checked
                   12678: $symb, optional the symb of the resource to check
                   12679: $udom, optional the domain of the user to check for
                   12680: $uname, optional the username of the user to check for
                   12681: 
                   12682: =cut
1.84      albertel 12683: 
                   12684: sub check_if_partid_hidden {
                   12685:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12686:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12687: 					 $symb,$udom,$uname);
1.141     albertel 12688:     my $truth=1;
                   12689:     #if the string starts with !, then the list is the list to show not hide
                   12690:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12691:     my @hiddenlist=split(/,/,$hiddenparts);
                   12692:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12693: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12694:     }
1.141     albertel 12695:     return !$truth;
1.84      albertel 12696: }
1.127     matthew  12697: 
1.138     matthew  12698: 
                   12699: ############################################################
                   12700: ############################################################
                   12701: 
                   12702: =pod
                   12703: 
1.157     matthew  12704: =back 
                   12705: 
1.138     matthew  12706: =head1 cgi-bin script and graphing routines
                   12707: 
1.157     matthew  12708: =over 4
                   12709: 
1.648     raeburn  12710: =item * &get_cgi_id()
1.138     matthew  12711: 
                   12712: Inputs: none
                   12713: 
                   12714: Returns an id which can be used to pass environment variables
                   12715: to various cgi-bin scripts.  These environment variables will
                   12716: be removed from the users environment after a given time by
                   12717: the routine &Apache::lonnet::transfer_profile_to_env.
                   12718: 
                   12719: =cut
                   12720: 
                   12721: ############################################################
                   12722: ############################################################
1.152     albertel 12723: my $uniq=0;
1.136     matthew  12724: sub get_cgi_id {
1.154     albertel 12725:     $uniq=($uniq+1)%100000;
1.280     albertel 12726:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12727: }
                   12728: 
1.127     matthew  12729: ############################################################
                   12730: ############################################################
                   12731: 
                   12732: =pod
                   12733: 
1.648     raeburn  12734: =item * &DrawBarGraph()
1.127     matthew  12735: 
1.138     matthew  12736: Facilitates the plotting of data in a (stacked) bar graph.
                   12737: Puts plot definition data into the users environment in order for 
                   12738: graph.png to plot it.  Returns an <img> tag for the plot.
                   12739: The bars on the plot are labeled '1','2',...,'n'.
                   12740: 
                   12741: Inputs:
                   12742: 
                   12743: =over 4
                   12744: 
                   12745: =item $Title: string, the title of the plot
                   12746: 
                   12747: =item $xlabel: string, text describing the X-axis of the plot
                   12748: 
                   12749: =item $ylabel: string, text describing the Y-axis of the plot
                   12750: 
                   12751: =item $Max: scalar, the maximum Y value to use in the plot
                   12752: If $Max is < any data point, the graph will not be rendered.
                   12753: 
1.140     matthew  12754: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12755: they are plotted.  If undefined, default values will be used.
                   12756: 
1.178     matthew  12757: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12758: 
1.138     matthew  12759: =item @Values: An array of array references.  Each array reference holds data
                   12760: to be plotted in a stacked bar chart.
                   12761: 
1.239     matthew  12762: =item If the final element of @Values is a hash reference the key/value
                   12763: pairs will be added to the graph definition.
                   12764: 
1.138     matthew  12765: =back
                   12766: 
                   12767: Returns:
                   12768: 
                   12769: An <img> tag which references graph.png and the appropriate identifying
                   12770: information for the plot.
                   12771: 
1.127     matthew  12772: =cut
                   12773: 
                   12774: ############################################################
                   12775: ############################################################
1.134     matthew  12776: sub DrawBarGraph {
1.178     matthew  12777:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12778:     #
                   12779:     if (! defined($colors)) {
                   12780:         $colors = ['#33ff00', 
                   12781:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12782:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12783:                   ]; 
                   12784:     }
1.228     matthew  12785:     my $extra_settings = {};
                   12786:     if (ref($Values[-1]) eq 'HASH') {
                   12787:         $extra_settings = pop(@Values);
                   12788:     }
1.127     matthew  12789:     #
1.136     matthew  12790:     my $identifier = &get_cgi_id();
                   12791:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12792:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12793:         return '';
                   12794:     }
1.225     matthew  12795:     #
                   12796:     my @Labels;
                   12797:     if (defined($labels)) {
                   12798:         @Labels = @$labels;
                   12799:     } else {
                   12800:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12801:             push (@Labels,$i+1);
                   12802:         }
                   12803:     }
                   12804:     #
1.129     matthew  12805:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12806:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12807:     my %ValuesHash;
                   12808:     my $NumSets=1;
                   12809:     foreach my $array (@Values) {
                   12810:         next if (! ref($array));
1.136     matthew  12811:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12812:             join(',',@$array);
1.129     matthew  12813:     }
1.127     matthew  12814:     #
1.136     matthew  12815:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12816:     if ($NumBars < 3) {
                   12817:         $width = 120+$NumBars*32;
1.220     matthew  12818:         $xskip = 1;
1.225     matthew  12819:         $bar_width = 30;
                   12820:     } elsif ($NumBars < 5) {
                   12821:         $width = 120+$NumBars*20;
                   12822:         $xskip = 1;
                   12823:         $bar_width = 20;
1.220     matthew  12824:     } elsif ($NumBars < 10) {
1.136     matthew  12825:         $width = 120+$NumBars*15;
                   12826:         $xskip = 1;
                   12827:         $bar_width = 15;
                   12828:     } elsif ($NumBars <= 25) {
                   12829:         $width = 120+$NumBars*11;
                   12830:         $xskip = 5;
                   12831:         $bar_width = 8;
                   12832:     } elsif ($NumBars <= 50) {
                   12833:         $width = 120+$NumBars*8;
                   12834:         $xskip = 5;
                   12835:         $bar_width = 4;
                   12836:     } else {
                   12837:         $width = 120+$NumBars*8;
                   12838:         $xskip = 5;
                   12839:         $bar_width = 4;
                   12840:     }
                   12841:     #
1.137     matthew  12842:     $Max = 1 if ($Max < 1);
                   12843:     if ( int($Max) < $Max ) {
                   12844:         $Max++;
                   12845:         $Max = int($Max);
                   12846:     }
1.127     matthew  12847:     $Title  = '' if (! defined($Title));
                   12848:     $xlabel = '' if (! defined($xlabel));
                   12849:     $ylabel = '' if (! defined($ylabel));
1.369     www      12850:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12851:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12852:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12853:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12854:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12855:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12856:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12857:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12858:     $ValuesHash{$id.'.height'}   = $height;
                   12859:     $ValuesHash{$id.'.width'}    = $width;
                   12860:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12861:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12862:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12863:     #
1.228     matthew  12864:     # Deal with other parameters
                   12865:     while (my ($key,$value) = each(%$extra_settings)) {
                   12866:         $ValuesHash{$id.'.'.$key} = $value;
                   12867:     }
                   12868:     #
1.646     raeburn  12869:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12870:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12871: }
                   12872: 
                   12873: ############################################################
                   12874: ############################################################
                   12875: 
                   12876: =pod
                   12877: 
1.648     raeburn  12878: =item * &DrawXYGraph()
1.137     matthew  12879: 
1.138     matthew  12880: Facilitates the plotting of data in an XY graph.
                   12881: Puts plot definition data into the users environment in order for 
                   12882: graph.png to plot it.  Returns an <img> tag for the plot.
                   12883: 
                   12884: Inputs:
                   12885: 
                   12886: =over 4
                   12887: 
                   12888: =item $Title: string, the title of the plot
                   12889: 
                   12890: =item $xlabel: string, text describing the X-axis of the plot
                   12891: 
                   12892: =item $ylabel: string, text describing the Y-axis of the plot
                   12893: 
                   12894: =item $Max: scalar, the maximum Y value to use in the plot
                   12895: If $Max is < any data point, the graph will not be rendered.
                   12896: 
                   12897: =item $colors: Array ref containing the hex color codes for the data to be 
                   12898: plotted in.  If undefined, default values will be used.
                   12899: 
                   12900: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12901: 
                   12902: =item $Ydata: Array ref containing Array refs.  
1.185     www      12903: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12904: 
                   12905: =item %Values: hash indicating or overriding any default values which are 
                   12906: passed to graph.png.  
                   12907: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12908: 
                   12909: =back
                   12910: 
                   12911: Returns:
                   12912: 
                   12913: An <img> tag which references graph.png and the appropriate identifying
                   12914: information for the plot.
                   12915: 
1.137     matthew  12916: =cut
                   12917: 
                   12918: ############################################################
                   12919: ############################################################
                   12920: sub DrawXYGraph {
                   12921:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12922:     #
                   12923:     # Create the identifier for the graph
                   12924:     my $identifier = &get_cgi_id();
                   12925:     my $id = 'cgi.'.$identifier;
                   12926:     #
                   12927:     $Title  = '' if (! defined($Title));
                   12928:     $xlabel = '' if (! defined($xlabel));
                   12929:     $ylabel = '' if (! defined($ylabel));
                   12930:     my %ValuesHash = 
                   12931:         (
1.369     www      12932:          $id.'.title'  => &escape($Title),
                   12933:          $id.'.xlabel' => &escape($xlabel),
                   12934:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12935:          $id.'.y_max_value'=> $Max,
                   12936:          $id.'.labels'     => join(',',@$Xlabels),
                   12937:          $id.'.PlotType'   => 'XY',
                   12938:          );
                   12939:     #
                   12940:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12941:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12942:     }
                   12943:     #
                   12944:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12945:         return '';
                   12946:     }
                   12947:     my $NumSets=1;
1.138     matthew  12948:     foreach my $array (@{$Ydata}){
1.137     matthew  12949:         next if (! ref($array));
                   12950:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12951:     }
1.138     matthew  12952:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12953:     #
                   12954:     # Deal with other parameters
                   12955:     while (my ($key,$value) = each(%Values)) {
                   12956:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12957:     }
                   12958:     #
1.646     raeburn  12959:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12960:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12961: }
                   12962: 
                   12963: ############################################################
                   12964: ############################################################
                   12965: 
                   12966: =pod
                   12967: 
1.648     raeburn  12968: =item * &DrawXYYGraph()
1.138     matthew  12969: 
                   12970: Facilitates the plotting of data in an XY graph with two Y axes.
                   12971: Puts plot definition data into the users environment in order for 
                   12972: graph.png to plot it.  Returns an <img> tag for the plot.
                   12973: 
                   12974: Inputs:
                   12975: 
                   12976: =over 4
                   12977: 
                   12978: =item $Title: string, the title of the plot
                   12979: 
                   12980: =item $xlabel: string, text describing the X-axis of the plot
                   12981: 
                   12982: =item $ylabel: string, text describing the Y-axis of the plot
                   12983: 
                   12984: =item $colors: Array ref containing the hex color codes for the data to be 
                   12985: plotted in.  If undefined, default values will be used.
                   12986: 
                   12987: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12988: 
                   12989: =item $Ydata1: The first data set
                   12990: 
                   12991: =item $Min1: The minimum value of the left Y-axis
                   12992: 
                   12993: =item $Max1: The maximum value of the left Y-axis
                   12994: 
                   12995: =item $Ydata2: The second data set
                   12996: 
                   12997: =item $Min2: The minimum value of the right Y-axis
                   12998: 
                   12999: =item $Max2: The maximum value of the left Y-axis
                   13000: 
                   13001: =item %Values: hash indicating or overriding any default values which are 
                   13002: passed to graph.png.  
                   13003: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13004: 
                   13005: =back
                   13006: 
                   13007: Returns:
                   13008: 
                   13009: An <img> tag which references graph.png and the appropriate identifying
                   13010: information for the plot.
1.136     matthew  13011: 
                   13012: =cut
                   13013: 
                   13014: ############################################################
                   13015: ############################################################
1.137     matthew  13016: sub DrawXYYGraph {
                   13017:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13018:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13019:     #
                   13020:     # Create the identifier for the graph
                   13021:     my $identifier = &get_cgi_id();
                   13022:     my $id = 'cgi.'.$identifier;
                   13023:     #
                   13024:     $Title  = '' if (! defined($Title));
                   13025:     $xlabel = '' if (! defined($xlabel));
                   13026:     $ylabel = '' if (! defined($ylabel));
                   13027:     my %ValuesHash = 
                   13028:         (
1.369     www      13029:          $id.'.title'  => &escape($Title),
                   13030:          $id.'.xlabel' => &escape($xlabel),
                   13031:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13032:          $id.'.labels' => join(',',@$Xlabels),
                   13033:          $id.'.PlotType' => 'XY',
                   13034:          $id.'.NumSets' => 2,
1.137     matthew  13035:          $id.'.two_axes' => 1,
                   13036:          $id.'.y1_max_value' => $Max1,
                   13037:          $id.'.y1_min_value' => $Min1,
                   13038:          $id.'.y2_max_value' => $Max2,
                   13039:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13040:          );
                   13041:     #
1.137     matthew  13042:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13043:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13044:     }
                   13045:     #
                   13046:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13047:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13048:         return '';
                   13049:     }
                   13050:     my $NumSets=1;
1.137     matthew  13051:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13052:         next if (! ref($array));
                   13053:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13054:     }
                   13055:     #
                   13056:     # Deal with other parameters
                   13057:     while (my ($key,$value) = each(%Values)) {
                   13058:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13059:     }
                   13060:     #
1.646     raeburn  13061:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13062:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13063: }
                   13064: 
                   13065: ############################################################
                   13066: ############################################################
                   13067: 
                   13068: =pod
                   13069: 
1.157     matthew  13070: =back 
                   13071: 
1.139     matthew  13072: =head1 Statistics helper routines?  
                   13073: 
                   13074: Bad place for them but what the hell.
                   13075: 
1.157     matthew  13076: =over 4
                   13077: 
1.648     raeburn  13078: =item * &chartlink()
1.139     matthew  13079: 
                   13080: Returns a link to the chart for a specific student.  
                   13081: 
                   13082: Inputs:
                   13083: 
                   13084: =over 4
                   13085: 
                   13086: =item $linktext: The text of the link
                   13087: 
                   13088: =item $sname: The students username
                   13089: 
                   13090: =item $sdomain: The students domain
                   13091: 
                   13092: =back
                   13093: 
1.157     matthew  13094: =back
                   13095: 
1.139     matthew  13096: =cut
                   13097: 
                   13098: ############################################################
                   13099: ############################################################
                   13100: sub chartlink {
                   13101:     my ($linktext, $sname, $sdomain) = @_;
                   13102:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13103:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13104:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13105:        '">'.$linktext.'</a>';
1.153     matthew  13106: }
                   13107: 
                   13108: #######################################################
                   13109: #######################################################
                   13110: 
                   13111: =pod
                   13112: 
                   13113: =head1 Course Environment Routines
1.157     matthew  13114: 
                   13115: =over 4
1.153     matthew  13116: 
1.648     raeburn  13117: =item * &restore_course_settings()
1.153     matthew  13118: 
1.648     raeburn  13119: =item * &store_course_settings()
1.153     matthew  13120: 
                   13121: Restores/Store indicated form parameters from the course environment.
                   13122: Will not overwrite existing values of the form parameters.
                   13123: 
                   13124: Inputs: 
                   13125: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13126: 
                   13127: a hash ref describing the data to be stored.  For example:
                   13128:    
                   13129: %Save_Parameters = ('Status' => 'scalar',
                   13130:     'chartoutputmode' => 'scalar',
                   13131:     'chartoutputdata' => 'scalar',
                   13132:     'Section' => 'array',
1.373     raeburn  13133:     'Group' => 'array',
1.153     matthew  13134:     'StudentData' => 'array',
                   13135:     'Maps' => 'array');
                   13136: 
                   13137: Returns: both routines return nothing
                   13138: 
1.631     raeburn  13139: =back
                   13140: 
1.153     matthew  13141: =cut
                   13142: 
                   13143: #######################################################
                   13144: #######################################################
                   13145: sub store_course_settings {
1.496     albertel 13146:     return &store_settings($env{'request.course.id'},@_);
                   13147: }
                   13148: 
                   13149: sub store_settings {
1.153     matthew  13150:     # save to the environment
                   13151:     # appenv the same items, just to be safe
1.300     albertel 13152:     my $udom  = $env{'user.domain'};
                   13153:     my $uname = $env{'user.name'};
1.496     albertel 13154:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13155:     my %SaveHash;
                   13156:     my %AppHash;
                   13157:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13158:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13159:         my $envname = 'environment.'.$basename;
1.258     albertel 13160:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13161:             # Save this value away
                   13162:             if ($type eq 'scalar' &&
1.258     albertel 13163:                 (! exists($env{$envname}) || 
                   13164:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13165:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13166:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13167:             } elsif ($type eq 'array') {
                   13168:                 my $stored_form;
1.258     albertel 13169:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13170:                     $stored_form = join(',',
                   13171:                                         map {
1.369     www      13172:                                             &escape($_);
1.258     albertel 13173:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13174:                 } else {
                   13175:                     $stored_form = 
1.369     www      13176:                         &escape($env{'form.'.$setting});
1.153     matthew  13177:                 }
                   13178:                 # Determine if the array contents are the same.
1.258     albertel 13179:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13180:                     $SaveHash{$basename} = $stored_form;
                   13181:                     $AppHash{$envname}   = $stored_form;
                   13182:                 }
                   13183:             }
                   13184:         }
                   13185:     }
                   13186:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13187:                                           $udom,$uname);
1.153     matthew  13188:     if ($put_result !~ /^(ok|delayed)/) {
                   13189:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13190:                                  'got error:'.$put_result);
                   13191:     }
                   13192:     # Make sure these settings stick around in this session, too
1.646     raeburn  13193:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13194:     return;
                   13195: }
                   13196: 
                   13197: sub restore_course_settings {
1.499     albertel 13198:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13199: }
                   13200: 
                   13201: sub restore_settings {
                   13202:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13203:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13204:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13205:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13206:             '.'.$setting;
1.258     albertel 13207:         if (exists($env{$envname})) {
1.153     matthew  13208:             if ($type eq 'scalar') {
1.258     albertel 13209:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13210:             } elsif ($type eq 'array') {
1.258     albertel 13211:                 $env{'form.'.$setting} = [ 
1.153     matthew  13212:                                            map { 
1.369     www      13213:                                                &unescape($_); 
1.258     albertel 13214:                                            } split(',',$env{$envname})
1.153     matthew  13215:                                            ];
                   13216:             }
                   13217:         }
                   13218:     }
1.127     matthew  13219: }
                   13220: 
1.618     raeburn  13221: #######################################################
                   13222: #######################################################
                   13223: 
                   13224: =pod
                   13225: 
                   13226: =head1 Domain E-mail Routines  
                   13227: 
                   13228: =over 4
                   13229: 
1.648     raeburn  13230: =item * &build_recipient_list()
1.618     raeburn  13231: 
1.1075.2.44  raeburn  13232: Build recipient lists for following types of e-mail:
1.766     raeburn  13233: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13234: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13235: module change checking, student/employee ID conflict checks, as
                   13236: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13237: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13238: 
                   13239: Inputs:
1.1075.2.44  raeburn  13240: defmail (scalar - email address of default recipient),
                   13241: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13242: requestsmail, updatesmail, or idconflictsmail).
                   13243: 
1.619     raeburn  13244: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13245: 
                   13246: origmail (scalar - email address of recipient from loncapa.conf,
                   13247: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13248: 
1.655     raeburn  13249: Returns: comma separated list of addresses to which to send e-mail.
                   13250: 
                   13251: =back
1.618     raeburn  13252: 
                   13253: =cut
                   13254: 
                   13255: ############################################################
                   13256: ############################################################
                   13257: sub build_recipient_list {
1.619     raeburn  13258:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13259:     my @recipients;
                   13260:     my $otheremails;
                   13261:     my %domconfig =
                   13262:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13263:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13264:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13265:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13266:                 my @contacts = ('adminemail','supportemail');
                   13267:                 foreach my $item (@contacts) {
                   13268:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13269:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13270:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13271:                             push(@recipients,$addr);
                   13272:                         }
1.619     raeburn  13273:                     }
1.766     raeburn  13274:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13275:                 }
                   13276:             }
1.766     raeburn  13277:         } elsif ($origmail ne '') {
                   13278:             push(@recipients,$origmail);
1.618     raeburn  13279:         }
1.619     raeburn  13280:     } elsif ($origmail ne '') {
                   13281:         push(@recipients,$origmail);
1.618     raeburn  13282:     }
1.688     raeburn  13283:     if (defined($defmail)) {
                   13284:         if ($defmail ne '') {
                   13285:             push(@recipients,$defmail);
                   13286:         }
1.618     raeburn  13287:     }
                   13288:     if ($otheremails) {
1.619     raeburn  13289:         my @others;
                   13290:         if ($otheremails =~ /,/) {
                   13291:             @others = split(/,/,$otheremails);
1.618     raeburn  13292:         } else {
1.619     raeburn  13293:             push(@others,$otheremails);
                   13294:         }
                   13295:         foreach my $addr (@others) {
                   13296:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13297:                 push(@recipients,$addr);
                   13298:             }
1.618     raeburn  13299:         }
                   13300:     }
1.619     raeburn  13301:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13302:     return $recipientlist;
                   13303: }
                   13304: 
1.127     matthew  13305: ############################################################
                   13306: ############################################################
1.154     albertel 13307: 
1.655     raeburn  13308: =pod
                   13309: 
                   13310: =head1 Course Catalog Routines
                   13311: 
                   13312: =over 4
                   13313: 
                   13314: =item * &gather_categories()
                   13315: 
                   13316: Converts category definitions - keys of categories hash stored in  
                   13317: coursecategories in configuration.db on the primary library server in a 
                   13318: domain - to an array.  Also generates javascript and idx hash used to 
                   13319: generate Domain Coordinator interface for editing Course Categories.
                   13320: 
                   13321: Inputs:
1.663     raeburn  13322: 
1.655     raeburn  13323: categories (reference to hash of category definitions).
1.663     raeburn  13324: 
1.655     raeburn  13325: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13326:       categories and subcategories).
1.663     raeburn  13327: 
1.655     raeburn  13328: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13329:       editing Course Categories).
1.663     raeburn  13330: 
1.655     raeburn  13331: jsarray (reference to array of categories used to create Javascript arrays for
                   13332:          Domain Coordinator interface for editing Course Categories).
                   13333: 
                   13334: Returns: nothing
                   13335: 
                   13336: Side effects: populates cats, idx and jsarray. 
                   13337: 
                   13338: =cut
                   13339: 
                   13340: sub gather_categories {
                   13341:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13342:     my %counters;
                   13343:     my $num = 0;
                   13344:     foreach my $item (keys(%{$categories})) {
                   13345:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13346:         if ($container eq '' && $depth == 0) {
                   13347:             $cats->[$depth][$categories->{$item}] = $cat;
                   13348:         } else {
                   13349:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13350:         }
                   13351:         my ($escitem,$tail) = split(/:/,$item,2);
                   13352:         if ($counters{$tail} eq '') {
                   13353:             $counters{$tail} = $num;
                   13354:             $num ++;
                   13355:         }
                   13356:         if (ref($idx) eq 'HASH') {
                   13357:             $idx->{$item} = $counters{$tail};
                   13358:         }
                   13359:         if (ref($jsarray) eq 'ARRAY') {
                   13360:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13361:         }
                   13362:     }
                   13363:     return;
                   13364: }
                   13365: 
                   13366: =pod
                   13367: 
                   13368: =item * &extract_categories()
                   13369: 
                   13370: Used to generate breadcrumb trails for course categories.
                   13371: 
                   13372: Inputs:
1.663     raeburn  13373: 
1.655     raeburn  13374: categories (reference to hash of category definitions).
1.663     raeburn  13375: 
1.655     raeburn  13376: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13377:       categories and subcategories).
1.663     raeburn  13378: 
1.655     raeburn  13379: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13380: 
1.655     raeburn  13381: allitems (reference to hash - key is category key 
                   13382:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13383: 
1.655     raeburn  13384: idx (reference to hash of counters used in Domain Coordinator interface for
                   13385:       editing Course Categories).
1.663     raeburn  13386: 
1.655     raeburn  13387: jsarray (reference to array of categories used to create Javascript arrays for
                   13388:          Domain Coordinator interface for editing Course Categories).
                   13389: 
1.665     raeburn  13390: subcats (reference to hash of arrays containing all subcategories within each 
                   13391:          category, -recursive)
                   13392: 
1.655     raeburn  13393: Returns: nothing
                   13394: 
                   13395: Side effects: populates trails and allitems hash references.
                   13396: 
                   13397: =cut
                   13398: 
                   13399: sub extract_categories {
1.665     raeburn  13400:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13401:     if (ref($categories) eq 'HASH') {
                   13402:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13403:         if (ref($cats->[0]) eq 'ARRAY') {
                   13404:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13405:                 my $name = $cats->[0][$i];
                   13406:                 my $item = &escape($name).'::0';
                   13407:                 my $trailstr;
                   13408:                 if ($name eq 'instcode') {
                   13409:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13410:                 } elsif ($name eq 'communities') {
                   13411:                     $trailstr = &mt('Communities');
1.655     raeburn  13412:                 } else {
                   13413:                     $trailstr = $name;
                   13414:                 }
                   13415:                 if ($allitems->{$item} eq '') {
                   13416:                     push(@{$trails},$trailstr);
                   13417:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13418:                 }
                   13419:                 my @parents = ($name);
                   13420:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13421:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13422:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13423:                         if (ref($subcats) eq 'HASH') {
                   13424:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13425:                         }
                   13426:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13427:                     }
                   13428:                 } else {
                   13429:                     if (ref($subcats) eq 'HASH') {
                   13430:                         $subcats->{$item} = [];
1.655     raeburn  13431:                     }
                   13432:                 }
                   13433:             }
                   13434:         }
                   13435:     }
                   13436:     return;
                   13437: }
                   13438: 
                   13439: =pod
                   13440: 
1.1075.2.56  raeburn  13441: =item * &recurse_categories()
1.655     raeburn  13442: 
                   13443: Recursively used to generate breadcrumb trails for course categories.
                   13444: 
                   13445: Inputs:
1.663     raeburn  13446: 
1.655     raeburn  13447: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13448:       categories and subcategories).
1.663     raeburn  13449: 
1.655     raeburn  13450: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13451: 
                   13452: category (current course category, for which breadcrumb trail is being generated).
                   13453: 
                   13454: trails (reference to array of breadcrumb trails for each category).
                   13455: 
1.655     raeburn  13456: allitems (reference to hash - key is category key
                   13457:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13458: 
1.655     raeburn  13459: parents (array containing containers directories for current category, 
                   13460:          back to top level). 
                   13461: 
                   13462: Returns: nothing
                   13463: 
                   13464: Side effects: populates trails and allitems hash references
                   13465: 
                   13466: =cut
                   13467: 
                   13468: sub recurse_categories {
1.665     raeburn  13469:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13470:     my $shallower = $depth - 1;
                   13471:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13472:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13473:             my $name = $cats->[$depth]{$category}[$k];
                   13474:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13475:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13476:             if ($allitems->{$item} eq '') {
                   13477:                 push(@{$trails},$trailstr);
                   13478:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13479:             }
                   13480:             my $deeper = $depth+1;
                   13481:             push(@{$parents},$category);
1.665     raeburn  13482:             if (ref($subcats) eq 'HASH') {
                   13483:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13484:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13485:                     my $higher;
                   13486:                     if ($j > 0) {
                   13487:                         $higher = &escape($parents->[$j]).':'.
                   13488:                                   &escape($parents->[$j-1]).':'.$j;
                   13489:                     } else {
                   13490:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13491:                     }
                   13492:                     push(@{$subcats->{$higher}},$subcat);
                   13493:                 }
                   13494:             }
                   13495:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13496:                                 $subcats);
1.655     raeburn  13497:             pop(@{$parents});
                   13498:         }
                   13499:     } else {
                   13500:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13501:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13502:         if ($allitems->{$item} eq '') {
                   13503:             push(@{$trails},$trailstr);
                   13504:             $allitems->{$item} = scalar(@{$trails})-1;
                   13505:         }
                   13506:     }
                   13507:     return;
                   13508: }
                   13509: 
1.663     raeburn  13510: =pod
                   13511: 
1.1075.2.56  raeburn  13512: =item * &assign_categories_table()
1.663     raeburn  13513: 
                   13514: Create a datatable for display of hierarchical categories in a domain,
                   13515: with checkboxes to allow a course to be categorized. 
                   13516: 
                   13517: Inputs:
                   13518: 
                   13519: cathash - reference to hash of categories defined for the domain (from
                   13520:           configuration.db)
                   13521: 
                   13522: currcat - scalar with an & separated list of categories assigned to a course. 
                   13523: 
1.919     raeburn  13524: type    - scalar contains course type (Course or Community).
                   13525: 
1.663     raeburn  13526: Returns: $output (markup to be displayed) 
                   13527: 
                   13528: =cut
                   13529: 
                   13530: sub assign_categories_table {
1.919     raeburn  13531:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13532:     my $output;
                   13533:     if (ref($cathash) eq 'HASH') {
                   13534:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13535:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13536:         $maxdepth = scalar(@cats);
                   13537:         if (@cats > 0) {
                   13538:             my $itemcount = 0;
                   13539:             if (ref($cats[0]) eq 'ARRAY') {
                   13540:                 my @currcategories;
                   13541:                 if ($currcat ne '') {
                   13542:                     @currcategories = split('&',$currcat);
                   13543:                 }
1.919     raeburn  13544:                 my $table;
1.663     raeburn  13545:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13546:                     my $parent = $cats[0][$i];
1.919     raeburn  13547:                     next if ($parent eq 'instcode');
                   13548:                     if ($type eq 'Community') {
                   13549:                         next unless ($parent eq 'communities');
                   13550:                     } else {
                   13551:                         next if ($parent eq 'communities');
                   13552:                     }
1.663     raeburn  13553:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13554:                     my $item = &escape($parent).'::0';
                   13555:                     my $checked = '';
                   13556:                     if (@currcategories > 0) {
                   13557:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13558:                             $checked = ' checked="checked"';
1.663     raeburn  13559:                         }
                   13560:                     }
1.919     raeburn  13561:                     my $parent_title = $parent;
                   13562:                     if ($parent eq 'communities') {
                   13563:                         $parent_title = &mt('Communities');
                   13564:                     }
                   13565:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13566:                               '<input type="checkbox" name="usecategory" value="'.
                   13567:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13568:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13569:                     my $depth = 1;
                   13570:                     push(@path,$parent);
1.919     raeburn  13571:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13572:                     pop(@path);
1.919     raeburn  13573:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13574:                     $itemcount ++;
                   13575:                 }
1.919     raeburn  13576:                 if ($itemcount) {
                   13577:                     $output = &Apache::loncommon::start_data_table().
                   13578:                               $table.
                   13579:                               &Apache::loncommon::end_data_table();
                   13580:                 }
1.663     raeburn  13581:             }
                   13582:         }
                   13583:     }
                   13584:     return $output;
                   13585: }
                   13586: 
                   13587: =pod
                   13588: 
1.1075.2.56  raeburn  13589: =item * &assign_category_rows()
1.663     raeburn  13590: 
                   13591: Create a datatable row for display of nested categories in a domain,
                   13592: with checkboxes to allow a course to be categorized,called recursively.
                   13593: 
                   13594: Inputs:
                   13595: 
                   13596: itemcount - track row number for alternating colors
                   13597: 
                   13598: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13599:       categories and subcategories.
                   13600: 
                   13601: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13602: 
                   13603: parent - parent of current category item
                   13604: 
                   13605: path - Array containing all categories back up through the hierarchy from the
                   13606:        current category to the top level.
                   13607: 
                   13608: currcategories - reference to array of current categories assigned to the course
                   13609: 
                   13610: Returns: $output (markup to be displayed).
                   13611: 
                   13612: =cut
                   13613: 
                   13614: sub assign_category_rows {
                   13615:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13616:     my ($text,$name,$item,$chgstr);
                   13617:     if (ref($cats) eq 'ARRAY') {
                   13618:         my $maxdepth = scalar(@{$cats});
                   13619:         if (ref($cats->[$depth]) eq 'HASH') {
                   13620:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13621:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13622:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  13623:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  13624:                 for (my $j=0; $j<$numchildren; $j++) {
                   13625:                     $name = $cats->[$depth]{$parent}[$j];
                   13626:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13627:                     my $deeper = $depth+1;
                   13628:                     my $checked = '';
                   13629:                     if (ref($currcategories) eq 'ARRAY') {
                   13630:                         if (@{$currcategories} > 0) {
                   13631:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13632:                                 $checked = ' checked="checked"';
1.663     raeburn  13633:                             }
                   13634:                         }
                   13635:                     }
1.664     raeburn  13636:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13637:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13638:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13639:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13640:                              '</td><td>';
1.663     raeburn  13641:                     if (ref($path) eq 'ARRAY') {
                   13642:                         push(@{$path},$name);
                   13643:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13644:                         pop(@{$path});
                   13645:                     }
                   13646:                     $text .= '</td></tr>';
                   13647:                 }
                   13648:                 $text .= '</table></td>';
                   13649:             }
                   13650:         }
                   13651:     }
                   13652:     return $text;
                   13653: }
                   13654: 
1.655     raeburn  13655: ############################################################
                   13656: ############################################################
                   13657: 
                   13658: 
1.443     albertel 13659: sub commit_customrole {
1.664     raeburn  13660:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13661:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13662:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13663:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13664:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13665:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13666:                  '</b><br />';
                   13667:     return $output;
                   13668: }
                   13669: 
                   13670: sub commit_standardrole {
1.1075.2.31  raeburn  13671:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  13672:     my ($output,$logmsg,$linefeed);
                   13673:     if ($context eq 'auto') {
                   13674:         $linefeed = "\n";
                   13675:     } else {
                   13676:         $linefeed = "<br />\n";
                   13677:     }  
1.443     albertel 13678:     if ($three eq 'st') {
1.541     raeburn  13679:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  13680:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  13681:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13682:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13683:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13684:         } else {
1.541     raeburn  13685:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13686:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13687:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13688:             if ($context eq 'auto') {
                   13689:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13690:             } else {
                   13691:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13692:                &mt('Add to classlist').': <b>ok</b>';
                   13693:             }
                   13694:             $output .= $linefeed;
1.443     albertel 13695:         }
                   13696:     } else {
                   13697:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13698:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13699:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13700:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13701:         if ($context eq 'auto') {
                   13702:             $output .= $result.$linefeed;
                   13703:         } else {
                   13704:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13705:         }
1.443     albertel 13706:     }
                   13707:     return $output;
                   13708: }
                   13709: 
                   13710: sub commit_studentrole {
1.1075.2.31  raeburn  13711:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   13712:         $credits) = @_;
1.626     raeburn  13713:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13714:     if ($context eq 'auto') {
                   13715:         $linefeed = "\n";
                   13716:     } else {
                   13717:         $linefeed = '<br />'."\n";
                   13718:     }
1.443     albertel 13719:     if (defined($one) && defined($two)) {
                   13720:         my $cid=$one.'_'.$two;
                   13721:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13722:         my $secchange = 0;
                   13723:         my $expire_role_result;
                   13724:         my $modify_section_result;
1.628     raeburn  13725:         if ($oldsec ne '-1') { 
                   13726:             if ($oldsec ne $sec) {
1.443     albertel 13727:                 $secchange = 1;
1.628     raeburn  13728:                 my $now = time;
1.443     albertel 13729:                 my $uurl='/'.$cid;
                   13730:                 $uurl=~s/\_/\//g;
                   13731:                 if ($oldsec) {
                   13732:                     $uurl.='/'.$oldsec;
                   13733:                 }
1.626     raeburn  13734:                 $oldsecurl = $uurl;
1.628     raeburn  13735:                 $expire_role_result = 
1.652     raeburn  13736:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13737:                 if ($env{'request.course.sec'} ne '') { 
                   13738:                     if ($expire_role_result eq 'refused') {
                   13739:                         my @roles = ('st');
                   13740:                         my @statuses = ('previous');
                   13741:                         my @roledoms = ($one);
                   13742:                         my $withsec = 1;
                   13743:                         my %roleshash = 
                   13744:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13745:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13746:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13747:                             my ($oldstart,$oldend) = 
                   13748:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13749:                             if ($oldend > 0 && $oldend <= $now) {
                   13750:                                 $expire_role_result = 'ok';
                   13751:                             }
                   13752:                         }
                   13753:                     }
                   13754:                 }
1.443     albertel 13755:                 $result = $expire_role_result;
                   13756:             }
                   13757:         }
                   13758:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  13759:             $modify_section_result = 
                   13760:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   13761:                                                            undef,undef,undef,$sec,
                   13762:                                                            $end,$start,'','',$cid,
                   13763:                                                            '',$context,$credits);
1.443     albertel 13764:             if ($modify_section_result =~ /^ok/) {
                   13765:                 if ($secchange == 1) {
1.628     raeburn  13766:                     if ($sec eq '') {
                   13767:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13768:                     } else {
                   13769:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13770:                     }
1.443     albertel 13771:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13772:                     if ($sec eq '') {
                   13773:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13774:                     } else {
                   13775:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13776:                     }
1.443     albertel 13777:                 } else {
1.628     raeburn  13778:                     if ($sec eq '') {
                   13779:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13780:                     } else {
                   13781:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13782:                     }
1.443     albertel 13783:                 }
                   13784:             } else {
1.628     raeburn  13785:                 if ($secchange) {       
                   13786:                     $$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;
                   13787:                 } else {
                   13788:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13789:                 }
1.443     albertel 13790:             }
                   13791:             $result = $modify_section_result;
                   13792:         } elsif ($secchange == 1) {
1.628     raeburn  13793:             if ($oldsec eq '') {
1.1075.2.20  raeburn  13794:                 $$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  13795:             } else {
                   13796:                 $$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;
                   13797:             }
1.626     raeburn  13798:             if ($expire_role_result eq 'refused') {
                   13799:                 my $newsecurl = '/'.$cid;
                   13800:                 $newsecurl =~ s/\_/\//g;
                   13801:                 if ($sec ne '') {
                   13802:                     $newsecurl.='/'.$sec;
                   13803:                 }
                   13804:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13805:                     if ($sec eq '') {
                   13806:                         $$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;
                   13807:                     } else {
                   13808:                         $$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;
                   13809:                     }
                   13810:                 }
                   13811:             }
1.443     albertel 13812:         }
                   13813:     } else {
1.626     raeburn  13814:         $$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 13815:         $result = "error: incomplete course id\n";
                   13816:     }
                   13817:     return $result;
                   13818: }
                   13819: 
1.1075.2.25  raeburn  13820: sub show_role_extent {
                   13821:     my ($scope,$context,$role) = @_;
                   13822:     $scope =~ s{^/}{};
                   13823:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   13824:     push(@courseroles,'co');
                   13825:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   13826:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   13827:         $scope =~ s{/}{_};
                   13828:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   13829:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   13830:         my ($audom,$auname) = split(/\//,$scope);
                   13831:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   13832:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   13833:     } else {
                   13834:         $scope =~ s{/$}{};
                   13835:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   13836:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   13837:     }
                   13838: }
                   13839: 
1.443     albertel 13840: ############################################################
                   13841: ############################################################
                   13842: 
1.566     albertel 13843: sub check_clone {
1.578     raeburn  13844:     my ($args,$linefeed) = @_;
1.566     albertel 13845:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13846:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13847:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13848:     my $clonemsg;
                   13849:     my $can_clone = 0;
1.944     raeburn  13850:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13851:     if ($lctype ne 'community') {
                   13852:         $lctype = 'course';
                   13853:     }
1.566     albertel 13854:     if ($clonehome eq 'no_host') {
1.944     raeburn  13855:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13856:             $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'});
                   13857:         } else {
                   13858:             $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'});
                   13859:         }     
1.566     albertel 13860:     } else {
                   13861: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13862:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13863:             if ($clonedesc{'type'} ne 'Community') {
                   13864:                  $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'});
                   13865:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13866:             }
                   13867:         }
1.882     raeburn  13868: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13869:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13870: 	    $can_clone = 1;
                   13871: 	} else {
                   13872: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13873: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13874: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13875:             if (grep(/^\*$/,@cloners)) {
                   13876:                 $can_clone = 1;
                   13877:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13878:                 $can_clone = 1;
                   13879:             } else {
1.908     raeburn  13880:                 my $ccrole = 'cc';
1.944     raeburn  13881:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13882:                     $ccrole = 'co';
                   13883:                 }
1.578     raeburn  13884: 	        my %roleshash =
                   13885: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13886: 					 $args->{'ccdomain'},
1.908     raeburn  13887:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13888: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13889: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13890:                     $can_clone = 1;
                   13891:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13892:                     $can_clone = 1;
                   13893:                 } else {
1.944     raeburn  13894:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13895:                         $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'});
                   13896:                     } else {
                   13897:                         $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'});
                   13898:                     }
1.578     raeburn  13899: 	        }
1.566     albertel 13900: 	    }
1.578     raeburn  13901:         }
1.566     albertel 13902:     }
                   13903:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13904: }
                   13905: 
1.444     albertel 13906: sub construct_course {
1.1075.2.59  raeburn  13907:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 13908:     my $outcome;
1.541     raeburn  13909:     my $linefeed =  '<br />'."\n";
                   13910:     if ($context eq 'auto') {
                   13911:         $linefeed = "\n";
                   13912:     }
1.566     albertel 13913: 
                   13914: #
                   13915: # Are we cloning?
                   13916: #
                   13917:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13918:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13919: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13920: 	if ($context ne 'auto') {
1.578     raeburn  13921:             if ($clonemsg ne '') {
                   13922: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13923:             }
1.566     albertel 13924: 	}
                   13925: 	$outcome .= $clonemsg.$linefeed;
                   13926: 
                   13927:         if (!$can_clone) {
                   13928: 	    return (0,$outcome);
                   13929: 	}
                   13930:     }
                   13931: 
1.444     albertel 13932: #
                   13933: # Open course
                   13934: #
                   13935:     my $crstype = lc($args->{'crstype'});
                   13936:     my %cenv=();
                   13937:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13938:                                              $args->{'cdescr'},
                   13939:                                              $args->{'curl'},
                   13940:                                              $args->{'course_home'},
                   13941:                                              $args->{'nonstandard'},
                   13942:                                              $args->{'crscode'},
                   13943:                                              $args->{'ccuname'}.':'.
                   13944:                                              $args->{'ccdomain'},
1.882     raeburn  13945:                                              $args->{'crstype'},
1.885     raeburn  13946:                                              $cnum,$context,$category);
1.444     albertel 13947: 
                   13948:     # Note: The testing routines depend on this being output; see 
                   13949:     # Utils::Course. This needs to at least be output as a comment
                   13950:     # if anyone ever decides to not show this, and Utils::Course::new
                   13951:     # will need to be suitably modified.
1.541     raeburn  13952:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13953:     if ($$courseid =~ /^error:/) {
                   13954:         return (0,$outcome);
                   13955:     }
                   13956: 
1.444     albertel 13957: #
                   13958: # Check if created correctly
                   13959: #
1.479     albertel 13960:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13961:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13962:     if ($crsuhome eq 'no_host') {
                   13963:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13964:         return (0,$outcome);
                   13965:     }
1.541     raeburn  13966:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13967: 
1.444     albertel 13968: #
1.566     albertel 13969: # Do the cloning
                   13970: #   
                   13971:     if ($can_clone && $cloneid) {
                   13972: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13973: 	if ($context ne 'auto') {
                   13974: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13975: 	}
                   13976: 	$outcome .= $clonemsg.$linefeed;
                   13977: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13978: # Copy all files
1.637     www      13979: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13980: # Restore URL
1.566     albertel 13981: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13982: # Restore title
1.566     albertel 13983: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13984: # Restore creation date, creator and creation context.
                   13985:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13986:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13987:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13988: # Mark as cloned
1.566     albertel 13989: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13990: # Need to clone grading mode
                   13991:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13992:         $cenv{'grading'}=$newenv{'grading'};
                   13993: # Do not clone these environment entries
                   13994:         &Apache::lonnet::del('environment',
                   13995:                   ['default_enrollment_start_date',
                   13996:                    'default_enrollment_end_date',
                   13997:                    'question.email',
                   13998:                    'policy.email',
                   13999:                    'comment.email',
                   14000:                    'pch.users.denied',
1.725     raeburn  14001:                    'plc.users.denied',
                   14002:                    'hidefromcat',
1.1075.2.36  raeburn  14003:                    'checkforpriv',
1.1075.2.59  raeburn  14004:                    'categories',
                   14005:                    'internal.uniquecode'],
1.638     www      14006:                    $$crsudom,$$crsunum);
1.444     albertel 14007:     }
1.566     albertel 14008: 
1.444     albertel 14009: #
                   14010: # Set environment (will override cloned, if existing)
                   14011: #
                   14012:     my @sections = ();
                   14013:     my @xlists = ();
                   14014:     if ($args->{'crstype'}) {
                   14015:         $cenv{'type'}=$args->{'crstype'};
                   14016:     }
                   14017:     if ($args->{'crsid'}) {
                   14018:         $cenv{'courseid'}=$args->{'crsid'};
                   14019:     }
                   14020:     if ($args->{'crscode'}) {
                   14021:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14022:     }
                   14023:     if ($args->{'crsquota'} ne '') {
                   14024:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14025:     } else {
                   14026:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14027:     }
                   14028:     if ($args->{'ccuname'}) {
                   14029:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14030:                                         ':'.$args->{'ccdomain'};
                   14031:     } else {
                   14032:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14033:     }
1.1075.2.31  raeburn  14034:     if ($args->{'defaultcredits'}) {
                   14035:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14036:     }
1.444     albertel 14037:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14038:     if ($args->{'crssections'}) {
                   14039:         $cenv{'internal.sectionnums'} = '';
                   14040:         if ($args->{'crssections'} =~ m/,/) {
                   14041:             @sections = split/,/,$args->{'crssections'};
                   14042:         } else {
                   14043:             $sections[0] = $args->{'crssections'};
                   14044:         }
                   14045:         if (@sections > 0) {
                   14046:             foreach my $item (@sections) {
                   14047:                 my ($sec,$gp) = split/:/,$item;
                   14048:                 my $class = $args->{'crscode'}.$sec;
                   14049:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14050:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14051:                 unless ($addcheck eq 'ok') {
                   14052:                     push @badclasses, $class;
                   14053:                 }
                   14054:             }
                   14055:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14056:         }
                   14057:     }
                   14058: # do not hide course coordinator from staff listing, 
                   14059: # even if privileged
                   14060:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14061: # add course coordinator's domain to domains to check for privileged users
                   14062: # if different to course domain
                   14063:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14064:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14065:     }
1.444     albertel 14066: # add crosslistings
                   14067:     if ($args->{'crsxlist'}) {
                   14068:         $cenv{'internal.crosslistings'}='';
                   14069:         if ($args->{'crsxlist'} =~ m/,/) {
                   14070:             @xlists = split/,/,$args->{'crsxlist'};
                   14071:         } else {
                   14072:             $xlists[0] = $args->{'crsxlist'};
                   14073:         }
                   14074:         if (@xlists > 0) {
                   14075:             foreach my $item (@xlists) {
                   14076:                 my ($xl,$gp) = split/:/,$item;
                   14077:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14078:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14079:                 unless ($addcheck eq 'ok') {
                   14080:                     push @badclasses, $xl;
                   14081:                 }
                   14082:             }
                   14083:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14084:         }
                   14085:     }
                   14086:     if ($args->{'autoadds'}) {
                   14087:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14088:     }
                   14089:     if ($args->{'autodrops'}) {
                   14090:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14091:     }
                   14092: # check for notification of enrollment changes
                   14093:     my @notified = ();
                   14094:     if ($args->{'notify_owner'}) {
                   14095:         if ($args->{'ccuname'} ne '') {
                   14096:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14097:         }
                   14098:     }
                   14099:     if ($args->{'notify_dc'}) {
                   14100:         if ($uname ne '') { 
1.630     raeburn  14101:             push(@notified,$uname.':'.$udom);
1.444     albertel 14102:         }
                   14103:     }
                   14104:     if (@notified > 0) {
                   14105:         my $notifylist;
                   14106:         if (@notified > 1) {
                   14107:             $notifylist = join(',',@notified);
                   14108:         } else {
                   14109:             $notifylist = $notified[0];
                   14110:         }
                   14111:         $cenv{'internal.notifylist'} = $notifylist;
                   14112:     }
                   14113:     if (@badclasses > 0) {
                   14114:         my %lt=&Apache::lonlocal::texthash(
                   14115:                 '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',
                   14116:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14117:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14118:         );
1.541     raeburn  14119:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14120:                            ' ('.$lt{'adby'}.')';
                   14121:         if ($context eq 'auto') {
                   14122:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14123:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14124:             foreach my $item (@badclasses) {
                   14125:                 if ($context eq 'auto') {
                   14126:                     $outcome .= " - $item\n";
                   14127:                 } else {
                   14128:                     $outcome .= "<li>$item</li>\n";
                   14129:                 }
                   14130:             }
                   14131:             if ($context eq 'auto') {
                   14132:                 $outcome .= $linefeed;
                   14133:             } else {
1.566     albertel 14134:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14135:             }
                   14136:         } 
1.444     albertel 14137:     }
                   14138:     if ($args->{'no_end_date'}) {
                   14139:         $args->{'endaccess'} = 0;
                   14140:     }
                   14141:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14142:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14143:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14144:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14145:     if ($args->{'showphotos'}) {
                   14146:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14147:     }
                   14148:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14149:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14150:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14151:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14152:             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'); 
                   14153:             if ($context eq 'auto') {
                   14154:                 $outcome .= $krb_msg;
                   14155:             } else {
1.566     albertel 14156:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14157:             }
                   14158:             $outcome .= $linefeed;
1.444     albertel 14159:         }
                   14160:     }
                   14161:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14162:        if ($args->{'setpolicy'}) {
                   14163:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14164:        }
                   14165:        if ($args->{'setcontent'}) {
                   14166:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14167:        }
                   14168:     }
                   14169:     if ($args->{'reshome'}) {
                   14170: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14171: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14172:     }
                   14173: #
                   14174: # course has keyed access
                   14175: #
                   14176:     if ($args->{'setkeys'}) {
                   14177:        $cenv{'keyaccess'}='yes';
                   14178:     }
                   14179: # if specified, key authority is not course, but user
                   14180: # only active if keyaccess is yes
                   14181:     if ($args->{'keyauth'}) {
1.487     albertel 14182: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14183: 	$user = &LONCAPA::clean_username($user);
                   14184: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14185: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14186: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14187: 	}
                   14188:     }
                   14189: 
1.1075.2.59  raeburn  14190: #
                   14191: #  generate and store uniquecode (available to course requester), if course should have one.
                   14192: #
                   14193:     if ($args->{'uniquecode'}) {
                   14194:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14195:         if ($code) {
                   14196:             $cenv{'internal.uniquecode'} = $code;
                   14197:             my %crsinfo =
                   14198:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14199:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14200:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14201:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14202:             }
                   14203:             if (ref($coderef)) {
                   14204:                 $$coderef = $code;
                   14205:             }
                   14206:         }
                   14207:     }
                   14208: 
1.444     albertel 14209:     if ($args->{'disresdis'}) {
                   14210:         $cenv{'pch.roles.denied'}='st';
                   14211:     }
                   14212:     if ($args->{'disablechat'}) {
                   14213:         $cenv{'plc.roles.denied'}='st';
                   14214:     }
                   14215: 
                   14216:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14217:     # course
                   14218:     $cenv{'course.helper.not.run'} = 1;
                   14219:     #
                   14220:     # Use new Randomseed
                   14221:     #
                   14222:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14223:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14224:     #
                   14225:     # The encryption code and receipt prefix for this course
                   14226:     #
                   14227:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14228:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14229:     #
                   14230:     # By default, use standard grading
                   14231:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14232: 
1.541     raeburn  14233:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14234:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14235: #
                   14236: # Open all assignments
                   14237: #
                   14238:     if ($args->{'openall'}) {
                   14239:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14240:        my %storecontent = ($storeunder         => time,
                   14241:                            $storeunder.'.type' => 'date_start');
                   14242:        
                   14243:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14244:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14245:    }
                   14246: #
                   14247: # Set first page
                   14248: #
                   14249:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14250: 	    || ($cloneid)) {
1.445     albertel 14251: 	use LONCAPA::map;
1.444     albertel 14252: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14253: 
                   14254: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14255:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14256: 
1.444     albertel 14257:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14258:         my $title; my $url;
                   14259:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14260: 	    $title=&mt('Syllabus');
1.444     albertel 14261:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14262:         } else {
1.963     raeburn  14263:             $title=&mt('Table of Contents');
1.444     albertel 14264:             $url='/adm/navmaps';
                   14265:         }
1.445     albertel 14266: 
                   14267:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14268: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14269: 
                   14270: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14271:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14272:     }
1.566     albertel 14273: 
                   14274:     return (1,$outcome);
1.444     albertel 14275: }
                   14276: 
1.1075.2.59  raeburn  14277: sub make_unique_code {
                   14278:     my ($cdom,$cnum) = @_;
                   14279:     # get lock on uniquecodes db
                   14280:     my $lockhash = {
                   14281:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14282:                                                   ':'.$env{'user.domain'},
                   14283:                    };
                   14284:     my $tries = 0;
                   14285:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14286:     my ($code,$error);
                   14287: 
                   14288:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14289:         $tries ++;
                   14290:         sleep 1;
                   14291:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14292:     }
                   14293:     if ($gotlock eq 'ok') {
                   14294:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14295:         my $gotcode;
                   14296:         my $attempts = 0;
                   14297:         while ((!$gotcode) && ($attempts < 100)) {
                   14298:             $code = &generate_code();
                   14299:             if (!exists($currcodes{$code})) {
                   14300:                 $gotcode = 1;
                   14301:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14302:                     $error = 'nostore';
                   14303:                 }
                   14304:             }
                   14305:             $attempts ++;
                   14306:         }
                   14307:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14308:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14309:     } else {
                   14310:         $error = 'nolock';
                   14311:     }
                   14312:     return ($code,$error);
                   14313: }
                   14314: 
                   14315: sub generate_code {
                   14316:     my $code;
                   14317:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14318:     for (my $i=0; $i<6; $i++) {
                   14319:         my $lettnum = int (rand 2);
                   14320:         my $item = '';
                   14321:         if ($lettnum) {
                   14322:             $item = $letts[int( rand(18) )];
                   14323:         } else {
                   14324:             $item = 1+int( rand(8) );
                   14325:         }
                   14326:         $code .= $item;
                   14327:     }
                   14328:     return $code;
                   14329: }
                   14330: 
1.444     albertel 14331: ############################################################
                   14332: ############################################################
                   14333: 
1.953     droeschl 14334: #SD
                   14335: # only Community and Course, or anything else?
1.378     raeburn  14336: sub course_type {
                   14337:     my ($cid) = @_;
                   14338:     if (!defined($cid)) {
                   14339:         $cid = $env{'request.course.id'};
                   14340:     }
1.404     albertel 14341:     if (defined($env{'course.'.$cid.'.type'})) {
                   14342:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14343:     } else {
                   14344:         return 'Course';
1.377     raeburn  14345:     }
                   14346: }
1.156     albertel 14347: 
1.406     raeburn  14348: sub group_term {
                   14349:     my $crstype = &course_type();
                   14350:     my %names = (
                   14351:                   'Course' => 'group',
1.865     raeburn  14352:                   'Community' => 'group',
1.406     raeburn  14353:                 );
                   14354:     return $names{$crstype};
                   14355: }
                   14356: 
1.902     raeburn  14357: sub course_types {
1.1075.2.59  raeburn  14358:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14359:     my %typename = (
                   14360:                          official   => 'Official course',
                   14361:                          unofficial => 'Unofficial course',
                   14362:                          community  => 'Community',
1.1075.2.59  raeburn  14363:                          textbook   => 'Textbook course',
1.902     raeburn  14364:                    );
                   14365:     return (\@types,\%typename);
                   14366: }
                   14367: 
1.156     albertel 14368: sub icon {
                   14369:     my ($file)=@_;
1.505     albertel 14370:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14371:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14372:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14373:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14374: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14375: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14376: 	            $curfext.".gif") {
                   14377: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14378: 		$curfext.".gif";
                   14379: 	}
                   14380:     }
1.249     albertel 14381:     return &lonhttpdurl($iconname);
1.154     albertel 14382: } 
1.84      albertel 14383: 
1.575     albertel 14384: sub lonhttpdurl {
1.692     www      14385: #
                   14386: # Had been used for "small fry" static images on separate port 8080.
                   14387: # Modify here if lightweight http functionality desired again.
                   14388: # Currently eliminated due to increasing firewall issues.
                   14389: #
1.575     albertel 14390:     my ($url)=@_;
1.692     www      14391:     return $url;
1.215     albertel 14392: }
                   14393: 
1.213     albertel 14394: sub connection_aborted {
                   14395:     my ($r)=@_;
                   14396:     $r->print(" ");$r->rflush();
                   14397:     my $c = $r->connection;
                   14398:     return $c->aborted();
                   14399: }
                   14400: 
1.221     foxr     14401: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14402: #    strings as 'strings'.
                   14403: sub escape_single {
1.221     foxr     14404:     my ($input) = @_;
1.223     albertel 14405:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14406:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14407:     return $input;
                   14408: }
1.223     albertel 14409: 
1.222     foxr     14410: #  Same as escape_single, but escape's "'s  This 
                   14411: #  can be used for  "strings"
                   14412: sub escape_double {
                   14413:     my ($input) = @_;
                   14414:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14415:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14416:     return $input;
                   14417: }
1.223     albertel 14418:  
1.222     foxr     14419: #   Escapes the last element of a full URL.
                   14420: sub escape_url {
                   14421:     my ($url)   = @_;
1.238     raeburn  14422:     my @urlslices = split(/\//, $url,-1);
1.369     www      14423:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 14424:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     14425: }
1.462     albertel 14426: 
1.820     raeburn  14427: sub compare_arrays {
                   14428:     my ($arrayref1,$arrayref2) = @_;
                   14429:     my (@difference,%count);
                   14430:     @difference = ();
                   14431:     %count = ();
                   14432:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14433:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14434:         foreach my $element (keys(%count)) {
                   14435:             if ($count{$element} == 1) {
                   14436:                 push(@difference,$element);
                   14437:             }
                   14438:         }
                   14439:     }
                   14440:     return @difference;
                   14441: }
                   14442: 
1.817     bisitz   14443: # -------------------------------------------------------- Initialize user login
1.462     albertel 14444: sub init_user_environment {
1.463     albertel 14445:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14446:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14447: 
                   14448:     my $public=($username eq 'public' && $domain eq 'public');
                   14449: 
                   14450: # See if old ID present, if so, remove
                   14451: 
1.1062    raeburn  14452:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14453:     my $now=time;
                   14454: 
                   14455:     if ($public) {
                   14456: 	my $max_public=100;
                   14457: 	my $oldest;
                   14458: 	my $oldest_time=0;
                   14459: 	for(my $next=1;$next<=$max_public;$next++) {
                   14460: 	    if (-e $lonids."/publicuser_$next.id") {
                   14461: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14462: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14463: 		    $oldest_time=$mtime;
                   14464: 		    $oldest=$next;
                   14465: 		}
                   14466: 	    } else {
                   14467: 		$cookie="publicuser_$next";
                   14468: 		last;
                   14469: 	    }
                   14470: 	}
                   14471: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14472:     } else {
1.463     albertel 14473: 	# if this isn't a robot, kill any existing non-robot sessions
                   14474: 	if (!$args->{'robot'}) {
                   14475: 	    opendir(DIR,$lonids);
                   14476: 	    while ($filename=readdir(DIR)) {
                   14477: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14478: 		    unlink($lonids.'/'.$filename);
                   14479: 		}
1.462     albertel 14480: 	    }
1.463     albertel 14481: 	    closedir(DIR);
1.462     albertel 14482: 	}
                   14483: # Give them a new cookie
1.463     albertel 14484: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14485: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14486: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14487:     
                   14488: # Initialize roles
                   14489: 
1.1062    raeburn  14490: 	($userroles,$firstaccenv,$timerintenv) = 
                   14491:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14492:     }
                   14493: # ------------------------------------ Check browser type and MathML capability
                   14494: 
                   14495:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.42  raeburn  14496:         $clientunicode,$clientos,$clientmobile,$clientinfo) = &decode_user_agent($r);
1.462     albertel 14497: 
                   14498: # ------------------------------------------------------------- Get environment
                   14499: 
                   14500:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14501:     my ($tmp) = keys(%userenv);
                   14502:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14503:     } else {
                   14504: 	undef(%userenv);
                   14505:     }
                   14506:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14507: 	$form->{'interface'}=$userenv{'interface'};
                   14508:     }
                   14509:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14510: 
                   14511: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14512:     foreach my $option ('interface','localpath','localres') {
                   14513:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14514:     }
                   14515: # --------------------------------------------------------- Write first profile
                   14516: 
                   14517:     {
                   14518: 	my %initial_env = 
                   14519: 	    ("user.name"          => $username,
                   14520: 	     "user.domain"        => $domain,
                   14521: 	     "user.home"          => $authhost,
                   14522: 	     "browser.type"       => $clientbrowser,
                   14523: 	     "browser.version"    => $clientversion,
                   14524: 	     "browser.mathml"     => $clientmathml,
                   14525: 	     "browser.unicode"    => $clientunicode,
                   14526: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  14527:              "browser.mobile"     => $clientmobile,
                   14528:              "browser.info"       => $clientinfo,
1.462     albertel 14529: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14530: 	     "request.course.fn"  => '',
                   14531: 	     "request.course.uri" => '',
                   14532: 	     "request.course.sec" => '',
                   14533: 	     "request.role"       => 'cm',
                   14534: 	     "request.role.adv"   => $env{'user.adv'},
                   14535: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14536: 
                   14537:         if ($form->{'localpath'}) {
                   14538: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14539: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14540:         }
                   14541: 	
                   14542: 	if ($form->{'interface'}) {
                   14543: 	    $form->{'interface'}=~s/\W//gs;
                   14544: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14545: 	    $env{'browser.interface'}=$form->{'interface'};
                   14546: 	}
                   14547: 
1.1075.2.54  raeburn  14548:         if ($form->{'iptoken'}) {
                   14549:             my $lonhost = $r->dir_config('lonHostID');
                   14550:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14551:             $env{'user.noloadbalance'} = $lonhost;
                   14552:         }
                   14553: 
1.981     raeburn  14554:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14555:         my %domdef;
                   14556:         unless ($domain eq 'public') {
                   14557:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14558:         }
1.980     raeburn  14559: 
1.1075.2.7  raeburn  14560:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14561:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14562:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14563:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14564:         }
                   14565: 
1.1075.2.59  raeburn  14566:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14567:             $userenv{'canrequest.'.$crstype} =
                   14568:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14569:                                                   'reload','requestcourses',
                   14570:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14571:         }
                   14572: 
1.1075.2.14  raeburn  14573:         $userenv{'canrequest.author'} =
                   14574:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14575:                                         'reload','requestauthor',
                   14576:                                         \%userenv,\%domdef,\%is_adv);
                   14577:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14578:                                              $domain,$username);
                   14579:         my $reqstatus = $reqauthor{'author_status'};
                   14580:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   14581:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14582:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14583:                                                   $reqauthor{'author'}{'timestamp'};
                   14584:             }
                   14585:         }
                   14586: 
1.462     albertel 14587: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  14588: 
1.462     albertel 14589: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   14590: 		 &GDBM_WRCREAT(),0640)) {
                   14591: 	    &_add_to_env(\%disk_env,\%initial_env);
                   14592: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   14593: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  14594:             if (ref($firstaccenv) eq 'HASH') {
                   14595:                 &_add_to_env(\%disk_env,$firstaccenv);
                   14596:             }
                   14597:             if (ref($timerintenv) eq 'HASH') {
                   14598:                 &_add_to_env(\%disk_env,$timerintenv);
                   14599:             }
1.463     albertel 14600: 	    if (ref($args->{'extra_env'})) {
                   14601: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   14602: 	    }
1.462     albertel 14603: 	    untie(%disk_env);
                   14604: 	} else {
1.705     tempelho 14605: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   14606: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 14607: 	    return 'error: '.$!;
                   14608: 	}
                   14609:     }
                   14610:     $env{'request.role'}='cm';
                   14611:     $env{'request.role.adv'}=$env{'user.adv'};
                   14612:     $env{'browser.type'}=$clientbrowser;
                   14613: 
                   14614:     return $cookie;
                   14615: 
                   14616: }
                   14617: 
                   14618: sub _add_to_env {
                   14619:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  14620:     if (ref($env_data) eq 'HASH') {
                   14621:         while (my ($key,$value) = each(%$env_data)) {
                   14622: 	    $idf->{$prefix.$key} = $value;
                   14623: 	    $env{$prefix.$key}   = $value;
                   14624:         }
1.462     albertel 14625:     }
                   14626: }
                   14627: 
1.685     tempelho 14628: # --- Get the symbolic name of a problem and the url
                   14629: sub get_symb {
                   14630:     my ($request,$silent) = @_;
1.726     raeburn  14631:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 14632:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   14633:     if ($symb eq '') {
                   14634:         if (!$silent) {
1.1071    raeburn  14635:             if (ref($request)) { 
                   14636:                 $request->print("Unable to handle ambiguous references:$url:.");
                   14637:             }
1.685     tempelho 14638:             return ();
                   14639:         }
                   14640:     }
                   14641:     &Apache::lonenc::check_decrypt(\$symb);
                   14642:     return ($symb);
                   14643: }
                   14644: 
                   14645: # --------------------------------------------------------------Get annotation
                   14646: 
                   14647: sub get_annotation {
                   14648:     my ($symb,$enc) = @_;
                   14649: 
                   14650:     my $key = $symb;
                   14651:     if (!$enc) {
                   14652:         $key =
                   14653:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   14654:     }
                   14655:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   14656:     return $annotation{$key};
                   14657: }
                   14658: 
                   14659: sub clean_symb {
1.731     raeburn  14660:     my ($symb,$delete_enc) = @_;
1.685     tempelho 14661: 
                   14662:     &Apache::lonenc::check_decrypt(\$symb);
                   14663:     my $enc = $env{'request.enc'};
1.731     raeburn  14664:     if ($delete_enc) {
1.730     raeburn  14665:         delete($env{'request.enc'});
                   14666:     }
1.685     tempelho 14667: 
                   14668:     return ($symb,$enc);
                   14669: }
1.462     albertel 14670: 
1.990     raeburn  14671: sub build_release_hashes {
                   14672:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   14673:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   14674:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   14675:                   (ref($randomizetry) eq 'HASH'));
                   14676:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14677:         my ($item,$name,$value) = split(/:/,$key);
                   14678:         if ($item eq 'parameter') {
                   14679:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   14680:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   14681:                     push(@{$checkparms->{$name}},$value);
                   14682:                 }
                   14683:             } else {
                   14684:                 push(@{$checkparms->{$name}},$value);
                   14685:             }
                   14686:         } elsif ($item eq 'resourcetag') {
                   14687:             if ($name eq 'responsetype') {
                   14688:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   14689:             }
                   14690:         } elsif ($item eq 'course') {
                   14691:             if ($name eq 'crstype') {
                   14692:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   14693:             }
                   14694:         }
                   14695:     }
                   14696:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14697:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14698:     return;
                   14699: }
                   14700: 
1.1075.2.11  raeburn  14701: sub update_content_constraints {
                   14702:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14703:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14704:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14705:     my %checkresponsetypes;
                   14706:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14707:         my ($item,$name,$value) = split(/:/,$key);
                   14708:         if ($item eq 'resourcetag') {
                   14709:             if ($name eq 'responsetype') {
                   14710:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14711:             }
                   14712:         }
                   14713:     }
                   14714:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14715:     if (defined($navmap)) {
                   14716:         my %allresponses;
                   14717:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14718:             my %responses = $res->responseTypes();
                   14719:             foreach my $key (keys(%responses)) {
                   14720:                 next unless(exists($checkresponsetypes{$key}));
                   14721:                 $allresponses{$key} += $responses{$key};
                   14722:             }
                   14723:         }
                   14724:         foreach my $key (keys(%allresponses)) {
                   14725:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14726:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14727:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14728:             }
                   14729:         }
                   14730:         undef($navmap);
                   14731:     }
                   14732:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14733:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14734:     }
                   14735:     return;
                   14736: }
                   14737: 
1.1075.2.27  raeburn  14738: sub allmaps_incourse {
                   14739:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14740:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   14741:         $cid = $env{'request.course.id'};
                   14742:         $cdom = $env{'course.'.$cid.'.domain'};
                   14743:         $cnum = $env{'course.'.$cid.'.num'};
                   14744:         $chome = $env{'course.'.$cid.'.home'};
                   14745:     }
                   14746:     my %allmaps = ();
                   14747:     my $lastchange =
                   14748:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   14749:     if ($lastchange > $env{'request.course.tied'}) {
                   14750:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   14751:         unless ($ferr) {
                   14752:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   14753:         }
                   14754:     }
                   14755:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14756:     if (defined($navmap)) {
                   14757:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   14758:             $allmaps{$res->src()} = 1;
                   14759:         }
                   14760:     }
                   14761:     return \%allmaps;
                   14762: }
                   14763: 
1.1075.2.11  raeburn  14764: sub parse_supplemental_title {
                   14765:     my ($title) = @_;
                   14766: 
                   14767:     my ($foldertitle,$renametitle);
                   14768:     if ($title =~ /&amp;&amp;&amp;/) {
                   14769:         $title = &HTML::Entites::decode($title);
                   14770:     }
                   14771:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14772:         $renametitle=$4;
                   14773:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14774:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14775:         my $name =  &plainname($uname,$udom);
                   14776:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14777:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14778:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14779:             $name.': <br />'.$foldertitle;
                   14780:     }
                   14781:     if (wantarray) {
                   14782:         return ($title,$foldertitle,$renametitle);
                   14783:     }
                   14784:     return $title;
                   14785: }
                   14786: 
1.1075.2.43  raeburn  14787: sub recurse_supplemental {
                   14788:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   14789:     if ($suppmap) {
                   14790:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   14791:         if ($fatal) {
                   14792:             $errors ++;
                   14793:         } else {
                   14794:             if ($#LONCAPA::map::resources > 0) {
                   14795:                 foreach my $res (@LONCAPA::map::resources) {
                   14796:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   14797:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  14798:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   14799:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  14800:                         } else {
                   14801:                             $numfiles ++;
                   14802:                         }
                   14803:                     }
                   14804:                 }
                   14805:             }
                   14806:         }
                   14807:     }
                   14808:     return ($numfiles,$errors);
                   14809: }
                   14810: 
1.1075.2.18  raeburn  14811: sub symb_to_docspath {
                   14812:     my ($symb) = @_;
                   14813:     return unless ($symb);
                   14814:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   14815:     if ($resurl=~/\.(sequence|page)$/) {
                   14816:         $mapurl=$resurl;
                   14817:     } elsif ($resurl eq 'adm/navmaps') {
                   14818:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   14819:     }
                   14820:     my $mapresobj;
                   14821:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14822:     if (ref($navmap)) {
                   14823:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   14824:     }
                   14825:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   14826:     my $type=$2;
                   14827:     my $path;
                   14828:     if (ref($mapresobj)) {
                   14829:         my $pcslist = $mapresobj->map_hierarchy();
                   14830:         if ($pcslist ne '') {
                   14831:             foreach my $pc (split(/,/,$pcslist)) {
                   14832:                 next if ($pc <= 1);
                   14833:                 my $res = $navmap->getByMapPc($pc);
                   14834:                 if (ref($res)) {
                   14835:                     my $thisurl = $res->src();
                   14836:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   14837:                     my $thistitle = $res->title();
                   14838:                     $path .= '&'.
                   14839:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  14840:                              &escape($thistitle).
1.1075.2.18  raeburn  14841:                              ':'.$res->randompick().
                   14842:                              ':'.$res->randomout().
                   14843:                              ':'.$res->encrypted().
                   14844:                              ':'.$res->randomorder().
                   14845:                              ':'.$res->is_page();
                   14846:                 }
                   14847:             }
                   14848:         }
                   14849:         $path =~ s/^\&//;
                   14850:         my $maptitle = $mapresobj->title();
                   14851:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  14852:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  14853:         }
                   14854:         $path .= (($path ne '')? '&' : '').
                   14855:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  14856:                  &escape($maptitle).
1.1075.2.18  raeburn  14857:                  ':'.$mapresobj->randompick().
                   14858:                  ':'.$mapresobj->randomout().
                   14859:                  ':'.$mapresobj->encrypted().
                   14860:                  ':'.$mapresobj->randomorder().
                   14861:                  ':'.$mapresobj->is_page();
                   14862:     } else {
                   14863:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   14864:         my $ispage = (($type eq 'page')? 1 : '');
                   14865:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  14866:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  14867:         }
                   14868:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  14869:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  14870:     }
                   14871:     unless ($mapurl eq 'default') {
                   14872:         $path = 'default&'.
1.1075.2.46  raeburn  14873:                 &escape('Main Content').
1.1075.2.18  raeburn  14874:                 ':::::&'.$path;
                   14875:     }
                   14876:     return $path;
                   14877: }
                   14878: 
1.1075.2.14  raeburn  14879: sub captcha_display {
                   14880:     my ($context,$lonhost) = @_;
                   14881:     my ($output,$error);
                   14882:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   14883:     if ($captcha eq 'original') {
                   14884:         $output = &create_captcha();
                   14885:         unless ($output) {
                   14886:             $error = 'captcha';
                   14887:         }
                   14888:     } elsif ($captcha eq 'recaptcha') {
                   14889:         $output = &create_recaptcha($pubkey);
                   14890:         unless ($output) {
                   14891:             $error = 'recaptcha';
                   14892:         }
                   14893:     }
                   14894:     return ($output,$error);
                   14895: }
                   14896: 
                   14897: sub captcha_response {
                   14898:     my ($context,$lonhost) = @_;
                   14899:     my ($captcha_chk,$captcha_error);
                   14900:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   14901:     if ($captcha eq 'original') {
                   14902:         ($captcha_chk,$captcha_error) = &check_captcha();
                   14903:     } elsif ($captcha eq 'recaptcha') {
                   14904:         $captcha_chk = &check_recaptcha($privkey);
                   14905:     } else {
                   14906:         $captcha_chk = 1;
                   14907:     }
                   14908:     return ($captcha_chk,$captcha_error);
                   14909: }
                   14910: 
                   14911: sub get_captcha_config {
                   14912:     my ($context,$lonhost) = @_;
                   14913:     my ($captcha,$pubkey,$privkey,$hashtocheck);
                   14914:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   14915:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   14916:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   14917:     if ($context eq 'usercreation') {
                   14918:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   14919:         if (ref($domconfig{$context}) eq 'HASH') {
                   14920:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   14921:             if (ref($hashtocheck) eq 'HASH') {
                   14922:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   14923:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   14924:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   14925:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   14926:                     }
                   14927:                     if ($privkey && $pubkey) {
                   14928:                         $captcha = 'recaptcha';
                   14929:                     } else {
                   14930:                         $captcha = 'original';
                   14931:                     }
                   14932:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   14933:                     $captcha = 'original';
                   14934:                 }
                   14935:             }
                   14936:         } else {
                   14937:             $captcha = 'captcha';
                   14938:         }
                   14939:     } elsif ($context eq 'login') {
                   14940:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   14941:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   14942:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   14943:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   14944:             if ($privkey && $pubkey) {
                   14945:                 $captcha = 'recaptcha';
                   14946:             } else {
                   14947:                 $captcha = 'original';
                   14948:             }
                   14949:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   14950:             $captcha = 'original';
                   14951:         }
                   14952:     }
                   14953:     return ($captcha,$pubkey,$privkey);
                   14954: }
                   14955: 
                   14956: sub create_captcha {
                   14957:     my %captcha_params = &captcha_settings();
                   14958:     my ($output,$maxtries,$tries) = ('',10,0);
                   14959:     while ($tries < $maxtries) {
                   14960:         $tries ++;
                   14961:         my $captcha = Authen::Captcha->new (
                   14962:                                            output_folder => $captcha_params{'output_dir'},
                   14963:                                            data_folder   => $captcha_params{'db_dir'},
                   14964:                                           );
                   14965:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   14966: 
                   14967:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   14968:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   14969:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
                   14970:                      '<input type="text" size="5" name="code" value="" /><br />'.
                   14971:                      '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" />';
                   14972:             last;
                   14973:         }
                   14974:     }
                   14975:     return $output;
                   14976: }
                   14977: 
                   14978: sub captcha_settings {
                   14979:     my %captcha_params = (
                   14980:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   14981:                            www_output_dir => "/captchaspool",
                   14982:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   14983:                            numchars       => '5',
                   14984:                          );
                   14985:     return %captcha_params;
                   14986: }
                   14987: 
                   14988: sub check_captcha {
                   14989:     my ($captcha_chk,$captcha_error);
                   14990:     my $code = $env{'form.code'};
                   14991:     my $md5sum = $env{'form.crypt'};
                   14992:     my %captcha_params = &captcha_settings();
                   14993:     my $captcha = Authen::Captcha->new(
                   14994:                       output_folder => $captcha_params{'output_dir'},
                   14995:                       data_folder   => $captcha_params{'db_dir'},
                   14996:                   );
1.1075.2.26  raeburn  14997:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  14998:     my %captcha_hash = (
                   14999:                         0       => 'Code not checked (file error)',
                   15000:                        -1      => 'Failed: code expired',
                   15001:                        -2      => 'Failed: invalid code (not in database)',
                   15002:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   15003:     );
                   15004:     if ($captcha_chk != 1) {
                   15005:         $captcha_error = $captcha_hash{$captcha_chk}
                   15006:     }
                   15007:     return ($captcha_chk,$captcha_error);
                   15008: }
                   15009: 
                   15010: sub create_recaptcha {
                   15011:     my ($pubkey) = @_;
1.1075.2.51  raeburn  15012:     my $use_ssl;
                   15013:     if ($ENV{'SERVER_PORT'} == 443) {
                   15014:         $use_ssl = 1;
                   15015:     }
1.1075.2.14  raeburn  15016:     my $captcha = Captcha::reCAPTCHA->new;
                   15017:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1075.2.51  raeburn  15018:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1075.2.14  raeburn  15019:            &mt('If either word is hard to read, [_1] will replace them.',
1.1075.2.39  raeburn  15020:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1075.2.14  raeburn  15021:            '<br /><br />';
                   15022: }
                   15023: 
                   15024: sub check_recaptcha {
                   15025:     my ($privkey) = @_;
                   15026:     my $captcha_chk;
                   15027:     my $captcha = Captcha::reCAPTCHA->new;
                   15028:     my $captcha_result =
                   15029:         $captcha->check_answer(
                   15030:                                 $privkey,
                   15031:                                 $ENV{'REMOTE_ADDR'},
                   15032:                                 $env{'form.recaptcha_challenge_field'},
                   15033:                                 $env{'form.recaptcha_response_field'},
                   15034:                               );
                   15035:     if ($captcha_result->{is_valid}) {
                   15036:         $captcha_chk = 1;
                   15037:     }
                   15038:     return $captcha_chk;
                   15039: }
                   15040: 
1.1075.2.56  raeburn  15041: sub cleanup_html {
                   15042:     my ($incoming) = @_;
                   15043:     my $outgoing;
                   15044:     if ($incoming ne '') {
                   15045:         $outgoing = $incoming;
                   15046:         $outgoing =~ s/;/&#059;/g;
                   15047:         $outgoing =~ s/\#/&#035;/g;
                   15048:         $outgoing =~ s/\&/&#038;/g;
                   15049:         $outgoing =~ s/</&#060;/g;
                   15050:         $outgoing =~ s/>/&#062;/g;
                   15051:         $outgoing =~ s/\(/&#040/g;
                   15052:         $outgoing =~ s/\)/&#041;/g;
                   15053:         $outgoing =~ s/"/&#034;/g;
                   15054:         $outgoing =~ s/'/&#039;/g;
                   15055:         $outgoing =~ s/\$/&#036;/g;
                   15056:         $outgoing =~ s{/}{&#047;}g;
                   15057:         $outgoing =~ s/=/&#061;/g;
                   15058:         $outgoing =~ s/\\/&#092;/g
                   15059:     }
                   15060:     return $outgoing;
                   15061: }
                   15062: 
1.41      ng       15063: =pod
                   15064: 
                   15065: =back
                   15066: 
1.112     bowersj2 15067: =cut
1.41      ng       15068: 
1.112     bowersj2 15069: 1;
                   15070: __END__;
1.41      ng       15071: 

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