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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1093  ! raeburn     4: # $Id: loncommon.pm,v 1.1092 2012/08/14 15:45:06 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.479     albertel   70: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    71: use DateTime::TimeZone;
1.687     raeburn    72: use DateTime::Locale::Catalog;
1.1091    foxr       73: use Text::Aspell;
1.117     www        74: 
1.517     raeburn    75: # ---------------------------------------------- Designs
                     76: use vars qw(%defaultdesign);
                     77: 
1.22      www        78: my $readit;
                     79: 
1.517     raeburn    80: 
1.157     matthew    81: ##
                     82: ## Global Variables
                     83: ##
1.46      matthew    84: 
1.643     foxr       85: 
                     86: # ----------------------------------------------- SSI with retries:
                     87: #
                     88: 
                     89: =pod
                     90: 
1.648     raeburn    91: =head1 Server Side include with retries:
1.643     foxr       92: 
                     93: =over 4
                     94: 
1.648     raeburn    95: =item * &ssi_with_retries(resource,retries form)
1.643     foxr       96: 
                     97: Performs an ssi with some number of retries.  Retries continue either
                     98: until the result is ok or until the retry count supplied by the
                     99: caller is exhausted.  
                    100: 
                    101: Inputs:
1.648     raeburn   102: 
                    103: =over 4
                    104: 
1.643     foxr      105: resource   - Identifies the resource to insert.
1.648     raeburn   106: 
1.643     foxr      107: retries    - Count of the number of retries allowed.
1.648     raeburn   108: 
1.643     foxr      109: form       - Hash that identifies the rendering options.
                    110: 
1.648     raeburn   111: =back
                    112: 
                    113: Returns:
                    114: 
                    115: =over 4
                    116: 
1.643     foxr      117: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   118: 
1.643     foxr      119: response   - The response from the last attempt (which may or may not have been successful.
                    120: 
1.648     raeburn   121: =back
                    122: 
                    123: =back
                    124: 
1.643     foxr      125: =cut
                    126: 
                    127: sub ssi_with_retries {
                    128:     my ($resource, $retries, %form) = @_;
                    129: 
                    130: 
                    131:     my $ok = 0;			# True if we got a good response.
                    132:     my $content;
                    133:     my $response;
                    134: 
                    135:     # Try to get the ssi done. within the retries count:
                    136: 
                    137:     do {
                    138: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    139: 	$ok      = $response->is_success;
1.650     www       140:         if (!$ok) {
                    141:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    142:         }
1.643     foxr      143: 	$retries--;
                    144:     } while (!$ok && ($retries > 0));
                    145: 
                    146:     if (!$ok) {
                    147: 	$content = '';		# On error return an empty content.
                    148:     }
                    149:     return ($content, $response);
                    150: 
                    151: }
                    152: 
                    153: 
                    154: 
1.20      www       155: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  156: my %language;
1.124     www       157: my %supported_language;
1.1088    foxr      158: my %supported_codes;
1.1048    foxr      159: my %latex_language;		# For choosing hyphenation in <transl..>
                    160: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  161: my %cprtag;
1.192     taceyjo1  162: my %scprtag;
1.351     www       163: my %fe; my %fd; my %fm;
1.41      ng        164: my %category_extensions;
1.12      harris41  165: 
1.46      matthew   166: # ---------------------------------------------- Thesaurus variables
1.144     matthew   167: #
                    168: # %Keywords:
                    169: #      A hash used by &keyword to determine if a word is considered a keyword.
                    170: # $thesaurus_db_file 
                    171: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   172: 
                    173: my %Keywords;
                    174: my $thesaurus_db_file;
                    175: 
1.144     matthew   176: #
                    177: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    178: # thesaurus.tab, and filecategories.tab.
                    179: #
1.18      www       180: BEGIN {
1.46      matthew   181:     # Variable initialization
                    182:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    183:     #
1.22      www       184:     unless ($readit) {
1.12      harris41  185: # ------------------------------------------------------------------- languages
                    186:     {
1.158     raeburn   187:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    188:                                    '/language.tab';
                    189:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  190:             while (my $line = <$fh>) {
                    191:                 next if ($line=~/^\#/);
                    192:                 chomp($line);
1.1088    foxr      193:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   194:                 $language{$key}=$val.' - '.$enc;
                    195:                 if ($sup) {
                    196:                     $supported_language{$key}=$sup;
1.1088    foxr      197: 		    $supported_codes{$key}   = $code;
1.158     raeburn   198:                 }
1.1048    foxr      199: 		if ($latex) {
                    200: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      201: 		    $latex_language{$code} = $latex;
1.1048    foxr      202: 		}
1.158     raeburn   203:             }
                    204:             close($fh);
                    205:         }
1.12      harris41  206:     }
                    207: # ------------------------------------------------------------------ copyrights
                    208:     {
1.158     raeburn   209:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    210:                                   '/copyright.tab';
                    211:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  212:             while (my $line = <$fh>) {
                    213:                 next if ($line=~/^\#/);
                    214:                 chomp($line);
                    215:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   216:                 $cprtag{$key}=$val;
                    217:             }
                    218:             close($fh);
                    219:         }
1.12      harris41  220:     }
1.351     www       221: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  222:     {
                    223:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    224:                                   '/source_copyright.tab';
                    225:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  226:             while (my $line = <$fh>) {
                    227:                 next if ($line =~ /^\#/);
                    228:                 chomp($line);
                    229:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  230:                 $scprtag{$key}=$val;
                    231:             }
                    232:             close($fh);
                    233:         }
                    234:     }
1.63      www       235: 
1.517     raeburn   236: # -------------------------------------------------------------- default domain designs
1.63      www       237:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   238:     my $designfile = $designdir.'/default.tab';
                    239:     if ( open (my $fh,"<$designfile") ) {
                    240:         while (my $line = <$fh>) {
                    241:             next if ($line =~ /^\#/);
                    242:             chomp($line);
                    243:             my ($key,$val)=(split(/\=/,$line));
                    244:             if ($val) { $defaultdesign{$key}=$val; }
                    245:         }
                    246:         close($fh);
1.63      www       247:     }
                    248: 
1.15      harris41  249: # ------------------------------------------------------------- file categories
                    250:     {
1.158     raeburn   251:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    252:                                   '/filecategories.tab';
                    253:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  254: 	    while (my $line = <$fh>) {
                    255: 		next if ($line =~ /^\#/);
                    256: 		chomp($line);
                    257:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   258:                 push @{$category_extensions{lc($category)}},$extension;
                    259:             }
                    260:             close($fh);
                    261:         }
                    262: 
1.15      harris41  263:     }
1.12      harris41  264: # ------------------------------------------------------------------ file types
                    265:     {
1.158     raeburn   266:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    267:                '/filetypes.tab';
                    268:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  269:             while (my $line = <$fh>) {
                    270: 		next if ($line =~ /^\#/);
                    271: 		chomp($line);
                    272:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   273:                 if ($descr ne '') {
                    274:                     $fe{$ending}=lc($emb);
                    275:                     $fd{$ending}=$descr;
1.351     www       276:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   277:                 }
                    278:             }
                    279:             close($fh);
                    280:         }
1.12      harris41  281:     }
1.22      www       282:     &Apache::lonnet::logthis(
1.705     tempelho  283:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       284:     $readit=1;
1.46      matthew   285:     }  # end of unless($readit) 
1.32      matthew   286:     
                    287: }
1.112     bowersj2  288: 
1.42      matthew   289: ###############################################################
                    290: ##           HTML and Javascript Helper Functions            ##
                    291: ###############################################################
                    292: 
                    293: =pod 
                    294: 
1.112     bowersj2  295: =head1 HTML and Javascript Functions
1.42      matthew   296: 
1.112     bowersj2  297: =over 4
                    298: 
1.648     raeburn   299: =item * &browser_and_searcher_javascript()
1.112     bowersj2  300: 
                    301: X<browsing, javascript>X<searching, javascript>Returns a string
                    302: containing javascript with two functions, C<openbrowser> and
                    303: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    304: tags.
1.42      matthew   305: 
1.648     raeburn   306: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   307: 
                    308: inputs: formname, elementname, only, omit
                    309: 
                    310: formname and elementname indicate the name of the html form and name of
                    311: the element that the results of the browsing selection are to be placed in. 
                    312: 
                    313: Specifying 'only' will restrict the browser to displaying only files
1.185     www       314: with the given extension.  Can be a comma separated list.
1.42      matthew   315: 
                    316: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       317: with the given extension.  Can be a comma separated list.
1.42      matthew   318: 
1.648     raeburn   319: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   320: 
                    321: Inputs: formname, elementname
                    322: 
                    323: formname and elementname specify the name of the html form and the name
                    324: of the element the selection from the search results will be placed in.
1.542     raeburn   325: 
1.42      matthew   326: =cut
                    327: 
                    328: sub browser_and_searcher_javascript {
1.199     albertel  329:     my ($mode)=@_;
                    330:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  331:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   332:     return <<END;
1.219     albertel  333: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   334:     var editbrowser = null;
1.135     albertel  335:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       336:         var url = '$resurl/?';
1.42      matthew   337:         if (editbrowser == null) {
                    338:             url += 'launch=1&';
                    339:         }
                    340:         url += 'catalogmode=interactive&';
1.199     albertel  341:         url += 'mode=$mode&';
1.611     albertel  342:         url += 'inhibitmenu=yes&';
1.42      matthew   343:         url += 'form=' + formname + '&';
                    344:         if (only != null) {
                    345:             url += 'only=' + only + '&';
1.217     albertel  346:         } else {
                    347:             url += 'only=&';
                    348: 	}
1.42      matthew   349:         if (omit != null) {
                    350:             url += 'omit=' + omit + '&';
1.217     albertel  351:         } else {
                    352:             url += 'omit=&';
                    353: 	}
1.135     albertel  354:         if (titleelement != null) {
                    355:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  356:         } else {
                    357: 	    url += 'titleelement=&';
                    358: 	}
1.42      matthew   359:         url += 'element=' + elementname + '';
                    360:         var title = 'Browser';
1.435     albertel  361:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   362:         options += ',width=700,height=600';
                    363:         editbrowser = open(url,title,options,'1');
                    364:         editbrowser.focus();
                    365:     }
                    366:     var editsearcher;
1.135     albertel  367:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   368:         var url = '/adm/searchcat?';
                    369:         if (editsearcher == null) {
                    370:             url += 'launch=1&';
                    371:         }
                    372:         url += 'catalogmode=interactive&';
1.199     albertel  373:         url += 'mode=$mode&';
1.42      matthew   374:         url += 'form=' + formname + '&';
1.135     albertel  375:         if (titleelement != null) {
                    376:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  377:         } else {
                    378: 	    url += 'titleelement=&';
                    379: 	}
1.42      matthew   380:         url += 'element=' + elementname + '';
                    381:         var title = 'Search';
1.435     albertel  382:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   383:         options += ',width=700,height=600';
                    384:         editsearcher = open(url,title,options,'1');
                    385:         editsearcher.focus();
                    386:     }
1.219     albertel  387: // END LON-CAPA Internal -->
1.42      matthew   388: END
1.170     www       389: }
                    390: 
                    391: sub lastresurl {
1.258     albertel  392:     if ($env{'environment.lastresurl'}) {
                    393: 	return $env{'environment.lastresurl'}
1.170     www       394:     } else {
                    395: 	return '/res';
                    396:     }
                    397: }
                    398: 
                    399: sub storeresurl {
                    400:     my $resurl=&Apache::lonnet::clutter(shift);
                    401:     unless ($resurl=~/^\/res/) { return 0; }
                    402:     $resurl=~s/\/$//;
                    403:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   404:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       405:     return 1;
1.42      matthew   406: }
                    407: 
1.74      www       408: sub studentbrowser_javascript {
1.111     www       409:    unless (
1.258     albertel  410:             (($env{'request.course.id'}) && 
1.302     albertel  411:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    412: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    413: 					  '/'.$env{'request.course.sec'})
                    414: 	      ))
1.258     albertel  415:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       416:           ) { return ''; }  
1.74      www       417:    return (<<'ENDSTDBRW');
1.776     bisitz    418: <script type="text/javascript" language="Javascript">
1.824     bisitz    419: // <![CDATA[
1.74      www       420:     var stdeditbrowser;
1.999     www       421:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       422:         var url = '/adm/pickstudent?';
                    423:         var filter;
1.558     albertel  424: 	if (!ignorefilter) {
                    425: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    426: 	}
1.74      www       427:         if (filter != null) {
                    428:            if (filter != '') {
                    429:                url += 'filter='+filter+'&';
                    430: 	   }
                    431:         }
                    432:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       433:                                     '&udomelement='+udom+
                    434:                                     '&clicker='+clicker;
1.111     www       435: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   436:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       437:         var title = 'Student_Browser';
1.74      www       438:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    439:         options += ',width=700,height=600';
                    440:         stdeditbrowser = open(url,title,options,'1');
                    441:         stdeditbrowser.focus();
                    442:     }
1.824     bisitz    443: // ]]>
1.74      www       444: </script>
                    445: ENDSTDBRW
                    446: }
1.42      matthew   447: 
1.1003    www       448: sub resourcebrowser_javascript {
                    449:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       450:    return (<<'ENDRESBRW');
1.1003    www       451: <script type="text/javascript" language="Javascript">
                    452: // <![CDATA[
                    453:     var reseditbrowser;
1.1004    www       454:     function openresbrowser(formname,reslink) {
1.1005    www       455:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       456:         var title = 'Resource_Browser';
                    457:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       458:         options += ',width=700,height=500';
1.1004    www       459:         reseditbrowser = open(url,title,options,'1');
                    460:         reseditbrowser.focus();
1.1003    www       461:     }
                    462: // ]]>
                    463: </script>
1.1004    www       464: ENDRESBRW
1.1003    www       465: }
                    466: 
1.74      www       467: sub selectstudent_link {
1.999     www       468:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    469:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    470:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    471:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  472:    if ($env{'request.course.id'}) {  
1.302     albertel  473:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    474: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    475: 					'/'.$env{'request.course.sec'})) {
1.111     www       476: 	   return '';
                    477:        }
1.999     www       478:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   479:        if ($courseadvonly)  {
                    480:            $callargs .= ",'',1,1";
                    481:        }
                    482:        return '<span class="LC_nobreak">'.
                    483:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    484:               &mt('Select User').'</a></span>';
1.74      www       485:    }
1.258     albertel  486:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       487:        $callargs .= ",'',1"; 
1.793     raeburn   488:        return '<span class="LC_nobreak">'.
                    489:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    490:               &mt('Select User').'</a></span>';
1.111     www       491:    }
                    492:    return '';
1.91      www       493: }
                    494: 
1.1004    www       495: sub selectresource_link {
                    496:    my ($form,$reslink,$arg)=@_;
                    497:    
                    498:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    499:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    500:    unless ($env{'request.course.id'}) { return $arg; }
                    501:    return '<span class="LC_nobreak">'.
                    502:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    503:               $arg.'</a></span>';
                    504: }
                    505: 
                    506: 
                    507: 
1.653     raeburn   508: sub authorbrowser_javascript {
                    509:     return <<"ENDAUTHORBRW";
1.776     bisitz    510: <script type="text/javascript" language="JavaScript">
1.824     bisitz    511: // <![CDATA[
1.653     raeburn   512: var stdeditbrowser;
                    513: 
                    514: function openauthorbrowser(formname,udom) {
                    515:     var url = '/adm/pickauthor?';
                    516:     url += 'form='+formname+'&roledom='+udom;
                    517:     var title = 'Author_Browser';
                    518:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    519:     options += ',width=700,height=600';
                    520:     stdeditbrowser = open(url,title,options,'1');
                    521:     stdeditbrowser.focus();
                    522: }
                    523: 
1.824     bisitz    524: // ]]>
1.653     raeburn   525: </script>
                    526: ENDAUTHORBRW
                    527: }
                    528: 
1.91      www       529: sub coursebrowser_javascript {
1.909     raeburn   530:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype) = @_;
1.932     raeburn   531:     my $wintitle = 'Course_Browser';
1.931     raeburn   532:     if ($crstype eq 'Community') {
1.932     raeburn   533:         $wintitle = 'Community_Browser';
1.909     raeburn   534:     }
1.876     raeburn   535:     my $id_functions = &javascript_index_functions();
                    536:     my $output = '
1.776     bisitz    537: <script type="text/javascript" language="JavaScript">
1.824     bisitz    538: // <![CDATA[
1.468     raeburn   539:     var stdeditbrowser;'."\n";
1.876     raeburn   540: 
                    541:     $output .= <<"ENDSTDBRW";
1.909     raeburn   542:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       543:         var url = '/adm/pickcourse?';
1.895     raeburn   544:         var formid = getFormIdByName(formname);
1.876     raeburn   545:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  546:         if (domainfilter != null) {
                    547:            if (domainfilter != '') {
                    548:                url += 'domainfilter='+domainfilter+'&';
                    549: 	   }
                    550:         }
1.91      www       551:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  552: 	                            '&cdomelement='+udom+
                    553:                                     '&cnameelement='+desc;
1.468     raeburn   554:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   555:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   556:                 url += '&roleelement='+extra_element;
                    557:                 if (domainfilter == null || domainfilter == '') {
                    558:                     url += '&domainfilter='+extra_element;
                    559:                 }
1.234     raeburn   560:             }
1.468     raeburn   561:             else {
                    562:                 if (formname == 'portform') {
                    563:                     url += '&setroles='+extra_element;
1.800     raeburn   564:                 } else {
                    565:                     if (formname == 'rules') {
                    566:                         url += '&fixeddom='+extra_element; 
                    567:                     }
1.468     raeburn   568:                 }
                    569:             }     
1.230     raeburn   570:         }
1.909     raeburn   571:         if (type != null && type != '') {
                    572:             url += '&type='+type;
                    573:         }
                    574:         if (type_elem != null && type_elem != '') {
                    575:             url += '&typeelement='+type_elem;
                    576:         }
1.872     raeburn   577:         if (formname == 'ccrs') {
                    578:             var ownername = document.forms[formid].ccuname.value;
                    579:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    580:             url += '&cloner='+ownername+':'+ownerdom;
                    581:         }
1.293     raeburn   582:         if (multflag !=null && multflag != '') {
                    583:             url += '&multiple='+multflag;
                    584:         }
1.909     raeburn   585:         var title = '$wintitle';
1.91      www       586:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    587:         options += ',width=700,height=600';
                    588:         stdeditbrowser = open(url,title,options,'1');
                    589:         stdeditbrowser.focus();
                    590:     }
1.876     raeburn   591: $id_functions
                    592: ENDSTDBRW
1.905     raeburn   593:     if (($sec_element ne '') || ($role_element ne '')) {
                    594:         $output .= &setsec_javascript($sec_element,$formname,$role_element);
1.876     raeburn   595:     }
                    596:     $output .= '
                    597: // ]]>
                    598: </script>';
                    599:     return $output;
                    600: }
                    601: 
                    602: sub javascript_index_functions {
                    603:     return <<"ENDJS";
                    604: 
                    605: function getFormIdByName(formname) {
                    606:     for (var i=0;i<document.forms.length;i++) {
                    607:         if (document.forms[i].name == formname) {
                    608:             return i;
                    609:         }
                    610:     }
                    611:     return -1;
                    612: }
                    613: 
                    614: function getIndexByName(formid,item) {
                    615:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    616:         if (document.forms[formid].elements[i].name == item) {
                    617:             return i;
                    618:         }
                    619:     }
                    620:     return -1;
                    621: }
1.468     raeburn   622: 
1.876     raeburn   623: function getDomainFromSelectbox(formname,udom) {
                    624:     var userdom;
                    625:     var formid = getFormIdByName(formname);
                    626:     if (formid > -1) {
                    627:         var domid = getIndexByName(formid,udom);
                    628:         if (domid > -1) {
                    629:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    630:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    631:             }
                    632:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    633:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   634:             }
                    635:         }
                    636:     }
1.876     raeburn   637:     return userdom;
                    638: }
                    639: 
                    640: ENDJS
1.468     raeburn   641: 
1.876     raeburn   642: }
                    643: 
1.1017    raeburn   644: sub javascript_array_indexof {
1.1018    raeburn   645:     return <<ENDJS;
1.1017    raeburn   646: <script type="text/javascript" language="JavaScript">
                    647: // <![CDATA[
                    648: 
                    649: if (!Array.prototype.indexOf) {
                    650:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    651:         "use strict";
                    652:         if (this === void 0 || this === null) {
                    653:             throw new TypeError();
                    654:         }
                    655:         var t = Object(this);
                    656:         var len = t.length >>> 0;
                    657:         if (len === 0) {
                    658:             return -1;
                    659:         }
                    660:         var n = 0;
                    661:         if (arguments.length > 0) {
                    662:             n = Number(arguments[1]);
1.1088    foxr      663:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   664:                 n = 0;
                    665:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    666:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    667:             }
                    668:         }
                    669:         if (n >= len) {
                    670:             return -1;
                    671:         }
                    672:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    673:         for (; k < len; k++) {
                    674:             if (k in t && t[k] === searchElement) {
                    675:                 return k;
                    676:             }
                    677:         }
                    678:         return -1;
                    679:     }
                    680: }
                    681: 
                    682: // ]]>
                    683: </script>
                    684: 
                    685: ENDJS
                    686: 
                    687: }
                    688: 
1.876     raeburn   689: sub userbrowser_javascript {
                    690:     my $id_functions = &javascript_index_functions();
                    691:     return <<"ENDUSERBRW";
                    692: 
1.888     raeburn   693: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   694:     var url = '/adm/pickuser?';
                    695:     var userdom = getDomainFromSelectbox(formname,udom);
                    696:     if (userdom != null) {
                    697:        if (userdom != '') {
                    698:            url += 'srchdom='+userdom+'&';
                    699:        }
                    700:     }
                    701:     url += 'form=' + formname + '&unameelement='+uname+
                    702:                                 '&udomelement='+udom+
                    703:                                 '&ulastelement='+ulast+
                    704:                                 '&ufirstelement='+ufirst+
                    705:                                 '&uemailelement='+uemail+
1.881     raeburn   706:                                 '&hideudomelement='+hideudom+
                    707:                                 '&coursedom='+crsdom;
1.888     raeburn   708:     if ((caller != null) && (caller != undefined)) {
                    709:         url += '&caller='+caller;
                    710:     }
1.876     raeburn   711:     var title = 'User_Browser';
                    712:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    713:     options += ',width=700,height=600';
                    714:     var stdeditbrowser = open(url,title,options,'1');
                    715:     stdeditbrowser.focus();
                    716: }
                    717: 
1.888     raeburn   718: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   719:     var formid = getFormIdByName(formname);
                    720:     if (formid > -1) {
1.888     raeburn   721:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   722:         var domid = getIndexByName(formid,udom);
                    723:         var hidedomid = getIndexByName(formid,origdom);
                    724:         if (hidedomid > -1) {
                    725:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   726:             var unameval = document.forms[formid].elements[unameid].value;
                    727:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    728:                 if (domid > -1) {
                    729:                     var slct = document.forms[formid].elements[domid];
                    730:                     if (slct.type == 'select-one') {
                    731:                         var i;
                    732:                         for (i=0;i<slct.length;i++) {
                    733:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    734:                         }
                    735:                     }
                    736:                     if (slct.type == 'hidden') {
                    737:                         slct.value = fixeddom;
1.876     raeburn   738:                     }
                    739:                 }
1.468     raeburn   740:             }
                    741:         }
                    742:     }
1.876     raeburn   743:     return;
                    744: }
                    745: 
                    746: $id_functions
                    747: ENDUSERBRW
1.468     raeburn   748: }
                    749: 
                    750: sub setsec_javascript {
1.905     raeburn   751:     my ($sec_element,$formname,$role_element) = @_;
                    752:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    753:         $communityrolestr);
                    754:     if ($role_element ne '') {
                    755:         my @allroles = ('st','ta','ep','in','ad');
                    756:         foreach my $crstype ('Course','Community') {
                    757:             if ($crstype eq 'Community') {
                    758:                 foreach my $role (@allroles) {
                    759:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    760:                 }
                    761:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    762:             } else {
                    763:                 foreach my $role (@allroles) {
                    764:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    765:                 }
                    766:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    767:             }
                    768:         }
                    769:         $rolestr = '"'.join('","',@allroles).'"';
                    770:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    771:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    772:     }
1.468     raeburn   773:     my $setsections = qq|
                    774: function setSect(sectionlist) {
1.629     raeburn   775:     var sectionsArray = new Array();
                    776:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    777:         sectionsArray = sectionlist.split(",");
                    778:     }
1.468     raeburn   779:     var numSections = sectionsArray.length;
                    780:     document.$formname.$sec_element.length = 0;
                    781:     if (numSections == 0) {
                    782:         document.$formname.$sec_element.multiple=false;
                    783:         document.$formname.$sec_element.size=1;
                    784:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    785:     } else {
                    786:         if (numSections == 1) {
                    787:             document.$formname.$sec_element.multiple=false;
                    788:             document.$formname.$sec_element.size=1;
                    789:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    790:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    791:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    792:         } else {
                    793:             for (var i=0; i<numSections; i++) {
                    794:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    795:             }
                    796:             document.$formname.$sec_element.multiple=true
                    797:             if (numSections < 3) {
                    798:                 document.$formname.$sec_element.size=numSections;
                    799:             } else {
                    800:                 document.$formname.$sec_element.size=3;
                    801:             }
                    802:             document.$formname.$sec_element.options[0].selected = false
                    803:         }
                    804:     }
1.91      www       805: }
1.905     raeburn   806: 
                    807: function setRole(crstype) {
1.468     raeburn   808: |;
1.905     raeburn   809:     if ($role_element eq '') {
                    810:         $setsections .= '    return;
                    811: }
                    812: ';
                    813:     } else {
                    814:         $setsections .= qq|
                    815:     var elementLength = document.$formname.$role_element.length;
                    816:     var allroles = Array($rolestr);
                    817:     var courserolenames = Array($courserolestr);
                    818:     var communityrolenames = Array($communityrolestr);
                    819:     if (elementLength != undefined) {
                    820:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    821:             if (crstype == 'Course') {
                    822:                 return;
                    823:             } else {
                    824:                 allroles[5] = 'co';
                    825:                 for (var i=0; i<6; i++) {
                    826:                     document.$formname.$role_element.options[i].value = allroles[i];
                    827:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    828:                 }
                    829:             }
                    830:         } else {
                    831:             if (crstype == 'Community') {
                    832:                 return;
                    833:             } else {
                    834:                 allroles[5] = 'cc';
                    835:                 for (var i=0; i<6; i++) {
                    836:                     document.$formname.$role_element.options[i].value = allroles[i];
                    837:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    838:                 }
                    839:             }
                    840:         }
                    841:     }
                    842:     return;
                    843: }
                    844: |;
                    845:     }
1.468     raeburn   846:     return $setsections;
                    847: }
                    848: 
1.91      www       849: sub selectcourse_link {
1.909     raeburn   850:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    851:        $typeelement) = @_;
                    852:    my $type = $selecttype;
1.871     raeburn   853:    my $linktext = &mt('Select Course');
                    854:    if ($selecttype eq 'Community') {
1.909     raeburn   855:        $linktext = &mt('Select Community');
1.906     raeburn   856:    } elsif ($selecttype eq 'Course/Community') {
                    857:        $linktext = &mt('Select Course/Community');
1.909     raeburn   858:        $type = '';
1.1019    raeburn   859:    } elsif ($selecttype eq 'Select') {
                    860:        $linktext = &mt('Select');
                    861:        $type = '';
1.871     raeburn   862:    }
1.787     bisitz    863:    return '<span class="LC_nobreak">'
                    864:          ."<a href='"
                    865:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    866:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   867:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   868:          ."'>".$linktext.'</a>'
1.787     bisitz    869:          .'</span>';
1.74      www       870: }
1.42      matthew   871: 
1.653     raeburn   872: sub selectauthor_link {
                    873:    my ($form,$udom)=@_;
                    874:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    875:           &mt('Select Author').'</a>';
                    876: }
                    877: 
1.876     raeburn   878: sub selectuser_link {
1.881     raeburn   879:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   880:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   881:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   882:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   883:            ');">'.$linktext.'</a>';
1.876     raeburn   884: }
                    885: 
1.273     raeburn   886: sub check_uncheck_jscript {
                    887:     my $jscript = <<"ENDSCRT";
                    888: function checkAll(field) {
                    889:     if (field.length > 0) {
                    890:         for (i = 0; i < field.length; i++) {
1.1093  ! raeburn   891:             if (!field[i].disabled) { 
        !           892:                 field[i].checked = true;
        !           893:             }
1.273     raeburn   894:         }
                    895:     } else {
1.1093  ! raeburn   896:         if (!field.disabled) { 
        !           897:             field.checked = true;
        !           898:         }
1.273     raeburn   899:     }
                    900: }
                    901:  
                    902: function uncheckAll(field) {
                    903:     if (field.length > 0) {
                    904:         for (i = 0; i < field.length; i++) {
                    905:             field[i].checked = false ;
1.543     albertel  906:         }
                    907:     } else {
1.273     raeburn   908:         field.checked = false ;
                    909:     }
                    910: }
                    911: ENDSCRT
                    912:     return $jscript;
                    913: }
                    914: 
1.656     www       915: sub select_timezone {
1.659     raeburn   916:    my ($name,$selected,$onchange,$includeempty)=@_;
                    917:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    918:    if ($includeempty) {
                    919:        $output .= '<option value=""';
                    920:        if (($selected eq '') || ($selected eq 'local')) {
                    921:            $output .= ' selected="selected" ';
                    922:        }
                    923:        $output .= '> </option>';
                    924:    }
1.657     raeburn   925:    my @timezones = DateTime::TimeZone->all_names;
                    926:    foreach my $tzone (@timezones) {
                    927:        $output.= '<option value="'.$tzone.'"';
                    928:        if ($tzone eq $selected) {
                    929:            $output.=' selected="selected"';
                    930:        }
                    931:        $output.=">$tzone</option>\n";
1.656     www       932:    }
                    933:    $output.="</select>";
                    934:    return $output;
                    935: }
1.273     raeburn   936: 
1.687     raeburn   937: sub select_datelocale {
                    938:     my ($name,$selected,$onchange,$includeempty)=@_;
                    939:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    940:     if ($includeempty) {
                    941:         $output .= '<option value=""';
                    942:         if ($selected eq '') {
                    943:             $output .= ' selected="selected" ';
                    944:         }
                    945:         $output .= '> </option>';
                    946:     }
                    947:     my (@possibles,%locale_names);
                    948:     my @locales = DateTime::Locale::Catalog::Locales;
                    949:     foreach my $locale (@locales) {
                    950:         if (ref($locale) eq 'HASH') {
                    951:             my $id = $locale->{'id'};
                    952:             if ($id ne '') {
                    953:                 my $en_terr = $locale->{'en_territory'};
                    954:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   955:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   956:                 if (grep(/^en$/,@languages) || !@languages) {
                    957:                     if ($en_terr ne '') {
                    958:                         $locale_names{$id} = '('.$en_terr.')';
                    959:                     } elsif ($native_terr ne '') {
                    960:                         $locale_names{$id} = $native_terr;
                    961:                     }
                    962:                 } else {
                    963:                     if ($native_terr ne '') {
                    964:                         $locale_names{$id} = $native_terr.' ';
                    965:                     } elsif ($en_terr ne '') {
                    966:                         $locale_names{$id} = '('.$en_terr.')';
                    967:                     }
                    968:                 }
                    969:                 push (@possibles,$id);
                    970:             }
                    971:         }
                    972:     }
                    973:     foreach my $item (sort(@possibles)) {
                    974:         $output.= '<option value="'.$item.'"';
                    975:         if ($item eq $selected) {
                    976:             $output.=' selected="selected"';
                    977:         }
                    978:         $output.=">$item";
                    979:         if ($locale_names{$item} ne '') {
                    980:             $output.="  $locale_names{$item}</option>\n";
                    981:         }
                    982:         $output.="</option>\n";
                    983:     }
                    984:     $output.="</select>";
                    985:     return $output;
                    986: }
                    987: 
1.792     raeburn   988: sub select_language {
                    989:     my ($name,$selected,$includeempty) = @_;
                    990:     my %langchoices;
                    991:     if ($includeempty) {
                    992:         %langchoices = ('' => 'No language preference');
                    993:     }
                    994:     foreach my $id (&languageids()) {
                    995:         my $code = &supportedlanguagecode($id);
                    996:         if ($code) {
                    997:             $langchoices{$code} = &plainlanguagedescription($id);
                    998:         }
                    999:     }
1.970     raeburn  1000:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1001: }
                   1002: 
1.42      matthew  1003: =pod
1.36      matthew  1004: 
1.1088    foxr     1005: 
                   1006: =item * &list_languages()
                   1007: 
                   1008: Returns an array reference that is suitable for use in language prompters.
                   1009: Each array element is itself a two element array.  The first element
                   1010: is the language code.  The second element a descsriptiuon of the 
                   1011: language itself.  This is suitable for use in e.g.
                   1012: &Apache::edit::select_arg (once dereferenced that is).
                   1013: 
                   1014: =cut 
                   1015: 
                   1016: sub list_languages {
                   1017:     my @lang_choices;
                   1018: 
                   1019:     foreach my $id (&languageids()) {
                   1020: 	my $code = &supportedlanguagecode($id);
                   1021: 	if ($code) {
                   1022: 	    my $selector    = $supported_codes{$id};
                   1023: 	    my $description = &plainlanguagedescription($id);
                   1024: 	    push (@lang_choices, [$selector, $description]);
                   1025: 	}
                   1026:     }
                   1027:     return \@lang_choices;
                   1028: }
                   1029: 
                   1030: =pod
                   1031: 
1.648     raeburn  1032: =item * &linked_select_forms(...)
1.36      matthew  1033: 
                   1034: linked_select_forms returns a string containing a <script></script> block
                   1035: and html for two <select> menus.  The select menus will be linked in that
                   1036: changing the value of the first menu will result in new values being placed
                   1037: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1038: order unless a defined order is provided.
1.36      matthew  1039: 
                   1040: linked_select_forms takes the following ordered inputs:
                   1041: 
                   1042: =over 4
                   1043: 
1.112     bowersj2 1044: =item * $formname, the name of the <form> tag
1.36      matthew  1045: 
1.112     bowersj2 1046: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1047: 
1.112     bowersj2 1048: =item * $firstdefault, the default value for the first menu
1.36      matthew  1049: 
1.112     bowersj2 1050: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1051: 
1.112     bowersj2 1052: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1053: 
1.112     bowersj2 1054: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1055: 
1.609     raeburn  1056: =item * $menuorder, the order of values in the first menu
                   1057: 
1.41      ng       1058: =back 
                   1059: 
1.36      matthew  1060: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1061: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1062: values for the first select menu.  The text that coincides with the 
1.41      ng       1063: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1064: and text for the second menu are given in the hash pointed to by 
                   1065: $menu{$choice1}->{'select2'}.  
                   1066: 
1.112     bowersj2 1067:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1068:                        default => "B3",
                   1069:                        select2 => { 
                   1070:                            B1 => "Choice B1",
                   1071:                            B2 => "Choice B2",
                   1072:                            B3 => "Choice B3",
                   1073:                            B4 => "Choice B4"
1.609     raeburn  1074:                            },
                   1075:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1076:                    },
                   1077:                A2 => { text =>"Choice A2" ,
                   1078:                        default => "C2",
                   1079:                        select2 => { 
                   1080:                            C1 => "Choice C1",
                   1081:                            C2 => "Choice C2",
                   1082:                            C3 => "Choice C3"
1.609     raeburn  1083:                            },
                   1084:                        order => ['C2','C1','C3'],
1.112     bowersj2 1085:                    },
                   1086:                A3 => { text =>"Choice A3" ,
                   1087:                        default => "D6",
                   1088:                        select2 => { 
                   1089:                            D1 => "Choice D1",
                   1090:                            D2 => "Choice D2",
                   1091:                            D3 => "Choice D3",
                   1092:                            D4 => "Choice D4",
                   1093:                            D5 => "Choice D5",
                   1094:                            D6 => "Choice D6",
                   1095:                            D7 => "Choice D7"
1.609     raeburn  1096:                            },
                   1097:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1098:                    }
                   1099:                );
1.36      matthew  1100: 
                   1101: =cut
                   1102: 
                   1103: sub linked_select_forms {
                   1104:     my ($formname,
                   1105:         $middletext,
                   1106:         $firstdefault,
                   1107:         $firstselectname,
                   1108:         $secondselectname, 
1.609     raeburn  1109:         $hashref,
                   1110:         $menuorder,
1.36      matthew  1111:         ) = @_;
                   1112:     my $second = "document.$formname.$secondselectname";
                   1113:     my $first = "document.$formname.$firstselectname";
                   1114:     # output the javascript to do the changing
                   1115:     my $result = '';
1.776     bisitz   1116:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1117:     $result.="// <![CDATA[\n";
1.36      matthew  1118:     $result.="var select2data = new Object();\n";
                   1119:     $" = '","';
                   1120:     my $debug = '';
                   1121:     foreach my $s1 (sort(keys(%$hashref))) {
                   1122:         $result.="select2data.d_$s1 = new Object();\n";        
                   1123:         $result.="select2data.d_$s1.def = new String('".
                   1124:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1125:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1126:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1127:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1128:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1129:         }
1.36      matthew  1130:         $result.="\"@s2values\");\n";
                   1131:         $result.="select2data.d_$s1.texts = new Array(";        
                   1132:         my @s2texts;
                   1133:         foreach my $value (@s2values) {
                   1134:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1135:         }
                   1136:         $result.="\"@s2texts\");\n";
                   1137:     }
                   1138:     $"=' ';
                   1139:     $result.= <<"END";
                   1140: 
                   1141: function select1_changed() {
                   1142:     // Determine new choice
                   1143:     var newvalue = "d_" + $first.value;
                   1144:     // update select2
                   1145:     var values     = select2data[newvalue].values;
                   1146:     var texts      = select2data[newvalue].texts;
                   1147:     var select2def = select2data[newvalue].def;
                   1148:     var i;
                   1149:     // out with the old
                   1150:     for (i = 0; i < $second.options.length; i++) {
                   1151:         $second.options[i] = null;
                   1152:     }
                   1153:     // in with the nuclear
                   1154:     for (i=0;i<values.length; i++) {
                   1155:         $second.options[i] = new Option(values[i]);
1.143     matthew  1156:         $second.options[i].value = values[i];
1.36      matthew  1157:         $second.options[i].text = texts[i];
                   1158:         if (values[i] == select2def) {
                   1159:             $second.options[i].selected = true;
                   1160:         }
                   1161:     }
                   1162: }
1.824     bisitz   1163: // ]]>
1.36      matthew  1164: </script>
                   1165: END
                   1166:     # output the initial values for the selection lists
                   1167:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed()\">\n";
1.609     raeburn  1168:     my @order = sort(keys(%{$hashref}));
                   1169:     if (ref($menuorder) eq 'ARRAY') {
                   1170:         @order = @{$menuorder};
                   1171:     }
                   1172:     foreach my $value (@order) {
1.36      matthew  1173:         $result.="    <option value=\"$value\" ";
1.253     albertel 1174:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1175:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1176:     }
                   1177:     $result .= "</select>\n";
                   1178:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1179:     $result .= $middletext;
                   1180:     $result .= "<select size=\"1\" name=\"$secondselectname\">\n";
                   1181:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1182:     
                   1183:     my @secondorder = sort(keys(%select2));
                   1184:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1185:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1186:     }
                   1187:     foreach my $value (@secondorder) {
1.36      matthew  1188:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1189:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1190:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1191:     }
                   1192:     $result .= "</select>\n";
                   1193:     #    return $debug;
                   1194:     return $result;
                   1195: }   #  end of sub linked_select_forms {
                   1196: 
1.45      matthew  1197: =pod
1.44      bowersj2 1198: 
1.973     raeburn  1199: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1200: 
1.112     bowersj2 1201: Returns a string corresponding to an HTML link to the given help
                   1202: $topic, where $topic corresponds to the name of a .tex file in
                   1203: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1204: spaces. 
                   1205: 
                   1206: $text will optionally be linked to the same topic, allowing you to
                   1207: link text in addition to the graphic. If you do not want to link
                   1208: text, but wish to specify one of the later parameters, pass an
                   1209: empty string. 
                   1210: 
                   1211: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1212: the link will not open a new window. If false, the link will open
                   1213: a new window using Javascript. (Default is false.) 
                   1214: 
                   1215: $width and $height are optional numerical parameters that will
                   1216: override the width and height of the popped up window, which may
1.973     raeburn  1217: be useful for certain help topics with big pictures included.
                   1218: 
                   1219: $imgid is the id of the img tag used for the help icon. This may be
                   1220: used in a javascript call to switch the image src.  See 
                   1221: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1222: 
                   1223: =cut
                   1224: 
                   1225: sub help_open_topic {
1.973     raeburn  1226:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1227:     $text = "" if (not defined $text);
1.44      bowersj2 1228:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1229:     $width = 500 if (not defined $width);
1.44      bowersj2 1230:     $height = 400 if (not defined $height);
                   1231:     my $filename = $topic;
                   1232:     $filename =~ s/ /_/g;
                   1233: 
1.48      bowersj2 1234:     my $template = "";
                   1235:     my $link;
1.572     banghart 1236:     
1.159     www      1237:     $topic=~s/\W/\_/g;
1.44      bowersj2 1238: 
1.572     banghart 1239:     if (!$stayOnPage) {
1.1033    www      1240: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1241:     } elsif ($stayOnPage eq 'popup') {
                   1242:         $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 1243:     } else {
1.48      bowersj2 1244: 	$link = "/adm/help/${filename}.hlp";
                   1245:     }
                   1246: 
                   1247:     # Add the text
1.755     neumanie 1248:     if ($text ne "") {	
1.763     bisitz   1249: 	$template.='<span class="LC_help_open_topic">'
                   1250:                   .'<a target="_top" href="'.$link.'">'
                   1251:                   .$text.'</a>';
1.48      bowersj2 1252:     }
                   1253: 
1.763     bisitz   1254:     # (Always) Add the graphic
1.179     matthew  1255:     my $title = &mt('Online Help');
1.667     raeburn  1256:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1257:     if ($imgid ne '') {
                   1258:         $imgid = ' id="'.$imgid.'"';
                   1259:     }
1.763     bisitz   1260:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1261:               .'<img src="'.$helpicon.'" border="0"'
                   1262:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1263:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1264:               .' /></a>';
                   1265:     if ($text ne "") {	
                   1266:         $template.='</span>';
                   1267:     }
1.44      bowersj2 1268:     return $template;
                   1269: 
1.106     bowersj2 1270: }
                   1271: 
                   1272: # This is a quicky function for Latex cheatsheet editing, since it 
                   1273: # appears in at least four places
                   1274: sub helpLatexCheatsheet {
1.1037    www      1275:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1276:     my $out;
1.106     bowersj2 1277:     my $addOther = '';
1.732     raeburn  1278:     if ($topic) {
1.1037    www      1279: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1280:     }
                   1281:     $out = '<span>' # Start cheatsheet
                   1282: 	  .$addOther
                   1283:           .'<span>'
1.1037    www      1284: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1285: 	  .'</span> <span>'
1.1037    www      1286: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1287: 	  .'</span>';
1.732     raeburn  1288:     unless ($not_author) {
1.763     bisitz   1289:         $out .= ' <span>'
1.1037    www      1290: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.763     bisitz   1291: 	       .'</span>';
1.732     raeburn  1292:     }
1.763     bisitz   1293:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1294:     return $out;
1.172     www      1295: }
                   1296: 
1.430     albertel 1297: sub general_help {
                   1298:     my $helptopic='Student_Intro';
                   1299:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1300: 	$helptopic='Authoring_Intro';
1.907     raeburn  1301:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1302: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1303:     } elsif ($env{'request.role'}=~/^dc/) {
                   1304:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1305:     }
                   1306:     return $helptopic;
                   1307: }
                   1308: 
                   1309: sub update_help_link {
                   1310:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1311:     my $origurl = $ENV{'REQUEST_URI'};
                   1312:     $origurl=~s|^/~|/priv/|;
                   1313:     my $timestamp = time;
                   1314:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1315:         $$datum = &escape($$datum);
                   1316:     }
                   1317: 
                   1318:     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";
                   1319:     my $output .= <<"ENDOUTPUT";
                   1320: <script type="text/javascript">
1.824     bisitz   1321: // <![CDATA[
1.430     albertel 1322: banner_link = '$banner_link';
1.824     bisitz   1323: // ]]>
1.430     albertel 1324: </script>
                   1325: ENDOUTPUT
                   1326:     return $output;
                   1327: }
                   1328: 
                   1329: # now just updates the help link and generates a blue icon
1.193     raeburn  1330: sub help_open_menu {
1.430     albertel 1331:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1332: 	= @_;    
1.949     droeschl 1333:     $stayOnPage = 1;
1.430     albertel 1334:     my $output;
                   1335:     if ($component_help) {
                   1336: 	if (!$text) {
                   1337: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1338: 				       $width,$height);
                   1339: 	} else {
                   1340: 	    my $help_text;
                   1341: 	    $help_text=&unescape($topic);
                   1342: 	    $output='<table><tr><td>'.
                   1343: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1344: 				 $width,$height).'</td></tr></table>';
                   1345: 	}
                   1346:     }
                   1347:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1348:     return $output.$banner_link;
                   1349: }
                   1350: 
                   1351: sub top_nav_help {
                   1352:     my ($text) = @_;
1.436     albertel 1353:     $text = &mt($text);
1.949     droeschl 1354:     my $stay_on_page = 1;
                   1355: 
1.572     banghart 1356:     my $link = ($stay_on_page) ? "javascript:helpMenu('display')"
1.436     albertel 1357: 	                     : "javascript:helpMenu('open')";
1.572     banghart 1358:     my $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
1.436     albertel 1359: 
1.201     raeburn  1360:     my $title = &mt('Get help');
1.436     albertel 1361: 
                   1362:     return <<"END";
                   1363: $banner_link
                   1364:  <a href="$link" title="$title">$text</a>
                   1365: END
                   1366: }
                   1367: 
                   1368: sub help_menu_js {
                   1369:     my ($text) = @_;
1.949     droeschl 1370:     my $stayOnPage = 1;
1.436     albertel 1371:     my $width = 620;
                   1372:     my $height = 600;
1.430     albertel 1373:     my $helptopic=&general_help();
                   1374:     my $details_link = '/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1375:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1376:     my $start_page =
                   1377:         &Apache::loncommon::start_page('Help Menu', undef,
                   1378: 				       {'frameset'    => 1,
                   1379: 					'js_ready'    => 1,
                   1380: 					'add_entries' => {
                   1381: 					    'border' => '0',
1.579     raeburn  1382: 					    'rows'   => "110,*",},});
1.331     albertel 1383:     my $end_page =
                   1384:         &Apache::loncommon::end_page({'frameset' => 1,
                   1385: 				      'js_ready' => 1,});
                   1386: 
1.436     albertel 1387:     my $template .= <<"ENDTEMPLATE";
                   1388: <script type="text/javascript">
1.877     bisitz   1389: // <![CDATA[
1.253     albertel 1390: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1391: var banner_link = '';
1.243     raeburn  1392: function helpMenu(target) {
                   1393:     var caller = this;
                   1394:     if (target == 'open') {
                   1395:         var newWindow = null;
                   1396:         try {
1.262     albertel 1397:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1398:         }
                   1399:         catch(error) {
                   1400:             writeHelp(caller);
                   1401:             return;
                   1402:         }
                   1403:         if (newWindow) {
                   1404:             caller = newWindow;
                   1405:         }
1.193     raeburn  1406:     }
1.243     raeburn  1407:     writeHelp(caller);
                   1408:     return;
                   1409: }
                   1410: function writeHelp(caller) {
1.1072    raeburn  1411:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" />\\n<frame name="bodyframe" src="$details_link" />\\n$end_page')
1.243     raeburn  1412:     caller.document.close()
                   1413:     caller.focus()
1.193     raeburn  1414: }
1.877     bisitz   1415: // END LON-CAPA Internal -->
1.253     albertel 1416: // ]]>
1.436     albertel 1417: </script>
1.193     raeburn  1418: ENDTEMPLATE
                   1419:     return $template;
                   1420: }
                   1421: 
1.172     www      1422: sub help_open_bug {
                   1423:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1424:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1425:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1426:     $text = "" if (not defined $text);
                   1427: 	$stayOnPage=1;
1.184     albertel 1428:     $width = 600 if (not defined $width);
                   1429:     $height = 600 if (not defined $height);
1.172     www      1430: 
                   1431:     $topic=~s/\W+/\+/g;
                   1432:     my $link='';
                   1433:     my $template='';
1.379     albertel 1434:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1435: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1436:     if (!$stayOnPage)
                   1437:     {
                   1438: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1439:     }
                   1440:     else
                   1441:     {
                   1442: 	$link = $url;
                   1443:     }
                   1444:     # Add the text
                   1445:     if ($text ne "")
                   1446:     {
                   1447: 	$template .= 
                   1448:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1449:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1450:     }
                   1451: 
                   1452:     # Add the graphic
1.179     matthew  1453:     my $title = &mt('Report a Bug');
1.215     albertel 1454:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1455:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1456:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1457: ENDTEMPLATE
                   1458:     if ($text ne '') { $template.='</td></tr></table>' };
                   1459:     return $template;
                   1460: 
                   1461: }
                   1462: 
                   1463: sub help_open_faq {
                   1464:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1465:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1466:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1467:     $text = "" if (not defined $text);
                   1468: 	$stayOnPage=1;
                   1469:     $width = 350 if (not defined $width);
                   1470:     $height = 400 if (not defined $height);
                   1471: 
                   1472:     $topic=~s/\W+/\+/g;
                   1473:     my $link='';
                   1474:     my $template='';
                   1475:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1476:     if (!$stayOnPage)
                   1477:     {
                   1478: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1479:     }
                   1480:     else
                   1481:     {
                   1482: 	$link = $url;
                   1483:     }
                   1484: 
                   1485:     # Add the text
                   1486:     if ($text ne "")
                   1487:     {
                   1488: 	$template .= 
1.173     www      1489:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1490:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1491:     }
                   1492: 
                   1493:     # Add the graphic
1.179     matthew  1494:     my $title = &mt('View the FAQ');
1.215     albertel 1495:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1496:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1497:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1498: ENDTEMPLATE
                   1499:     if ($text ne '') { $template.='</td></tr></table>' };
                   1500:     return $template;
                   1501: 
1.44      bowersj2 1502: }
1.37      matthew  1503: 
1.180     matthew  1504: ###############################################################
                   1505: ###############################################################
                   1506: 
1.45      matthew  1507: =pod
                   1508: 
1.648     raeburn  1509: =item * &change_content_javascript():
1.256     matthew  1510: 
                   1511: This and the next function allow you to create small sections of an
                   1512: otherwise static HTML page that you can update on the fly with
                   1513: Javascript, even in Netscape 4.
                   1514: 
                   1515: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1516: must be written to the HTML page once. It will prove the Javascript
                   1517: function "change(name, content)". Calling the change function with the
                   1518: name of the section 
                   1519: you want to update, matching the name passed to C<changable_area>, and
                   1520: the new content you want to put in there, will put the content into
                   1521: that area.
                   1522: 
                   1523: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1524: to contain room for the original contents. You need to "make space"
                   1525: for whatever changes you wish to make, and be B<sure> to check your
                   1526: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1527: it's adequate for updating a one-line status display, but little more.
                   1528: This script will set the space to 100% width, so you only need to
                   1529: worry about height in Netscape 4.
                   1530: 
                   1531: Modern browsers are much less limiting, and if you can commit to the
                   1532: user not using Netscape 4, this feature may be used freely with
                   1533: pretty much any HTML.
                   1534: 
                   1535: =cut
                   1536: 
                   1537: sub change_content_javascript {
                   1538:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1539:     if ($env{'browser.type'} eq 'netscape' &&
                   1540: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1541: 	return (<<NETSCAPE4);
                   1542: 	function change(name, content) {
                   1543: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1544: 	    doc.open();
                   1545: 	    doc.write(content);
                   1546: 	    doc.close();
                   1547: 	}
                   1548: NETSCAPE4
                   1549:     } else {
                   1550: 	# Otherwise, we need to use semi-standards-compliant code
                   1551: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1552: 	# is really scary, and every useful browser supports it
                   1553: 	return (<<DOMBASED);
                   1554: 	function change(name, content) {
                   1555: 	    element = document.getElementById(name);
                   1556: 	    element.innerHTML = content;
                   1557: 	}
                   1558: DOMBASED
                   1559:     }
                   1560: }
                   1561: 
                   1562: =pod
                   1563: 
1.648     raeburn  1564: =item * &changable_area($name,$origContent):
1.256     matthew  1565: 
                   1566: This provides a "changable area" that can be modified on the fly via
                   1567: the Javascript code provided in C<change_content_javascript>. $name is
                   1568: the name you will use to reference the area later; do not repeat the
                   1569: same name on a given HTML page more then once. $origContent is what
                   1570: the area will originally contain, which can be left blank.
                   1571: 
                   1572: =cut
                   1573: 
                   1574: sub changable_area {
                   1575:     my ($name, $origContent) = @_;
                   1576: 
1.258     albertel 1577:     if ($env{'browser.type'} eq 'netscape' &&
                   1578: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1579: 	# If this is netscape 4, we need to use the Layer tag
                   1580: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1581:     } else {
                   1582: 	return "<span id='$name'>$origContent</span>";
                   1583:     }
                   1584: }
                   1585: 
                   1586: =pod
                   1587: 
1.648     raeburn  1588: =item * &viewport_geometry_js 
1.590     raeburn  1589: 
                   1590: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1591: 
                   1592: =cut
                   1593: 
                   1594: 
                   1595: sub viewport_geometry_js { 
                   1596:     return <<"GEOMETRY";
                   1597: var Geometry = {};
                   1598: function init_geometry() {
                   1599:     if (Geometry.init) { return };
                   1600:     Geometry.init=1;
                   1601:     if (window.innerHeight) {
                   1602:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1603:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1604:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1605:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1606:     }
                   1607:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1608:         Geometry.getViewportHeight =
                   1609:             function() { return document.documentElement.clientHeight; };
                   1610:         Geometry.getViewportWidth =
                   1611:             function() { return document.documentElement.clientWidth; };
                   1612: 
                   1613:         Geometry.getHorizontalScroll =
                   1614:             function() { return document.documentElement.scrollLeft; };
                   1615:         Geometry.getVerticalScroll =
                   1616:             function() { return document.documentElement.scrollTop; };
                   1617:     }
                   1618:     else if (document.body.clientHeight) {
                   1619:         Geometry.getViewportHeight =
                   1620:             function() { return document.body.clientHeight; };
                   1621:         Geometry.getViewportWidth =
                   1622:             function() { return document.body.clientWidth; };
                   1623:         Geometry.getHorizontalScroll =
                   1624:             function() { return document.body.scrollLeft; };
                   1625:         Geometry.getVerticalScroll =
                   1626:             function() { return document.body.scrollTop; };
                   1627:     }
                   1628: }
                   1629: 
                   1630: GEOMETRY
                   1631: }
                   1632: 
                   1633: =pod
                   1634: 
1.648     raeburn  1635: =item * &viewport_size_js()
1.590     raeburn  1636: 
                   1637: 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. 
                   1638: 
                   1639: =cut
                   1640: 
                   1641: sub viewport_size_js {
                   1642:     my $geometry = &viewport_geometry_js();
                   1643:     return <<"DIMS";
                   1644: 
                   1645: $geometry
                   1646: 
                   1647: function getViewportDims(width,height) {
                   1648:     init_geometry();
                   1649:     width.value = Geometry.getViewportWidth();
                   1650:     height.value = Geometry.getViewportHeight();
                   1651:     return;
                   1652: }
                   1653: 
                   1654: DIMS
                   1655: }
                   1656: 
                   1657: =pod
                   1658: 
1.648     raeburn  1659: =item * &resize_textarea_js()
1.565     albertel 1660: 
                   1661: emits the needed javascript to resize a textarea to be as big as possible
                   1662: 
                   1663: creates a function resize_textrea that takes two IDs first should be
                   1664: the id of the element to resize, second should be the id of a div that
                   1665: surrounds everything that comes after the textarea, this routine needs
                   1666: to be attached to the <body> for the onload and onresize events.
                   1667: 
1.648     raeburn  1668: =back
1.565     albertel 1669: 
                   1670: =cut
                   1671: 
                   1672: sub resize_textarea_js {
1.590     raeburn  1673:     my $geometry = &viewport_geometry_js();
1.565     albertel 1674:     return <<"RESIZE";
                   1675:     <script type="text/javascript">
1.824     bisitz   1676: // <![CDATA[
1.590     raeburn  1677: $geometry
1.565     albertel 1678: 
1.588     albertel 1679: function getX(element) {
                   1680:     var x = 0;
                   1681:     while (element) {
                   1682: 	x += element.offsetLeft;
                   1683: 	element = element.offsetParent;
                   1684:     }
                   1685:     return x;
                   1686: }
                   1687: function getY(element) {
                   1688:     var y = 0;
                   1689:     while (element) {
                   1690: 	y += element.offsetTop;
                   1691: 	element = element.offsetParent;
                   1692:     }
                   1693:     return y;
                   1694: }
                   1695: 
                   1696: 
1.565     albertel 1697: function resize_textarea(textarea_id,bottom_id) {
                   1698:     init_geometry();
                   1699:     var textarea        = document.getElementById(textarea_id);
                   1700:     //alert(textarea);
                   1701: 
1.588     albertel 1702:     var textarea_top    = getY(textarea);
1.565     albertel 1703:     var textarea_height = textarea.offsetHeight;
                   1704:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1705:     var bottom_top      = getY(bottom);
1.565     albertel 1706:     var bottom_height   = bottom.offsetHeight;
                   1707:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1708:     var fudge           = 23;
1.565     albertel 1709:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1710:     if (new_height < 300) {
                   1711: 	new_height = 300;
                   1712:     }
                   1713:     textarea.style.height=new_height+'px';
                   1714: }
1.824     bisitz   1715: // ]]>
1.565     albertel 1716: </script>
                   1717: RESIZE
                   1718: 
                   1719: }
                   1720: 
                   1721: =pod
                   1722: 
1.256     matthew  1723: =head1 Excel and CSV file utility routines
                   1724: 
                   1725: =over 4
                   1726: 
                   1727: =cut
                   1728: 
                   1729: ###############################################################
                   1730: ###############################################################
                   1731: 
                   1732: =pod
                   1733: 
1.648     raeburn  1734: =item * &csv_translate($text) 
1.37      matthew  1735: 
1.185     www      1736: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1737: format.
                   1738: 
                   1739: =cut
                   1740: 
1.180     matthew  1741: ###############################################################
                   1742: ###############################################################
1.37      matthew  1743: sub csv_translate {
                   1744:     my $text = shift;
                   1745:     $text =~ s/\"/\"\"/g;
1.209     albertel 1746:     $text =~ s/\n/ /g;
1.37      matthew  1747:     return $text;
                   1748: }
1.180     matthew  1749: 
                   1750: ###############################################################
                   1751: ###############################################################
                   1752: 
                   1753: =pod
                   1754: 
1.648     raeburn  1755: =item * &define_excel_formats()
1.180     matthew  1756: 
                   1757: Define some commonly used Excel cell formats.
                   1758: 
                   1759: Currently supported formats:
                   1760: 
                   1761: =over 4
                   1762: 
                   1763: =item header
                   1764: 
                   1765: =item bold
                   1766: 
                   1767: =item h1
                   1768: 
                   1769: =item h2
                   1770: 
                   1771: =item h3
                   1772: 
1.256     matthew  1773: =item h4
                   1774: 
                   1775: =item i
                   1776: 
1.180     matthew  1777: =item date
                   1778: 
                   1779: =back
                   1780: 
                   1781: Inputs: $workbook
                   1782: 
                   1783: Returns: $format, a hash reference.
                   1784: 
1.1057    foxr     1785: 
1.180     matthew  1786: =cut
                   1787: 
                   1788: ###############################################################
                   1789: ###############################################################
                   1790: sub define_excel_formats {
                   1791:     my ($workbook) = @_;
                   1792:     my $format;
                   1793:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1794:                                                 bottom    => 1,
                   1795:                                                 align     => 'center');
                   1796:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1797:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1798:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1799:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1800:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1801:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1802:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1803:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1804:     return $format;
                   1805: }
                   1806: 
                   1807: ###############################################################
                   1808: ###############################################################
1.113     bowersj2 1809: 
                   1810: =pod
                   1811: 
1.648     raeburn  1812: =item * &create_workbook()
1.255     matthew  1813: 
                   1814: Create an Excel worksheet.  If it fails, output message on the
                   1815: request object and return undefs.
                   1816: 
                   1817: Inputs: Apache request object
                   1818: 
                   1819: Returns (undef) on failure, 
                   1820:     Excel worksheet object, scalar with filename, and formats 
                   1821:     from &Apache::loncommon::define_excel_formats on success
                   1822: 
                   1823: =cut
                   1824: 
                   1825: ###############################################################
                   1826: ###############################################################
                   1827: sub create_workbook {
                   1828:     my ($r) = @_;
                   1829:         #
                   1830:     # Create the excel spreadsheet
                   1831:     my $filename = '/prtspool/'.
1.258     albertel 1832:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1833:         time.'_'.rand(1000000000).'.xls';
                   1834:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1835:     if (! defined($workbook)) {
                   1836:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1837:         $r->print(
                   1838:             '<p class="LC_error">'
                   1839:            .&mt('Problems occurred in creating the new Excel file.')
                   1840:            .' '.&mt('This error has been logged.')
                   1841:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1842:            .'</p>'
                   1843:         );
1.255     matthew  1844:         return (undef);
                   1845:     }
                   1846:     #
1.1014    foxr     1847:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1848:     #
                   1849:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1850:     return ($workbook,$filename,$format);
                   1851: }
                   1852: 
                   1853: ###############################################################
                   1854: ###############################################################
                   1855: 
                   1856: =pod
                   1857: 
1.648     raeburn  1858: =item * &create_text_file()
1.113     bowersj2 1859: 
1.542     raeburn  1860: Create a file to write to and eventually make available to the user.
1.256     matthew  1861: If file creation fails, outputs an error message on the request object and 
                   1862: return undefs.
1.113     bowersj2 1863: 
1.256     matthew  1864: Inputs: Apache request object, and file suffix
1.113     bowersj2 1865: 
1.256     matthew  1866: Returns (undef) on failure, 
                   1867:     Filehandle and filename on success.
1.113     bowersj2 1868: 
                   1869: =cut
                   1870: 
1.256     matthew  1871: ###############################################################
                   1872: ###############################################################
                   1873: sub create_text_file {
                   1874:     my ($r,$suffix) = @_;
                   1875:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1876:     my $fh;
                   1877:     my $filename = '/prtspool/'.
1.258     albertel 1878:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1879:         time.'_'.rand(1000000000).'.'.$suffix;
                   1880:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1881:     if (! defined($fh)) {
                   1882:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1883:         $r->print(
                   1884:             '<p class="LC_error">'
                   1885:            .&mt('Problems occurred in creating the output file.')
                   1886:            .' '.&mt('This error has been logged.')
                   1887:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1888:            .'</p>'
                   1889:         );
1.113     bowersj2 1890:     }
1.256     matthew  1891:     return ($fh,$filename)
1.113     bowersj2 1892: }
                   1893: 
                   1894: 
1.256     matthew  1895: =pod 
1.113     bowersj2 1896: 
                   1897: =back
                   1898: 
                   1899: =cut
1.37      matthew  1900: 
                   1901: ###############################################################
1.33      matthew  1902: ##        Home server <option> list generating code          ##
                   1903: ###############################################################
1.35      matthew  1904: 
1.169     www      1905: # ------------------------------------------
                   1906: 
                   1907: sub domain_select {
                   1908:     my ($name,$value,$multiple)=@_;
                   1909:     my %domains=map { 
1.514     albertel 1910: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1911:     } &Apache::lonnet::all_domains();
1.169     www      1912:     if ($multiple) {
                   1913: 	$domains{''}=&mt('Any domain');
1.550     albertel 1914: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1915: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1916:     } else {
1.550     albertel 1917: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1918: 	return &select_form($name,$value,\%domains);
1.169     www      1919:     }
                   1920: }
                   1921: 
1.282     albertel 1922: #-------------------------------------------
                   1923: 
                   1924: =pod
                   1925: 
1.519     raeburn  1926: =head1 Routines for form select boxes
                   1927: 
                   1928: =over 4
                   1929: 
1.648     raeburn  1930: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1931: 
                   1932: Returns a string containing a <select> element int multiple mode
                   1933: 
                   1934: 
                   1935: Args:
                   1936:   $name - name of the <select> element
1.506     raeburn  1937:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1938:   $size - number of rows long the select element is
1.283     albertel 1939:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1940:           (shown text should already have been &mt())
1.506     raeburn  1941:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1942: 
1.282     albertel 1943: =cut
                   1944: 
                   1945: #-------------------------------------------
1.169     www      1946: sub multiple_select_form {
1.284     albertel 1947:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1948:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1949:     my $output='';
1.191     matthew  1950:     if (! defined($size)) {
                   1951:         $size = 4;
1.283     albertel 1952:         if (scalar(keys(%$hash))<4) {
                   1953:             $size = scalar(keys(%$hash));
1.191     matthew  1954:         }
                   1955:     }
1.734     bisitz   1956:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1957:     my @order;
1.506     raeburn  1958:     if (ref($order) eq 'ARRAY')  {
                   1959:         @order = @{$order};
                   1960:     } else {
                   1961:         @order = sort(keys(%$hash));
1.501     banghart 1962:     }
                   1963:     if (exists($$hash{'select_form_order'})) {
                   1964:         @order = @{$$hash{'select_form_order'}};
                   1965:     }
                   1966:         
1.284     albertel 1967:     foreach my $key (@order) {
1.356     albertel 1968:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1969:         $output.='selected="selected" ' if ($selected{$key});
                   1970:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1971:     }
                   1972:     $output.="</select>\n";
                   1973:     return $output;
                   1974: }
                   1975: 
1.88      www      1976: #-------------------------------------------
                   1977: 
                   1978: =pod
                   1979: 
1.970     raeburn  1980: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      1981: 
                   1982: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  1983: allow a user to select options from a ref to a hash containing:
                   1984: option_name => displayed text. An optional $onchange can include
                   1985: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   1986: 
1.88      www      1987: See lonrights.pm for an example invocation and use.
                   1988: 
                   1989: =cut
                   1990: 
                   1991: #-------------------------------------------
                   1992: sub select_form {
1.970     raeburn  1993:     my ($def,$name,$hashref,$onchange) = @_;
                   1994:     return unless (ref($hashref) eq 'HASH');
                   1995:     if ($onchange) {
                   1996:         $onchange = ' onchange="'.$onchange.'"';
                   1997:     }
                   1998:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 1999:     my @keys;
1.970     raeburn  2000:     if (exists($hashref->{'select_form_order'})) {
                   2001: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2002:     } else {
1.970     raeburn  2003: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2004:     }
1.356     albertel 2005:     foreach my $key (@keys) {
                   2006:         $selectform.=
                   2007: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2008:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2009:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2010:     }
                   2011:     $selectform.="</select>";
                   2012:     return $selectform;
                   2013: }
                   2014: 
1.475     www      2015: # For display filters
                   2016: 
                   2017: sub display_filter {
1.1074    raeburn  2018:     my ($context) = @_;
1.475     www      2019:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2020:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2021:     my $phraseinput = 'hidden';
                   2022:     my $includeinput = 'hidden';
                   2023:     my ($checked,$includetypestext);
                   2024:     if ($env{'form.displayfilter'} eq 'containing') {
                   2025:         $phraseinput = 'text'; 
                   2026:         if ($context eq 'parmslog') {
                   2027:             $includeinput = 'checkbox';
                   2028:             if ($env{'form.includetypes'}) {
                   2029:                 $checked = ' checked="checked"';
                   2030:             }
                   2031:             $includetypestext = &mt('Include parameter types');
                   2032:         }
                   2033:     } else {
                   2034:         $includetypestext = '&nbsp;';
                   2035:     }
                   2036:     my ($additional,$secondid,$thirdid);
                   2037:     if ($context eq 'parmslog') {
                   2038:         $additional = 
                   2039:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2040:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2041:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2042:             '</label>';
                   2043:         $secondid = 'includetypes';
                   2044:         $thirdid = 'includetypestext';
                   2045:     }
                   2046:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2047:                                                     '$secondid','$thirdid')";
                   2048:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2049: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2050: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2051: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2052:            &mt('Filter: [_1]',
1.477     www      2053: 	   &select_form($env{'form.displayfilter'},
                   2054: 			'displayfilter',
1.970     raeburn  2055: 			{'currentfolder' => 'Current folder/page',
1.477     www      2056: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2057: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2058: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2059:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2060:                          '" />'.$additional;
                   2061: }
                   2062: 
                   2063: sub display_filter_js {
                   2064:     my $includetext = &mt('Include parameter types');
                   2065:     return <<"ENDJS";
                   2066:   
                   2067: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2068:     var firstType = 'hidden';
                   2069:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2070:         firstType = 'text';
                   2071:     }
                   2072:     firstObject = document.getElementById(firstid);
                   2073:     if (typeof(firstObject) == 'object') {
                   2074:         if (firstObject.type != firstType) {
                   2075:             changeInputType(firstObject,firstType);
                   2076:         }
                   2077:     }
                   2078:     if (context == 'parmslog') {
                   2079:         var secondType = 'hidden';
                   2080:         if (firstType == 'text') {
                   2081:             secondType = 'checkbox';
                   2082:         }
                   2083:         secondObject = document.getElementById(secondid);  
                   2084:         if (typeof(secondObject) == 'object') {
                   2085:             if (secondObject.type != secondType) {
                   2086:                 changeInputType(secondObject,secondType);
                   2087:             }
                   2088:         }
                   2089:         var textItem = document.getElementById(thirdid);
                   2090:         var currtext = textItem.innerHTML;
                   2091:         var newtext;
                   2092:         if (firstType == 'text') {
                   2093:             newtext = '$includetext';
                   2094:         } else {
                   2095:             newtext = '&nbsp;';
                   2096:         }
                   2097:         if (currtext != newtext) {
                   2098:             textItem.innerHTML = newtext;
                   2099:         }
                   2100:     }
                   2101:     return;
                   2102: }
                   2103: 
                   2104: function changeInputType(oldObject,newType) {
                   2105:     var newObject = document.createElement('input');
                   2106:     newObject.type = newType;
                   2107:     if (oldObject.size) {
                   2108:         newObject.size = oldObject.size;
                   2109:     }
                   2110:     if (oldObject.value) {
                   2111:         newObject.value = oldObject.value;
                   2112:     }
                   2113:     if (oldObject.name) {
                   2114:         newObject.name = oldObject.name;
                   2115:     }
                   2116:     if (oldObject.id) {
                   2117:         newObject.id = oldObject.id;
                   2118:     }
                   2119:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2120:     return;
                   2121: }
                   2122: 
                   2123: ENDJS
1.475     www      2124: }
                   2125: 
1.167     www      2126: sub gradeleveldescription {
                   2127:     my $gradelevel=shift;
                   2128:     my %gradelevels=(0 => 'Not specified',
                   2129: 		     1 => 'Grade 1',
                   2130: 		     2 => 'Grade 2',
                   2131: 		     3 => 'Grade 3',
                   2132: 		     4 => 'Grade 4',
                   2133: 		     5 => 'Grade 5',
                   2134: 		     6 => 'Grade 6',
                   2135: 		     7 => 'Grade 7',
                   2136: 		     8 => 'Grade 8',
                   2137: 		     9 => 'Grade 9',
                   2138: 		     10 => 'Grade 10',
                   2139: 		     11 => 'Grade 11',
                   2140: 		     12 => 'Grade 12',
                   2141: 		     13 => 'Grade 13',
                   2142: 		     14 => '100 Level',
                   2143: 		     15 => '200 Level',
                   2144: 		     16 => '300 Level',
                   2145: 		     17 => '400 Level',
                   2146: 		     18 => 'Graduate Level');
                   2147:     return &mt($gradelevels{$gradelevel});
                   2148: }
                   2149: 
1.163     www      2150: sub select_level_form {
                   2151:     my ($deflevel,$name)=@_;
                   2152:     unless ($deflevel) { $deflevel=0; }
1.167     www      2153:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2154:     for (my $i=0; $i<=18; $i++) {
                   2155:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2156:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2157:                 ">".&gradeleveldescription($i)."</option>\n";
                   2158:     }
                   2159:     $selectform.="</select>";
                   2160:     return $selectform;
1.163     www      2161: }
1.167     www      2162: 
1.35      matthew  2163: #-------------------------------------------
                   2164: 
1.45      matthew  2165: =pod
                   2166: 
1.910     raeburn  2167: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms)
1.35      matthew  2168: 
                   2169: Returns a string containing a <select name='$name' size='1'> form to 
                   2170: allow a user to select the domain to preform an operation in.  
                   2171: See loncreateuser.pm for an example invocation and use.
                   2172: 
1.90      www      2173: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2174: selected");
                   2175: 
1.743     raeburn  2176: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2177: 
1.910     raeburn  2178: 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.
                   2179: 
                   2180: The optional $incdoms is a reference to an array of domains which will be the only available options. 
1.563     raeburn  2181: 
1.35      matthew  2182: =cut
                   2183: 
                   2184: #-------------------------------------------
1.34      matthew  2185: sub select_dom_form {
1.910     raeburn  2186:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms) = @_;
1.872     raeburn  2187:     if ($onchange) {
1.874     raeburn  2188:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2189:     }
1.910     raeburn  2190:     my @domains;
                   2191:     if (ref($incdoms) eq 'ARRAY') {
                   2192:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2193:     } else {
                   2194:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2195:     }
1.90      www      2196:     if ($includeempty) { @domains=('',@domains); }
1.743     raeburn  2197:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2198:     foreach my $dom (@domains) {
                   2199:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2200:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2201:         if ($showdomdesc) {
                   2202:             if ($dom ne '') {
                   2203:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2204:                 if ($domdesc ne '') {
                   2205:                     $selectdomain .= ' ('.$domdesc.')';
                   2206:                 }
                   2207:             } 
                   2208:         }
                   2209:         $selectdomain .= "</option>\n";
1.34      matthew  2210:     }
                   2211:     $selectdomain.="</select>";
                   2212:     return $selectdomain;
                   2213: }
                   2214: 
1.35      matthew  2215: #-------------------------------------------
                   2216: 
1.45      matthew  2217: =pod
                   2218: 
1.648     raeburn  2219: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2220: 
1.586     raeburn  2221: input: 4 arguments (two required, two optional) - 
                   2222:     $domain - domain of new user
                   2223:     $name - name of form element
                   2224:     $default - Value of 'default' causes a default item to be first 
                   2225:                             option, and selected by default. 
                   2226:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2227:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2228: output: returns 2 items: 
1.586     raeburn  2229: (a) form element which contains either:
                   2230:    (i) <select name="$name">
                   2231:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2232:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2233:        </select>
                   2234:        form item if there are multiple library servers in $domain, or
                   2235:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2236:        if there is only one library server in $domain.
                   2237: 
                   2238: (b) number of library servers found.
                   2239: 
                   2240: See loncreateuser.pm for example of use.
1.35      matthew  2241: 
                   2242: =cut
                   2243: 
                   2244: #-------------------------------------------
1.586     raeburn  2245: sub home_server_form_item {
                   2246:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2247:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2248:     my $result;
                   2249:     my $numlib = keys(%servers);
                   2250:     if ($numlib > 1) {
                   2251:         $result .= '<select name="'.$name.'" />'."\n";
                   2252:         if ($default) {
1.804     bisitz   2253:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2254:                        '</option>'."\n";
                   2255:         }
                   2256:         foreach my $hostid (sort(keys(%servers))) {
                   2257:             $result.= '<option value="'.$hostid.'">'.
                   2258: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2259:         }
                   2260:         $result .= '</select>'."\n";
                   2261:     } elsif ($numlib == 1) {
                   2262:         my $hostid;
                   2263:         foreach my $item (keys(%servers)) {
                   2264:             $hostid = $item;
                   2265:         }
                   2266:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2267:                    $hostid.'" />';
                   2268:                    if (!$hide) {
                   2269:                        $result .= $hostid.' '.$servers{$hostid};
                   2270:                    }
                   2271:                    $result .= "\n";
                   2272:     } elsif ($default) {
                   2273:         $result .= '<input type="hidden" name="'.$name.
                   2274:                    '" value="default" />';
                   2275:                    if (!$hide) {
                   2276:                        $result .= &mt('default');
                   2277:                    }
                   2278:                    $result .= "\n";
1.33      matthew  2279:     }
1.586     raeburn  2280:     return ($result,$numlib);
1.33      matthew  2281: }
1.112     bowersj2 2282: 
                   2283: =pod
                   2284: 
1.534     albertel 2285: =back 
                   2286: 
1.112     bowersj2 2287: =cut
1.87      matthew  2288: 
                   2289: ###############################################################
1.112     bowersj2 2290: ##                  Decoding User Agent                      ##
1.87      matthew  2291: ###############################################################
                   2292: 
                   2293: =pod
                   2294: 
1.112     bowersj2 2295: =head1 Decoding the User Agent
                   2296: 
                   2297: =over 4
                   2298: 
                   2299: =item * &decode_user_agent()
1.87      matthew  2300: 
                   2301: Inputs: $r
                   2302: 
                   2303: Outputs:
                   2304: 
                   2305: =over 4
                   2306: 
1.112     bowersj2 2307: =item * $httpbrowser
1.87      matthew  2308: 
1.112     bowersj2 2309: =item * $clientbrowser
1.87      matthew  2310: 
1.112     bowersj2 2311: =item * $clientversion
1.87      matthew  2312: 
1.112     bowersj2 2313: =item * $clientmathml
1.87      matthew  2314: 
1.112     bowersj2 2315: =item * $clientunicode
1.87      matthew  2316: 
1.112     bowersj2 2317: =item * $clientos
1.87      matthew  2318: 
                   2319: =back
                   2320: 
1.157     matthew  2321: =back 
                   2322: 
1.87      matthew  2323: =cut
                   2324: 
                   2325: ###############################################################
                   2326: ###############################################################
                   2327: sub decode_user_agent {
1.247     albertel 2328:     my ($r)=@_;
1.87      matthew  2329:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2330:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2331:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2332:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2333:     my $clientbrowser='unknown';
                   2334:     my $clientversion='0';
                   2335:     my $clientmathml='';
                   2336:     my $clientunicode='0';
                   2337:     for (my $i=0;$i<=$#browsertype;$i++) {
                   2338:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\:/,$browsertype[$i]);
                   2339: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2340: 	    $clientbrowser=$bname;
                   2341:             $httpbrowser=~/$vreg/i;
                   2342: 	    $clientversion=$1;
                   2343:             $clientmathml=($clientversion>=$minv);
                   2344:             $clientunicode=($clientversion>=$univ);
                   2345: 	}
                   2346:     }
                   2347:     my $clientos='unknown';
                   2348:     if (($httpbrowser=~/linux/i) ||
                   2349:         ($httpbrowser=~/unix/i) ||
                   2350:         ($httpbrowser=~/ux/i) ||
                   2351:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2352:     if (($httpbrowser=~/vax/i) ||
                   2353:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2354:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2355:     if (($httpbrowser=~/mac/i) ||
                   2356:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
                   2357:     if ($httpbrowser=~/win/i) { $clientos='win'; }
                   2358:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
                   2359:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   2360:             $clientunicode,$clientos,);
                   2361: }
                   2362: 
1.32      matthew  2363: ###############################################################
                   2364: ##    Authentication changing form generation subroutines    ##
                   2365: ###############################################################
                   2366: ##
                   2367: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2368: ## hash, and have reasonable default values.
                   2369: ##
                   2370: ##    formname = the name given in the <form> tag.
1.35      matthew  2371: #-------------------------------------------
                   2372: 
1.45      matthew  2373: =pod
                   2374: 
1.112     bowersj2 2375: =head1 Authentication Routines
                   2376: 
                   2377: =over 4
                   2378: 
1.648     raeburn  2379: =item * &authform_xxxxxx()
1.35      matthew  2380: 
                   2381: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2382: handle some of the conveniences required for authentication forms.  
                   2383: This is not an optimal method, but it works.  
                   2384: 
                   2385: =over 4
                   2386: 
1.112     bowersj2 2387: =item * authform_header
1.35      matthew  2388: 
1.112     bowersj2 2389: =item * authform_authorwarning
1.35      matthew  2390: 
1.112     bowersj2 2391: =item * authform_nochange
1.35      matthew  2392: 
1.112     bowersj2 2393: =item * authform_kerberos
1.35      matthew  2394: 
1.112     bowersj2 2395: =item * authform_internal
1.35      matthew  2396: 
1.112     bowersj2 2397: =item * authform_filesystem
1.35      matthew  2398: 
                   2399: =back
                   2400: 
1.648     raeburn  2401: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2402: 
1.35      matthew  2403: =cut
                   2404: 
                   2405: #-------------------------------------------
1.32      matthew  2406: sub authform_header{  
                   2407:     my %in = (
                   2408:         formname => 'cu',
1.80      albertel 2409:         kerb_def_dom => '',
1.32      matthew  2410:         @_,
                   2411:     );
                   2412:     $in{'formname'} = 'document.' . $in{'formname'};
                   2413:     my $result='';
1.80      albertel 2414: 
                   2415: #---------------------------------------------- Code for upper case translation
                   2416:     my $Javascript_toUpperCase;
                   2417:     unless ($in{kerb_def_dom}) {
                   2418:         $Javascript_toUpperCase =<<"END";
                   2419:         switch (choice) {
                   2420:            case 'krb': currentform.elements[choicearg].value =
                   2421:                currentform.elements[choicearg].value.toUpperCase();
                   2422:                break;
                   2423:            default:
                   2424:         }
                   2425: END
                   2426:     } else {
                   2427:         $Javascript_toUpperCase = "";
                   2428:     }
                   2429: 
1.165     raeburn  2430:     my $radioval = "'nochange'";
1.591     raeburn  2431:     if (defined($in{'curr_authtype'})) {
                   2432:         if ($in{'curr_authtype'} ne '') {
                   2433:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2434:         }
1.174     matthew  2435:     }
1.165     raeburn  2436:     my $argfield = 'null';
1.591     raeburn  2437:     if (defined($in{'mode'})) {
1.165     raeburn  2438:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2439:             if (defined($in{'curr_autharg'})) {
                   2440:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2441:                     $argfield = "'$in{'curr_autharg'}'";
                   2442:                 }
                   2443:             }
                   2444:         }
                   2445:     }
                   2446: 
1.32      matthew  2447:     $result.=<<"END";
                   2448: var current = new Object();
1.165     raeburn  2449: current.radiovalue = $radioval;
                   2450: current.argfield = $argfield;
1.32      matthew  2451: 
                   2452: function changed_radio(choice,currentform) {
                   2453:     var choicearg = choice + 'arg';
                   2454:     // If a radio button in changed, we need to change the argfield
                   2455:     if (current.radiovalue != choice) {
                   2456:         current.radiovalue = choice;
                   2457:         if (current.argfield != null) {
                   2458:             currentform.elements[current.argfield].value = '';
                   2459:         }
                   2460:         if (choice == 'nochange') {
                   2461:             current.argfield = null;
                   2462:         } else {
                   2463:             current.argfield = choicearg;
                   2464:             switch(choice) {
                   2465:                 case 'krb': 
                   2466:                     currentform.elements[current.argfield].value = 
                   2467:                         "$in{'kerb_def_dom'}";
                   2468:                 break;
                   2469:               default:
                   2470:                 break;
                   2471:             }
                   2472:         }
                   2473:     }
                   2474:     return;
                   2475: }
1.22      www      2476: 
1.32      matthew  2477: function changed_text(choice,currentform) {
                   2478:     var choicearg = choice + 'arg';
                   2479:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2480:         $Javascript_toUpperCase
1.32      matthew  2481:         // clear old field
                   2482:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2483:             currentform.elements[current.argfield].value = '';
                   2484:         }
                   2485:         current.argfield = choicearg;
                   2486:     }
                   2487:     set_auth_radio_buttons(choice,currentform);
                   2488:     return;
1.20      www      2489: }
1.32      matthew  2490: 
                   2491: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2492:     var numauthchoices = currentform.login.length;
                   2493:     if (typeof numauthchoices  == "undefined") {
                   2494:         return;
                   2495:     } 
1.32      matthew  2496:     var i=0;
1.986     raeburn  2497:     while (i < numauthchoices) {
1.32      matthew  2498:         if (currentform.login[i].value == newvalue) { break; }
                   2499:         i++;
                   2500:     }
1.986     raeburn  2501:     if (i == numauthchoices) {
1.32      matthew  2502:         return;
                   2503:     }
                   2504:     current.radiovalue = newvalue;
                   2505:     currentform.login[i].checked = true;
                   2506:     return;
                   2507: }
                   2508: END
                   2509:     return $result;
                   2510: }
                   2511: 
                   2512: sub authform_authorwarning{
                   2513:     my $result='';
1.144     matthew  2514:     $result='<i>'.
                   2515:         &mt('As a general rule, only authors or co-authors should be '.
                   2516:             'filesystem authenticated '.
                   2517:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2518:     return $result;
                   2519: }
                   2520: 
                   2521: sub authform_nochange{  
                   2522:     my %in = (
                   2523:               formname => 'document.cu',
                   2524:               kerb_def_dom => 'MSU.EDU',
                   2525:               @_,
                   2526:           );
1.586     raeburn  2527:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'}); 
                   2528:     my $result;
                   2529:     if (keys(%can_assign) == 0) {
                   2530:         $result = &mt('Under you current role you are not permitted to change login settings for this user');  
                   2531:     } else {
                   2532:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2533:                   '<input type="radio" name="login" value="nochange" '.
                   2534:                   'checked="checked" onclick="'.
1.281     albertel 2535:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2536: 	    '</label>';
1.586     raeburn  2537:     }
1.32      matthew  2538:     return $result;
                   2539: }
                   2540: 
1.591     raeburn  2541: sub authform_kerberos {
1.32      matthew  2542:     my %in = (
                   2543:               formname => 'document.cu',
                   2544:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2545:               kerb_def_auth => 'krb4',
1.32      matthew  2546:               @_,
                   2547:               );
1.586     raeburn  2548:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2549:         $autharg,$jscall);
                   2550:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.80      albertel 2551:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2552:        $check5 = ' checked="checked"';
1.80      albertel 2553:     } else {
1.772     bisitz   2554:        $check4 = ' checked="checked"';
1.80      albertel 2555:     }
1.165     raeburn  2556:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2557:     if (defined($in{'curr_authtype'})) {
                   2558:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2559:             $krbcheck = ' checked="checked"';
1.623     raeburn  2560:             if (defined($in{'mode'})) {
                   2561:                 if ($in{'mode'} eq 'modifyuser') {
                   2562:                     $krbcheck = '';
                   2563:                 }
                   2564:             }
1.591     raeburn  2565:             if (defined($in{'curr_kerb_ver'})) {
                   2566:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2567:                     $check5 = ' checked="checked"';
1.591     raeburn  2568:                     $check4 = '';
                   2569:                 } else {
1.772     bisitz   2570:                     $check4 = ' checked="checked"';
1.591     raeburn  2571:                     $check5 = '';
                   2572:                 }
1.586     raeburn  2573:             }
1.591     raeburn  2574:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2575:                 $krbarg = $in{'curr_autharg'};
                   2576:             }
1.586     raeburn  2577:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2578:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2579:                     $result = 
                   2580:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2581:         $in{'curr_autharg'},$krbver);
                   2582:                 } else {
                   2583:                     $result =
                   2584:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2585:                 }
                   2586:                 return $result; 
                   2587:             }
                   2588:         }
                   2589:     } else {
                   2590:         if ($authnum == 1) {
1.784     bisitz   2591:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2592:         }
                   2593:     }
1.586     raeburn  2594:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2595:         return;
1.587     raeburn  2596:     } elsif ($authtype eq '') {
1.591     raeburn  2597:         if (defined($in{'mode'})) {
1.587     raeburn  2598:             if ($in{'mode'} eq 'modifycourse') {
                   2599:                 if ($authnum == 1) {
1.784     bisitz   2600:                     $authtype = '<input type="hidden" name="login" value="krb" />';
1.587     raeburn  2601:                 }
                   2602:             }
                   2603:         }
1.586     raeburn  2604:     }
                   2605:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2606:     if ($authtype eq '') {
                   2607:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2608:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2609:                     $krbcheck.' />';
                   2610:     }
                   2611:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
                   2612:         ($can_assign{'krb4'} && !$can_assign{'krb5'} && 
                   2613:          $in{'curr_authtype'} eq 'krb5') ||
                   2614:         (!$can_assign{'krb4'} && $can_assign{'krb5'} && 
                   2615:          $in{'curr_authtype'} eq 'krb4')) {
                   2616:         $result .= &mt
1.144     matthew  2617:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2618:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2619:          '<label>'.$authtype,
1.281     albertel 2620:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2621:              'value="'.$krbarg.'" '.
1.144     matthew  2622:              'onchange="'.$jscall.'" />',
1.281     albertel 2623:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2624:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2625: 	 '</label>');
1.586     raeburn  2626:     } elsif ($can_assign{'krb4'}) {
                   2627:         $result .= &mt
                   2628:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2629:          '[_3] Version 4 [_4]',
                   2630:          '<label>'.$authtype,
                   2631:          '</label><input type="text" size="10" name="krbarg" '.
                   2632:              'value="'.$krbarg.'" '.
                   2633:              'onchange="'.$jscall.'" />',
                   2634:          '<label><input type="hidden" name="krbver" value="4" />',
                   2635:          '</label>');
                   2636:     } elsif ($can_assign{'krb5'}) {
                   2637:         $result .= &mt
                   2638:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2639:          '[_3] Version 5 [_4]',
                   2640:          '<label>'.$authtype,
                   2641:          '</label><input type="text" size="10" name="krbarg" '.
                   2642:              'value="'.$krbarg.'" '.
                   2643:              'onchange="'.$jscall.'" />',
                   2644:          '<label><input type="hidden" name="krbver" value="5" />',
                   2645:          '</label>');
                   2646:     }
1.32      matthew  2647:     return $result;
                   2648: }
                   2649: 
                   2650: sub authform_internal{  
1.586     raeburn  2651:     my %in = (
1.32      matthew  2652:                 formname => 'document.cu',
                   2653:                 kerb_def_dom => 'MSU.EDU',
                   2654:                 @_,
                   2655:                 );
1.586     raeburn  2656:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
                   2657:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2658:     if (defined($in{'curr_authtype'})) {
                   2659:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2660:             if ($can_assign{'int'}) {
1.772     bisitz   2661:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2662:                 if (defined($in{'mode'})) {
                   2663:                     if ($in{'mode'} eq 'modifyuser') {
                   2664:                         $intcheck = '';
                   2665:                     }
                   2666:                 }
1.591     raeburn  2667:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2668:                     $intarg = $in{'curr_autharg'};
                   2669:                 }
                   2670:             } else {
                   2671:                 $result = &mt('Currently internally authenticated.');
                   2672:                 return $result;
1.165     raeburn  2673:             }
                   2674:         }
1.586     raeburn  2675:     } else {
                   2676:         if ($authnum == 1) {
1.784     bisitz   2677:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2678:         }
                   2679:     }
                   2680:     if (!$can_assign{'int'}) {
                   2681:         return;
1.587     raeburn  2682:     } elsif ($authtype eq '') {
1.591     raeburn  2683:         if (defined($in{'mode'})) {
1.587     raeburn  2684:             if ($in{'mode'} eq 'modifycourse') {
                   2685:                 if ($authnum == 1) {
1.784     bisitz   2686:                     $authtype = '<input type="hidden" name="login" value="int" />';
1.587     raeburn  2687:                 }
                   2688:             }
                   2689:         }
1.165     raeburn  2690:     }
1.586     raeburn  2691:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2692:     if ($authtype eq '') {
                   2693:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2694:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2695:     }
1.605     bisitz   2696:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2697:                $intarg.'" onchange="'.$jscall.'" />';
                   2698:     $result = &mt
1.144     matthew  2699:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2700:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2701:     $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  2702:     return $result;
                   2703: }
                   2704: 
                   2705: sub authform_local{  
                   2706:     my %in = (
                   2707:               formname => 'document.cu',
                   2708:               kerb_def_dom => 'MSU.EDU',
                   2709:               @_,
                   2710:               );
1.586     raeburn  2711:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
                   2712:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2713:     if (defined($in{'curr_authtype'})) {
                   2714:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2715:             if ($can_assign{'loc'}) {
1.772     bisitz   2716:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2717:                 if (defined($in{'mode'})) {
                   2718:                     if ($in{'mode'} eq 'modifyuser') {
                   2719:                         $loccheck = '';
                   2720:                     }
                   2721:                 }
1.591     raeburn  2722:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2723:                     $locarg = $in{'curr_autharg'};
                   2724:                 }
                   2725:             } else {
                   2726:                 $result = &mt('Currently using local (institutional) authentication.');
                   2727:                 return $result;
1.165     raeburn  2728:             }
                   2729:         }
1.586     raeburn  2730:     } else {
                   2731:         if ($authnum == 1) {
1.784     bisitz   2732:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2733:         }
                   2734:     }
                   2735:     if (!$can_assign{'loc'}) {
                   2736:         return;
1.587     raeburn  2737:     } elsif ($authtype eq '') {
1.591     raeburn  2738:         if (defined($in{'mode'})) {
1.587     raeburn  2739:             if ($in{'mode'} eq 'modifycourse') {
                   2740:                 if ($authnum == 1) {
1.784     bisitz   2741:                     $authtype = '<input type="hidden" name="login" value="loc" />';
1.587     raeburn  2742:                 }
                   2743:             }
                   2744:         }
1.165     raeburn  2745:     }
1.586     raeburn  2746:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2747:     if ($authtype eq '') {
                   2748:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2749:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2750:                     $jscall.'" />';
                   2751:     }
                   2752:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2753:                $locarg.'" onchange="'.$jscall.'" />';
                   2754:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2755:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2756:     return $result;
                   2757: }
                   2758: 
                   2759: sub authform_filesystem{  
                   2760:     my %in = (
                   2761:               formname => 'document.cu',
                   2762:               kerb_def_dom => 'MSU.EDU',
                   2763:               @_,
                   2764:               );
1.586     raeburn  2765:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
                   2766:     my ($authnum,%can_assign) =  &get_assignable_auth($in{'domain'});
1.591     raeburn  2767:     if (defined($in{'curr_authtype'})) {
                   2768:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2769:             if ($can_assign{'fsys'}) {
1.772     bisitz   2770:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2771:                 if (defined($in{'mode'})) {
                   2772:                     if ($in{'mode'} eq 'modifyuser') {
                   2773:                         $fsyscheck = '';
                   2774:                     }
                   2775:                 }
1.586     raeburn  2776:             } else {
                   2777:                 $result = &mt('Currently Filesystem Authenticated.');
                   2778:                 return $result;
                   2779:             }           
                   2780:         }
                   2781:     } else {
                   2782:         if ($authnum == 1) {
1.784     bisitz   2783:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2784:         }
                   2785:     }
                   2786:     if (!$can_assign{'fsys'}) {
                   2787:         return;
1.587     raeburn  2788:     } elsif ($authtype eq '') {
1.591     raeburn  2789:         if (defined($in{'mode'})) {
1.587     raeburn  2790:             if ($in{'mode'} eq 'modifycourse') {
                   2791:                 if ($authnum == 1) {
1.784     bisitz   2792:                     $authtype = '<input type="hidden" name="login" value="fsys" />';
1.587     raeburn  2793:                 }
                   2794:             }
                   2795:         }
1.586     raeburn  2796:     }
                   2797:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2798:     if ($authtype eq '') {
                   2799:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2800:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2801:                     $jscall.'" />';
                   2802:     }
                   2803:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2804:                ' onchange="'.$jscall.'" />';
                   2805:     $result = &mt
1.144     matthew  2806:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2807:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2808:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2809:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2810:                   'onchange="'.$jscall.'" />');
1.32      matthew  2811:     return $result;
                   2812: }
                   2813: 
1.586     raeburn  2814: sub get_assignable_auth {
                   2815:     my ($dom) = @_;
                   2816:     if ($dom eq '') {
                   2817:         $dom = $env{'request.role.domain'};
                   2818:     }
                   2819:     my %can_assign = (
                   2820:                           krb4 => 1,
                   2821:                           krb5 => 1,
                   2822:                           int  => 1,
                   2823:                           loc  => 1,
                   2824:                      );
                   2825:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2826:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2827:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2828:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2829:             my $context;
                   2830:             if ($env{'request.role'} =~ /^au/) {
                   2831:                 $context = 'author';
                   2832:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2833:                 $context = 'domain';
                   2834:             } elsif ($env{'request.course.id'}) {
                   2835:                 $context = 'course';
                   2836:             }
                   2837:             if ($context) {
                   2838:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2839:                    %can_assign = %{$authhash->{$context}}; 
                   2840:                 }
                   2841:             }
                   2842:         }
                   2843:     }
                   2844:     my $authnum = 0;
                   2845:     foreach my $key (keys(%can_assign)) {
                   2846:         if ($can_assign{$key}) {
                   2847:             $authnum ++;
                   2848:         }
                   2849:     }
                   2850:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2851:         $authnum --;
                   2852:     }
                   2853:     return ($authnum,%can_assign);
                   2854: }
                   2855: 
1.80      albertel 2856: ###############################################################
                   2857: ##    Get Kerberos Defaults for Domain                 ##
                   2858: ###############################################################
                   2859: ##
                   2860: ## Returns default kerberos version and an associated argument
                   2861: ## as listed in file domain.tab. If not listed, provides
                   2862: ## appropriate default domain and kerberos version.
                   2863: ##
                   2864: #-------------------------------------------
                   2865: 
                   2866: =pod
                   2867: 
1.648     raeburn  2868: =item * &get_kerberos_defaults()
1.80      albertel 2869: 
                   2870: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2871: version and domain. If not found, it defaults to version 4 and the 
                   2872: domain of the server.
1.80      albertel 2873: 
1.648     raeburn  2874: =over 4
                   2875: 
1.80      albertel 2876: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2877: 
1.648     raeburn  2878: =back
                   2879: 
                   2880: =back
                   2881: 
1.80      albertel 2882: =cut
                   2883: 
                   2884: #-------------------------------------------
                   2885: sub get_kerberos_defaults {
                   2886:     my $domain=shift;
1.641     raeburn  2887:     my ($krbdef,$krbdefdom);
                   2888:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2889:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2890:         $krbdef = $domdefaults{'auth_def'};
                   2891:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2892:     } else {
1.80      albertel 2893:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2894:         my $krbdefdom=$1;
                   2895:         $krbdefdom=~tr/a-z/A-Z/;
                   2896:         $krbdef = "krb4";
                   2897:     }
                   2898:     return ($krbdef,$krbdefdom);
                   2899: }
1.112     bowersj2 2900: 
1.32      matthew  2901: 
1.46      matthew  2902: ###############################################################
                   2903: ##                Thesaurus Functions                        ##
                   2904: ###############################################################
1.20      www      2905: 
1.46      matthew  2906: =pod
1.20      www      2907: 
1.112     bowersj2 2908: =head1 Thesaurus Functions
                   2909: 
                   2910: =over 4
                   2911: 
1.648     raeburn  2912: =item * &initialize_keywords()
1.46      matthew  2913: 
                   2914: Initializes the package variable %Keywords if it is empty.  Uses the
                   2915: package variable $thesaurus_db_file.
                   2916: 
                   2917: =cut
                   2918: 
                   2919: ###################################################
                   2920: 
                   2921: sub initialize_keywords {
                   2922:     return 1 if (scalar keys(%Keywords));
                   2923:     # If we are here, %Keywords is empty, so fill it up
                   2924:     #   Make sure the file we need exists...
                   2925:     if (! -e $thesaurus_db_file) {
                   2926:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2927:                                  " failed because it does not exist");
                   2928:         return 0;
                   2929:     }
                   2930:     #   Set up the hash as a database
                   2931:     my %thesaurus_db;
                   2932:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2933:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2934:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2935:                                  $thesaurus_db_file);
                   2936:         return 0;
                   2937:     } 
                   2938:     #  Get the average number of appearances of a word.
                   2939:     my $avecount = $thesaurus_db{'average.count'};
                   2940:     #  Put keywords (those that appear > average) into %Keywords
                   2941:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2942:         my ($count,undef) = split /:/,$data;
                   2943:         $Keywords{$word}++ if ($count > $avecount);
                   2944:     }
                   2945:     untie %thesaurus_db;
                   2946:     # Remove special values from %Keywords.
1.356     albertel 2947:     foreach my $value ('total.count','average.count') {
                   2948:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2949:   }
1.46      matthew  2950:     return 1;
                   2951: }
                   2952: 
                   2953: ###################################################
                   2954: 
                   2955: =pod
                   2956: 
1.648     raeburn  2957: =item * &keyword($word)
1.46      matthew  2958: 
                   2959: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   2960: than the average number of times in the thesaurus database.  Calls 
                   2961: &initialize_keywords
                   2962: 
                   2963: =cut
                   2964: 
                   2965: ###################################################
1.20      www      2966: 
                   2967: sub keyword {
1.46      matthew  2968:     return if (!&initialize_keywords());
                   2969:     my $word=lc(shift());
                   2970:     $word=~s/\W//g;
                   2971:     return exists($Keywords{$word});
1.20      www      2972: }
1.46      matthew  2973: 
                   2974: ###############################################################
                   2975: 
                   2976: =pod 
1.20      www      2977: 
1.648     raeburn  2978: =item * &get_related_words()
1.46      matthew  2979: 
1.160     matthew  2980: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  2981: an array of words.  If the keyword is not in the thesaurus, an empty array
                   2982: will be returned.  The order of the words returned is determined by the
                   2983: database which holds them.
                   2984: 
                   2985: Uses global $thesaurus_db_file.
                   2986: 
1.1057    foxr     2987: 
1.46      matthew  2988: =cut
                   2989: 
                   2990: ###############################################################
                   2991: sub get_related_words {
                   2992:     my $keyword = shift;
                   2993:     my %thesaurus_db;
                   2994:     if (! -e $thesaurus_db_file) {
                   2995:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   2996:                                  "failed because the file does not exist");
                   2997:         return ();
                   2998:     }
                   2999:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3000:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3001:         return ();
                   3002:     } 
                   3003:     my @Words=();
1.429     www      3004:     my $count=0;
1.46      matthew  3005:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3006: 	# The first element is the number of times
                   3007: 	# the word appears.  We do not need it now.
1.429     www      3008: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3009: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3010: 	my $threshold=$mostfrequentcount/10;
                   3011:         foreach my $possibleword (@RelatedWords) {
                   3012:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3013:             if ($wordcount>$threshold) {
                   3014: 		push(@Words,$word);
                   3015:                 $count++;
                   3016:                 if ($count>10) { last; }
                   3017: 	    }
1.20      www      3018:         }
                   3019:     }
1.46      matthew  3020:     untie %thesaurus_db;
                   3021:     return @Words;
1.14      harris41 3022: }
1.1090    foxr     3023: ###############################################################
                   3024: #
                   3025: #  Spell checking
                   3026: #
                   3027: 
                   3028: =pod
                   3029: 
                   3030: =head1 Spell checking
                   3031: 
                   3032: =over 4
                   3033: 
                   3034: =item * &check_spelling($wordlist $language)
                   3035: 
                   3036: Takes a string containing words and feeds it to an external
                   3037: spellcheck program via a pipeline. Returns a string containing
                   3038: them mis-spelled words.
                   3039: 
                   3040: Parameters:
                   3041: 
                   3042: =over 4
                   3043: 
                   3044: =item - $wordlist
                   3045: 
                   3046: String that will be fed into the spellcheck program.
                   3047: 
                   3048: =item - $language
                   3049: 
                   3050: Language string that specifies the language for which the spell
                   3051: check will be performed.
                   3052: 
                   3053: =back
                   3054: 
                   3055: =back
                   3056: 
                   3057: Note: This sub assumes that aspell is installed.
                   3058: 
                   3059: 
                   3060: =cut
                   3061: 
1.46      matthew  3062: 
1.112     bowersj2 3063: =pod
                   3064: 
                   3065: =back
                   3066: 
                   3067: =cut
1.61      www      3068: 
1.1090    foxr     3069: sub check_spelling {
                   3070:     my ($wordlist, $language) = @_;
1.1091    foxr     3071:     my @misspellings;
                   3072:     
                   3073:     # Generate the speller and set the langauge.
                   3074:     # if explicitly selected:
1.1090    foxr     3075: 
1.1091    foxr     3076:     my $speller = Text::Aspell->new;
1.1090    foxr     3077:     if ($language) {
1.1091    foxr     3078: 	$speller->set_option('lang', $language);
1.1090    foxr     3079:     }
                   3080: 
1.1091    foxr     3081:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3082: 
1.1091    foxr     3083:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3084: 
1.1091    foxr     3085:     foreach my $word (@words) {
                   3086: 	if(! $speller->check($word)) {
                   3087: 	    push(@misspellings, $word);
1.1090    foxr     3088: 	}
                   3089:     }
1.1091    foxr     3090:     return join(' ', @misspellings);
                   3091:     
1.1090    foxr     3092: }
                   3093: 
1.61      www      3094: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3095: =pod
                   3096: 
1.112     bowersj2 3097: =head1 User Name Functions
                   3098: 
                   3099: =over 4
                   3100: 
1.648     raeburn  3101: =item * &plainname($uname,$udom,$first)
1.81      albertel 3102: 
1.112     bowersj2 3103: Takes a users logon name and returns it as a string in
1.226     albertel 3104: "first middle last generation" form 
                   3105: if $first is set to 'lastname' then it returns it as
                   3106: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3107: 
                   3108: =cut
1.61      www      3109: 
1.295     www      3110: 
1.81      albertel 3111: ###############################################################
1.61      www      3112: sub plainname {
1.226     albertel 3113:     my ($uname,$udom,$first)=@_;
1.537     albertel 3114:     return if (!defined($uname) || !defined($udom));
1.295     www      3115:     my %names=&getnames($uname,$udom);
1.226     albertel 3116:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3117: 					  $names{'middlename'},
                   3118: 					  $names{'lastname'},
                   3119: 					  $names{'generation'},$first);
                   3120:     $name=~s/^\s+//;
1.62      www      3121:     $name=~s/\s+$//;
                   3122:     $name=~s/\s+/ /g;
1.353     albertel 3123:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3124:     return $name;
1.61      www      3125: }
1.66      www      3126: 
                   3127: # -------------------------------------------------------------------- Nickname
1.81      albertel 3128: =pod
                   3129: 
1.648     raeburn  3130: =item * &nickname($uname,$udom)
1.81      albertel 3131: 
                   3132: Gets a users name and returns it as a string as
                   3133: 
                   3134: "&quot;nickname&quot;"
1.66      www      3135: 
1.81      albertel 3136: if the user has a nickname or
                   3137: 
                   3138: "first middle last generation"
                   3139: 
                   3140: if the user does not
                   3141: 
                   3142: =cut
1.66      www      3143: 
                   3144: sub nickname {
                   3145:     my ($uname,$udom)=@_;
1.537     albertel 3146:     return if (!defined($uname) || !defined($udom));
1.295     www      3147:     my %names=&getnames($uname,$udom);
1.68      albertel 3148:     my $name=$names{'nickname'};
1.66      www      3149:     if ($name) {
                   3150:        $name='&quot;'.$name.'&quot;'; 
                   3151:     } else {
                   3152:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3153: 	     $names{'lastname'}.' '.$names{'generation'};
                   3154:        $name=~s/\s+$//;
                   3155:        $name=~s/\s+/ /g;
                   3156:     }
                   3157:     return $name;
                   3158: }
                   3159: 
1.295     www      3160: sub getnames {
                   3161:     my ($uname,$udom)=@_;
1.537     albertel 3162:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3163:     if ($udom eq 'public' && $uname eq 'public') {
                   3164: 	return ('lastname' => &mt('Public'));
                   3165:     }
1.295     www      3166:     my $id=$uname.':'.$udom;
                   3167:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3168:     if ($cached) {
                   3169: 	return %{$names};
                   3170:     } else {
                   3171: 	my %loadnames=&Apache::lonnet::get('environment',
                   3172:                     ['firstname','middlename','lastname','generation','nickname'],
                   3173: 					 $udom,$uname);
                   3174: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3175: 	return %loadnames;
                   3176:     }
                   3177: }
1.61      www      3178: 
1.542     raeburn  3179: # -------------------------------------------------------------------- getemails
1.648     raeburn  3180: 
1.542     raeburn  3181: =pod
                   3182: 
1.648     raeburn  3183: =item * &getemails($uname,$udom)
1.542     raeburn  3184: 
                   3185: Gets a user's email information and returns it as a hash with keys:
                   3186: notification, critnotification, permanentemail
                   3187: 
                   3188: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3189: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3190:  
1.648     raeburn  3191: 
1.542     raeburn  3192: =cut
                   3193: 
1.648     raeburn  3194: 
1.466     albertel 3195: sub getemails {
                   3196:     my ($uname,$udom)=@_;
                   3197:     if ($udom eq 'public' && $uname eq 'public') {
                   3198: 	return;
                   3199:     }
1.467     www      3200:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3201:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3202:     my $id=$uname.':'.$udom;
                   3203:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3204:     if ($cached) {
                   3205: 	return %{$names};
                   3206:     } else {
                   3207: 	my %loadnames=&Apache::lonnet::get('environment',
                   3208:                     			   ['notification','critnotification',
                   3209: 					    'permanentemail'],
                   3210: 					   $udom,$uname);
                   3211: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3212: 	return %loadnames;
                   3213:     }
                   3214: }
                   3215: 
1.551     albertel 3216: sub flush_email_cache {
                   3217:     my ($uname,$udom)=@_;
                   3218:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3219:     if (!$uname) { $uname=$env{'user.name'};   }
                   3220:     return if ($udom eq 'public' && $uname eq 'public');
                   3221:     my $id=$uname.':'.$udom;
                   3222:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3223: }
                   3224: 
1.728     raeburn  3225: # -------------------------------------------------------------------- getlangs
                   3226: 
                   3227: =pod
                   3228: 
                   3229: =item * &getlangs($uname,$udom)
                   3230: 
                   3231: Gets a user's language preference and returns it as a hash with key:
                   3232: language.
                   3233: 
                   3234: =cut
                   3235: 
                   3236: 
                   3237: sub getlangs {
                   3238:     my ($uname,$udom) = @_;
                   3239:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3240:     if (!$uname) { $uname=$env{'user.name'};   }
                   3241:     my $id=$uname.':'.$udom;
                   3242:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3243:     if ($cached) {
                   3244:         return %{$langs};
                   3245:     } else {
                   3246:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3247:                                            $udom,$uname);
                   3248:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3249:         return %loadlangs;
                   3250:     }
                   3251: }
                   3252: 
                   3253: sub flush_langs_cache {
                   3254:     my ($uname,$udom)=@_;
                   3255:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3256:     if (!$uname) { $uname=$env{'user.name'};   }
                   3257:     return if ($udom eq 'public' && $uname eq 'public');
                   3258:     my $id=$uname.':'.$udom;
                   3259:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3260: }
                   3261: 
1.61      www      3262: # ------------------------------------------------------------------ Screenname
1.81      albertel 3263: 
                   3264: =pod
                   3265: 
1.648     raeburn  3266: =item * &screenname($uname,$udom)
1.81      albertel 3267: 
                   3268: Gets a users screenname and returns it as a string
                   3269: 
                   3270: =cut
1.61      www      3271: 
                   3272: sub screenname {
                   3273:     my ($uname,$udom)=@_;
1.258     albertel 3274:     if ($uname eq $env{'user.name'} &&
                   3275: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3276:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3277:     return $names{'screenname'};
1.62      www      3278: }
                   3279: 
1.212     albertel 3280: 
1.802     bisitz   3281: # ------------------------------------------------------------- Confirm Wrapper
                   3282: =pod
                   3283: 
                   3284: =item confirmwrapper
                   3285: 
                   3286: Wrap messages about completion of operation in box
                   3287: 
                   3288: =cut
                   3289: 
                   3290: sub confirmwrapper {
                   3291:     my ($message)=@_;
                   3292:     if ($message) {
                   3293:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3294:                .$message."\n"
                   3295:                .'</div>'."\n";
                   3296:     } else {
                   3297:         return $message;
                   3298:     }
                   3299: }
                   3300: 
1.62      www      3301: # ------------------------------------------------------------- Message Wrapper
                   3302: 
                   3303: sub messagewrapper {
1.369     www      3304:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3305:     return 
1.441     albertel 3306:         '<a href="/adm/email?compose=individual&amp;'.
                   3307:         'recname='.$username.'&amp;recdom='.$domain.
                   3308: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3309:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3310: }
1.802     bisitz   3311: 
1.74      www      3312: # --------------------------------------------------------------- Notes Wrapper
                   3313: 
                   3314: sub noteswrapper {
                   3315:     my ($link,$un,$do)=@_;
                   3316:     return 
1.896     amueller 3317: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3318: }
1.802     bisitz   3319: 
1.62      www      3320: # ------------------------------------------------------------- Aboutme Wrapper
                   3321: 
                   3322: sub aboutmewrapper {
1.1070    raeburn  3323:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3324:     if (!defined($username)  && !defined($domain)) {
                   3325:         return;
                   3326:     }
1.892     amueller 3327:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme?forcestudent=1"'.
1.1070    raeburn  3328: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3329: }
                   3330: 
                   3331: # ------------------------------------------------------------ Syllabus Wrapper
                   3332: 
                   3333: sub syllabuswrapper {
1.707     bisitz   3334:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3335:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3336: }
1.14      harris41 3337: 
1.802     bisitz   3338: # -----------------------------------------------------------------------------
                   3339: 
1.208     matthew  3340: sub track_student_link {
1.887     raeburn  3341:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3342:     my $link ="/adm/trackstudent?";
1.208     matthew  3343:     my $title = 'View recent activity';
                   3344:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3345:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3346:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3347:         $title .= ' of this student';
1.268     albertel 3348:     } 
1.208     matthew  3349:     if (defined($target) && $target !~ /^\s*$/) {
                   3350:         $target = qq{target="$target"};
                   3351:     } else {
                   3352:         $target = '';
                   3353:     }
1.268     albertel 3354:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3355:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3356:     $title = &mt($title);
                   3357:     $linktext = &mt($linktext);
1.448     albertel 3358:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3359: 	&help_open_topic('View_recent_activity');
1.208     matthew  3360: }
                   3361: 
1.781     raeburn  3362: sub slot_reservations_link {
                   3363:     my ($linktext,$sname,$sdom,$target) = @_;
                   3364:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3365:     my $title = 'View slot reservation history';
                   3366:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3367:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3368:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3369:         $title .= ' of this student';
                   3370:     }
                   3371:     if (defined($target) && $target !~ /^\s*$/) {
                   3372:         $target = qq{target="$target"};
                   3373:     } else {
                   3374:         $target = '';
                   3375:     }
                   3376:     $title = &mt($title);
                   3377:     $linktext = &mt($linktext);
                   3378:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3379: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3380: 
                   3381: }
                   3382: 
1.508     www      3383: # ===================================================== Display a student photo
                   3384: 
                   3385: 
1.509     albertel 3386: sub student_image_tag {
1.508     www      3387:     my ($domain,$user)=@_;
                   3388:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3389:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3390: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3391:     } else {
                   3392: 	return '';
                   3393:     }
                   3394: }
                   3395: 
1.112     bowersj2 3396: =pod
                   3397: 
                   3398: =back
                   3399: 
                   3400: =head1 Access .tab File Data
                   3401: 
                   3402: =over 4
                   3403: 
1.648     raeburn  3404: =item * &languageids() 
1.112     bowersj2 3405: 
                   3406: returns list of all language ids
                   3407: 
                   3408: =cut
                   3409: 
1.14      harris41 3410: sub languageids {
1.16      harris41 3411:     return sort(keys(%language));
1.14      harris41 3412: }
                   3413: 
1.112     bowersj2 3414: =pod
                   3415: 
1.648     raeburn  3416: =item * &languagedescription() 
1.112     bowersj2 3417: 
                   3418: returns description of a specified language id
                   3419: 
                   3420: =cut
                   3421: 
1.14      harris41 3422: sub languagedescription {
1.125     www      3423:     my $code=shift;
                   3424:     return  ($supported_language{$code}?'* ':'').
                   3425:             $language{$code}.
1.126     www      3426: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3427: }
                   3428: 
1.1048    foxr     3429: =pod
                   3430: 
                   3431: =item * &plainlanguagedescription
                   3432: 
                   3433: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3434: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3435: 
                   3436: =cut
                   3437: 
1.145     www      3438: sub plainlanguagedescription {
                   3439:     my $code=shift;
                   3440:     return $language{$code};
                   3441: }
                   3442: 
1.1048    foxr     3443: =pod
                   3444: 
                   3445: =item * &supportedlanguagecode
                   3446: 
                   3447: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3448: code.
                   3449: 
                   3450: =cut
                   3451: 
1.145     www      3452: sub supportedlanguagecode {
                   3453:     my $code=shift;
                   3454:     return $supported_language{$code};
1.97      www      3455: }
                   3456: 
1.112     bowersj2 3457: =pod
                   3458: 
1.1048    foxr     3459: =item * &latexlanguage()
                   3460: 
                   3461: Given a language key code returns the correspondnig language to use
                   3462: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3463: is no supported hyphenation for the language code.
                   3464: 
                   3465: =cut
                   3466: 
                   3467: sub latexlanguage {
                   3468:     my $code = shift;
                   3469:     return $latex_language{$code};
                   3470: }
                   3471: 
                   3472: =pod
                   3473: 
                   3474: =item * &latexhyphenation()
                   3475: 
                   3476: Same as above but what's supplied is the language as it might be stored
                   3477: in the metadata.
                   3478: 
                   3479: =cut
                   3480: 
                   3481: sub latexhyphenation {
                   3482:     my $key = shift;
                   3483:     return $latex_language_bykey{$key};
                   3484: }
                   3485: 
                   3486: =pod
                   3487: 
1.648     raeburn  3488: =item * &copyrightids() 
1.112     bowersj2 3489: 
                   3490: returns list of all copyrights
                   3491: 
                   3492: =cut
                   3493: 
                   3494: sub copyrightids {
                   3495:     return sort(keys(%cprtag));
                   3496: }
                   3497: 
                   3498: =pod
                   3499: 
1.648     raeburn  3500: =item * &copyrightdescription() 
1.112     bowersj2 3501: 
                   3502: returns description of a specified copyright id
                   3503: 
                   3504: =cut
                   3505: 
                   3506: sub copyrightdescription {
1.166     www      3507:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3508: }
1.197     matthew  3509: 
                   3510: =pod
                   3511: 
1.648     raeburn  3512: =item * &source_copyrightids() 
1.192     taceyjo1 3513: 
                   3514: returns list of all source copyrights
                   3515: 
                   3516: =cut
                   3517: 
                   3518: sub source_copyrightids {
                   3519:     return sort(keys(%scprtag));
                   3520: }
                   3521: 
                   3522: =pod
                   3523: 
1.648     raeburn  3524: =item * &source_copyrightdescription() 
1.192     taceyjo1 3525: 
                   3526: returns description of a specified source copyright id
                   3527: 
                   3528: =cut
                   3529: 
                   3530: sub source_copyrightdescription {
                   3531:     return &mt($scprtag{shift(@_)});
                   3532: }
1.112     bowersj2 3533: 
                   3534: =pod
                   3535: 
1.648     raeburn  3536: =item * &filecategories() 
1.112     bowersj2 3537: 
                   3538: returns list of all file categories
                   3539: 
                   3540: =cut
                   3541: 
                   3542: sub filecategories {
                   3543:     return sort(keys(%category_extensions));
                   3544: }
                   3545: 
                   3546: =pod
                   3547: 
1.648     raeburn  3548: =item * &filecategorytypes() 
1.112     bowersj2 3549: 
                   3550: returns list of file types belonging to a given file
                   3551: category
                   3552: 
                   3553: =cut
                   3554: 
                   3555: sub filecategorytypes {
1.356     albertel 3556:     my ($cat) = @_;
                   3557:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3558: }
                   3559: 
                   3560: =pod
                   3561: 
1.648     raeburn  3562: =item * &fileembstyle() 
1.112     bowersj2 3563: 
                   3564: returns embedding style for a specified file type
                   3565: 
                   3566: =cut
                   3567: 
                   3568: sub fileembstyle {
                   3569:     return $fe{lc(shift(@_))};
1.169     www      3570: }
                   3571: 
1.351     www      3572: sub filemimetype {
                   3573:     return $fm{lc(shift(@_))};
                   3574: }
                   3575: 
1.169     www      3576: 
                   3577: sub filecategoryselect {
                   3578:     my ($name,$value)=@_;
1.189     matthew  3579:     return &select_form($value,$name,
1.970     raeburn  3580:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3581: }
                   3582: 
                   3583: =pod
                   3584: 
1.648     raeburn  3585: =item * &filedescription() 
1.112     bowersj2 3586: 
                   3587: returns description for a specified file type
                   3588: 
                   3589: =cut
                   3590: 
                   3591: sub filedescription {
1.188     matthew  3592:     my $file_description = $fd{lc(shift())};
                   3593:     $file_description =~ s:([\[\]]):~$1:g;
                   3594:     return &mt($file_description);
1.112     bowersj2 3595: }
                   3596: 
                   3597: =pod
                   3598: 
1.648     raeburn  3599: =item * &filedescriptionex() 
1.112     bowersj2 3600: 
                   3601: returns description for a specified file type with
                   3602: extra formatting
                   3603: 
                   3604: =cut
                   3605: 
                   3606: sub filedescriptionex {
                   3607:     my $ex=shift;
1.188     matthew  3608:     my $file_description = $fd{lc($ex)};
                   3609:     $file_description =~ s:([\[\]]):~$1:g;
                   3610:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3611: }
                   3612: 
                   3613: # End of .tab access
                   3614: =pod
                   3615: 
                   3616: =back
                   3617: 
                   3618: =cut
                   3619: 
                   3620: # ------------------------------------------------------------------ File Types
                   3621: sub fileextensions {
                   3622:     return sort(keys(%fe));
                   3623: }
                   3624: 
1.97      www      3625: # ----------------------------------------------------------- Display Languages
                   3626: # returns a hash with all desired display languages
                   3627: #
                   3628: 
                   3629: sub display_languages {
                   3630:     my %languages=();
1.695     raeburn  3631:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3632: 	$languages{$lang}=1;
1.97      www      3633:     }
                   3634:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3635:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3636: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3637: 	    $languages{$lang}=1;
1.97      www      3638:         }
                   3639:     }
                   3640:     return %languages;
1.14      harris41 3641: }
                   3642: 
1.582     albertel 3643: sub languages {
                   3644:     my ($possible_langs) = @_;
1.695     raeburn  3645:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3646:     if (!ref($possible_langs)) {
                   3647: 	if( wantarray ) {
                   3648: 	    return @preferred_langs;
                   3649: 	} else {
                   3650: 	    return $preferred_langs[0];
                   3651: 	}
                   3652:     }
                   3653:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3654:     my @preferred_possibilities;
                   3655:     foreach my $preferred_lang (@preferred_langs) {
                   3656: 	if (exists($possibilities{$preferred_lang})) {
                   3657: 	    push(@preferred_possibilities, $preferred_lang);
                   3658: 	}
                   3659:     }
                   3660:     if( wantarray ) {
                   3661: 	return @preferred_possibilities;
                   3662:     }
                   3663:     return $preferred_possibilities[0];
                   3664: }
                   3665: 
1.742     raeburn  3666: sub user_lang {
                   3667:     my ($touname,$toudom,$fromcid) = @_;
                   3668:     my @userlangs;
                   3669:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3670:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3671:                     $env{'course.'.$fromcid.'.languages'}));
                   3672:     } else {
                   3673:         my %langhash = &getlangs($touname,$toudom);
                   3674:         if ($langhash{'languages'} ne '') {
                   3675:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3676:         } else {
                   3677:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3678:             if ($domdefs{'lang_def'} ne '') {
                   3679:                 @userlangs = ($domdefs{'lang_def'});
                   3680:             }
                   3681:         }
                   3682:     }
                   3683:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3684:     my $user_lh = Apache::localize->get_handle(@languages);
                   3685:     return $user_lh;
                   3686: }
                   3687: 
                   3688: 
1.112     bowersj2 3689: ###############################################################
                   3690: ##               Student Answer Attempts                     ##
                   3691: ###############################################################
                   3692: 
                   3693: =pod
                   3694: 
                   3695: =head1 Alternate Problem Views
                   3696: 
                   3697: =over 4
                   3698: 
1.648     raeburn  3699: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.112     bowersj2 3700:     $getattempt, $regexp, $gradesub)
                   3701: 
                   3702: Return string with previous attempt on problem. Arguments:
                   3703: 
                   3704: =over 4
                   3705: 
                   3706: =item * $symb: Problem, including path
                   3707: 
                   3708: =item * $username: username of the desired student
                   3709: 
                   3710: =item * $domain: domain of the desired student
1.14      harris41 3711: 
1.112     bowersj2 3712: =item * $course: Course ID
1.14      harris41 3713: 
1.112     bowersj2 3714: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3715:     something
1.14      harris41 3716: 
1.112     bowersj2 3717: =item * $regexp: if string matches this regexp, the string will be
                   3718:     sent to $gradesub
1.14      harris41 3719: 
1.112     bowersj2 3720: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3721: 
1.112     bowersj2 3722: =back
1.14      harris41 3723: 
1.112     bowersj2 3724: The output string is a table containing all desired attempts, if any.
1.16      harris41 3725: 
1.112     bowersj2 3726: =cut
1.1       albertel 3727: 
                   3728: sub get_previous_attempt {
1.43      ng       3729:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub)=@_;
1.1       albertel 3730:   my $prevattempts='';
1.43      ng       3731:   no strict 'refs';
1.1       albertel 3732:   if ($symb) {
1.3       albertel 3733:     my (%returnhash)=
                   3734:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3735:     if ($returnhash{'version'}) {
                   3736:       my %lasthash=();
                   3737:       my $version;
                   3738:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.356     albertel 3739:         foreach my $key (sort(split(/\:/,$returnhash{$version.':keys'}))) {
                   3740: 	  $lasthash{$key}=$returnhash{$version.':'.$key};
1.19      harris41 3741:         }
1.1       albertel 3742:       }
1.596     albertel 3743:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3744:       $prevattempts.='<th>'.&mt('History').'</th>';
1.978     raeburn  3745:       my (%typeparts,%lasthidden);
1.945     raeburn  3746:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3747:       foreach my $key (sort(keys(%lasthash))) {
                   3748: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3749: 	if ($#parts > 0) {
1.31      albertel 3750: 	  my $data=$parts[-1];
1.989     raeburn  3751:           next if ($data eq 'foilorder');
1.31      albertel 3752: 	  pop(@parts);
1.1010    www      3753:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3754:           if ($data eq 'type') {
                   3755:               unless ($showsurv) {
                   3756:                   my $id = join(',',@parts);
                   3757:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3758:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3759:                       $lasthidden{$ign.'.'.$id} = 1;
                   3760:                   }
1.945     raeburn  3761:               }
1.1010    www      3762:           } 
1.31      albertel 3763: 	} else {
1.41      ng       3764: 	  if ($#parts == 0) {
                   3765: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3766: 	  } else {
                   3767: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3768: 	  }
1.31      albertel 3769: 	}
1.16      harris41 3770:       }
1.596     albertel 3771:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3772:       if ($getattempt eq '') {
                   3773: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.945     raeburn  3774:             my @hidden;
                   3775:             if (%typeparts) {
                   3776:                 foreach my $id (keys(%typeparts)) {
                   3777:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
                   3778:                         push(@hidden,$id);
                   3779:                     }
                   3780:                 }
                   3781:             }
                   3782:             $prevattempts.=&start_data_table_row().
                   3783:                            '<td>'.&mt('Transaction [_1]',$version).'</td>';
                   3784:             if (@hidden) {
                   3785:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3786:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3787:                     my $hide;
                   3788:                     foreach my $id (@hidden) {
                   3789:                         if ($key =~ /^\Q$id\E/) {
                   3790:                             $hide = 1;
                   3791:                             last;
                   3792:                         }
                   3793:                     }
                   3794:                     if ($hide) {
                   3795:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3796:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3797:                             my $value = &format_previous_attempt_value($key,
                   3798:                                              $returnhash{$version.':'.$key});
                   3799:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3800:                         } else {
                   3801:                             $prevattempts.='<td>&nbsp;</td>';
                   3802:                         }
                   3803:                     } else {
                   3804:                         if ($key =~ /\./) {
                   3805:                             my $value = &format_previous_attempt_value($key,
                   3806:                                               $returnhash{$version.':'.$key});
                   3807:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3808:                         } else {
                   3809:                             $prevattempts.='<td>&nbsp;</td>';
                   3810:                         }
                   3811:                     }
                   3812:                 }
                   3813:             } else {
                   3814: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3815:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3816: 		    my $value = &format_previous_attempt_value($key,
                   3817: 			            $returnhash{$version.':'.$key});
                   3818: 		    $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3819: 	        }
                   3820:             }
                   3821: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3822: 	 }
1.1       albertel 3823:       }
1.945     raeburn  3824:       my @currhidden = keys(%lasthidden);
1.596     albertel 3825:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3826:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3827:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3828:           if (%typeparts) {
                   3829:               my $hidden;
                   3830:               foreach my $id (@currhidden) {
                   3831:                   if ($key =~ /^\Q$id\E/) {
                   3832:                       $hidden = 1;
                   3833:                       last;
                   3834:                   }
                   3835:               }
                   3836:               if ($hidden) {
                   3837:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3838:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3839:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3840:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3841:                           $value = &$gradesub($value);
                   3842:                       }
                   3843:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3844:                   } else {
                   3845:                       $prevattempts.='<td>&nbsp;</td>';
                   3846:                   }
                   3847:               } else {
                   3848:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3849:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3850:                       $value = &$gradesub($value);
                   3851:                   }
                   3852:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3853:               }
                   3854:           } else {
                   3855: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3856: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3857:                   $value = &$gradesub($value);
                   3858:               }
                   3859: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3860:           }
1.16      harris41 3861:       }
1.596     albertel 3862:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3863:     } else {
1.596     albertel 3864:       $prevattempts=
                   3865: 	  &start_data_table().&start_data_table_row().
                   3866: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3867: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3868:     }
                   3869:   } else {
1.596     albertel 3870:     $prevattempts=
                   3871: 	  &start_data_table().&start_data_table_row().
                   3872: 	  '<td>'.&mt('No data.').'</td>'.
                   3873: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3874:   }
1.10      albertel 3875: }
                   3876: 
1.581     albertel 3877: sub format_previous_attempt_value {
                   3878:     my ($key,$value) = @_;
1.1011    www      3879:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3880: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3881:     } elsif (ref($value) eq 'ARRAY') {
                   3882: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3883:     } elsif ($key =~ /answerstring$/) {
                   3884:         my %answers = &Apache::lonnet::str2hash($value);
                   3885:         my @anskeys = sort(keys(%answers));
                   3886:         if (@anskeys == 1) {
                   3887:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3888:             if ($answer =~ m{\0}) {
                   3889:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3890:             }
                   3891:             my $tag_internal_answer_name = 'INTERNAL';
                   3892:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3893:                 $value = $answer; 
                   3894:             } else {
                   3895:                 $value = $anskeys[0].'='.$answer;
                   3896:             }
                   3897:         } else {
                   3898:             foreach my $ans (@anskeys) {
                   3899:                 my $answer = $answers{$ans};
1.1001    raeburn  3900:                 if ($answer =~ m{\0}) {
                   3901:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3902:                 }
                   3903:                 $value .=  $ans.'='.$answer.'<br />';;
                   3904:             } 
                   3905:         }
1.581     albertel 3906:     } else {
                   3907: 	$value = &unescape($value);
                   3908:     }
                   3909:     return $value;
                   3910: }
                   3911: 
                   3912: 
1.107     albertel 3913: sub relative_to_absolute {
                   3914:     my ($url,$output)=@_;
                   3915:     my $parser=HTML::TokeParser->new(\$output);
                   3916:     my $token;
                   3917:     my $thisdir=$url;
                   3918:     my @rlinks=();
                   3919:     while ($token=$parser->get_token) {
                   3920: 	if ($token->[0] eq 'S') {
                   3921: 	    if ($token->[1] eq 'a') {
                   3922: 		if ($token->[2]->{'href'}) {
                   3923: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3924: 		}
                   3925: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3926: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3927: 	    } elsif ($token->[1] eq 'base') {
                   3928: 		$thisdir=$token->[2]->{'href'};
                   3929: 	    }
                   3930: 	}
                   3931:     }
                   3932:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3933:     foreach my $link (@rlinks) {
1.726     raeburn  3934: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3935: 		($link=~/^\//) ||
                   3936: 		($link=~/^javascript:/i) ||
                   3937: 		($link=~/^mailto:/i) ||
                   3938: 		($link=~/^\#/)) {
                   3939: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   3940: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 3941: 	}
                   3942:     }
                   3943: # -------------------------------------------------- Deal with Applet codebases
                   3944:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   3945:     return $output;
                   3946: }
                   3947: 
1.112     bowersj2 3948: =pod
                   3949: 
1.648     raeburn  3950: =item * &get_student_view()
1.112     bowersj2 3951: 
                   3952: show a snapshot of what student was looking at
                   3953: 
                   3954: =cut
                   3955: 
1.10      albertel 3956: sub get_student_view {
1.186     albertel 3957:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      3958:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 3959:   my (%form);
1.10      albertel 3960:   my @elements=('symb','courseid','domain','username');
                   3961:   foreach my $element (@elements) {
1.186     albertel 3962:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 3963:   }
1.186     albertel 3964:   if (defined($moreenv)) {
                   3965:       %form=(%form,%{$moreenv});
                   3966:   }
1.236     albertel 3967:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 3968:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      3969:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 3970:   $userview=~s/\<body[^\>]*\>//gi;
                   3971:   $userview=~s/\<\/body\>//gi;
                   3972:   $userview=~s/\<html\>//gi;
                   3973:   $userview=~s/\<\/html\>//gi;
                   3974:   $userview=~s/\<head\>//gi;
                   3975:   $userview=~s/\<\/head\>//gi;
                   3976:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 3977:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      3978:   if (wantarray) {
                   3979:      return ($userview,$response);
                   3980:   } else {
                   3981:      return $userview;
                   3982:   }
                   3983: }
                   3984: 
                   3985: sub get_student_view_with_retries {
                   3986:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   3987: 
                   3988:     my $ok = 0;                 # True if we got a good response.
                   3989:     my $content;
                   3990:     my $response;
                   3991: 
                   3992:     # Try to get the student_view done. within the retries count:
                   3993:     
                   3994:     do {
                   3995:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   3996:          $ok      = $response->is_success;
                   3997:          if (!$ok) {
                   3998:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   3999:          }
                   4000:          $retries--;
                   4001:     } while (!$ok && ($retries > 0));
                   4002:     
                   4003:     if (!$ok) {
                   4004:        $content = '';          # On error return an empty content.
                   4005:     }
1.651     www      4006:     if (wantarray) {
                   4007:        return ($content, $response);
                   4008:     } else {
                   4009:        return $content;
                   4010:     }
1.11      albertel 4011: }
                   4012: 
1.112     bowersj2 4013: =pod
                   4014: 
1.648     raeburn  4015: =item * &get_student_answers() 
1.112     bowersj2 4016: 
                   4017: show a snapshot of how student was answering problem
                   4018: 
                   4019: =cut
                   4020: 
1.11      albertel 4021: sub get_student_answers {
1.100     sakharuk 4022:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4023:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4024:   my (%moreenv);
1.11      albertel 4025:   my @elements=('symb','courseid','domain','username');
                   4026:   foreach my $element (@elements) {
1.186     albertel 4027:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4028:   }
1.186     albertel 4029:   $moreenv{'grade_target'}='answer';
                   4030:   %moreenv=(%form,%moreenv);
1.497     raeburn  4031:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4032:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4033:   return $userview;
1.1       albertel 4034: }
1.116     albertel 4035: 
                   4036: =pod
                   4037: 
                   4038: =item * &submlink()
                   4039: 
1.242     albertel 4040: Inputs: $text $uname $udom $symb $target
1.116     albertel 4041: 
                   4042: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4043: 
                   4044: =cut
                   4045: 
                   4046: ###############################################
                   4047: sub submlink {
1.242     albertel 4048:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4049:     if (!($uname && $udom)) {
                   4050: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4051: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4052: 	if (!$symb) { $symb=$cursymb; }
                   4053:     }
1.254     matthew  4054:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4055:     $symb=&escape($symb);
1.960     bisitz   4056:     if ($target) { $target=" target=\"$target\""; }
                   4057:     return
                   4058:         '<a href="/adm/grades?command=submission'.
                   4059:         '&amp;symb='.$symb.
                   4060:         '&amp;student='.$uname.
                   4061:         '&amp;userdom='.$udom.'"'.
                   4062:         $target.'>'.$text.'</a>';
1.242     albertel 4063: }
                   4064: ##############################################
                   4065: 
                   4066: =pod
                   4067: 
                   4068: =item * &pgrdlink()
                   4069: 
                   4070: Inputs: $text $uname $udom $symb $target
                   4071: 
                   4072: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4073: 
                   4074: =cut
                   4075: 
                   4076: ###############################################
                   4077: sub pgrdlink {
                   4078:     my $link=&submlink(@_);
                   4079:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4080:     return $link;
                   4081: }
                   4082: ##############################################
                   4083: 
                   4084: =pod
                   4085: 
                   4086: =item * &pprmlink()
                   4087: 
                   4088: Inputs: $text $uname $udom $symb $target
                   4089: 
                   4090: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4091: student and a specific resource
1.242     albertel 4092: 
                   4093: =cut
                   4094: 
                   4095: ###############################################
                   4096: sub pprmlink {
                   4097:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4098:     if (!($uname && $udom)) {
                   4099: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4100: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4101: 	if (!$symb) { $symb=$cursymb; }
                   4102:     }
1.254     matthew  4103:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4104:     $symb=&escape($symb);
1.242     albertel 4105:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4106:     return '<a href="/adm/parmset?command=set&amp;'.
                   4107: 	'symb='.$symb.'&amp;uname='.$uname.
                   4108: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4109: }
                   4110: ##############################################
1.37      matthew  4111: 
1.112     bowersj2 4112: =pod
                   4113: 
                   4114: =back
                   4115: 
                   4116: =cut
                   4117: 
1.37      matthew  4118: ###############################################
1.51      www      4119: 
                   4120: 
                   4121: sub timehash {
1.687     raeburn  4122:     my ($thistime) = @_;
                   4123:     my $timezone = &Apache::lonlocal::gettimezone();
                   4124:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4125:                      ->set_time_zone($timezone);
                   4126:     my $wday = $dt->day_of_week();
                   4127:     if ($wday == 7) { $wday = 0; }
                   4128:     return ( 'second' => $dt->second(),
                   4129:              'minute' => $dt->minute(),
                   4130:              'hour'   => $dt->hour(),
                   4131:              'day'     => $dt->day_of_month(),
                   4132:              'month'   => $dt->month(),
                   4133:              'year'    => $dt->year(),
                   4134:              'weekday' => $wday,
                   4135:              'dayyear' => $dt->day_of_year(),
                   4136:              'dlsav'   => $dt->is_dst() );
1.51      www      4137: }
                   4138: 
1.370     www      4139: sub utc_string {
                   4140:     my ($date)=@_;
1.371     www      4141:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4142: }
                   4143: 
1.51      www      4144: sub maketime {
                   4145:     my %th=@_;
1.687     raeburn  4146:     my ($epoch_time,$timezone,$dt);
                   4147:     $timezone = &Apache::lonlocal::gettimezone();
                   4148:     eval {
                   4149:         $dt = DateTime->new( year   => $th{'year'},
                   4150:                              month  => $th{'month'},
                   4151:                              day    => $th{'day'},
                   4152:                              hour   => $th{'hour'},
                   4153:                              minute => $th{'minute'},
                   4154:                              second => $th{'second'},
                   4155:                              time_zone => $timezone,
                   4156:                          );
                   4157:     };
                   4158:     if (!$@) {
                   4159:         $epoch_time = $dt->epoch;
                   4160:         if ($epoch_time) {
                   4161:             return $epoch_time;
                   4162:         }
                   4163:     }
1.51      www      4164:     return POSIX::mktime(
                   4165:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4166:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4167: }
                   4168: 
                   4169: #########################################
1.51      www      4170: 
                   4171: sub findallcourses {
1.482     raeburn  4172:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4173:     my %roles;
                   4174:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4175:     my %courses;
1.51      www      4176:     my $now=time;
1.482     raeburn  4177:     if (!defined($uname)) {
                   4178:         $uname = $env{'user.name'};
                   4179:     }
                   4180:     if (!defined($udom)) {
                   4181:         $udom = $env{'user.domain'};
                   4182:     }
                   4183:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4184:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4185:         if (!%roles) {
                   4186:             %roles = (
                   4187:                        cc => 1,
1.907     raeburn  4188:                        co => 1,
1.482     raeburn  4189:                        in => 1,
                   4190:                        ep => 1,
                   4191:                        ta => 1,
                   4192:                        cr => 1,
                   4193:                        st => 1,
                   4194:              );
                   4195:         }
                   4196:         foreach my $entry (keys(%roleshash)) {
                   4197:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4198:             if ($trole =~ /^cr/) { 
                   4199:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4200:             } else {
                   4201:                 next if (!exists($roles{$trole}));
                   4202:             }
                   4203:             if ($tend) {
                   4204:                 next if ($tend < $now);
                   4205:             }
                   4206:             if ($tstart) {
                   4207:                 next if ($tstart > $now);
                   4208:             }
1.1058    raeburn  4209:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4210:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4211:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4212:             if ($secpart eq '') {
                   4213:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4214:                 $sec = 'none';
1.1058    raeburn  4215:                 $value .= $cnum.'/';
1.482     raeburn  4216:             } else {
                   4217:                 $cnum = $cnumpart;
                   4218:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4219:                 $value .= $cnum.'/'.$sec;
                   4220:             }
                   4221:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4222:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4223:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4224:                 }
                   4225:             } else {
                   4226:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4227:             }
1.482     raeburn  4228:         }
                   4229:     } else {
                   4230:         foreach my $key (keys(%env)) {
1.483     albertel 4231: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4232:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4233: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4234: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4235: 	        next if (%roles && !exists($roles{$role}));
                   4236: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4237:                 my $active=1;
                   4238:                 if ($starttime) {
                   4239: 		    if ($now<$starttime) { $active=0; }
                   4240:                 }
                   4241:                 if ($endtime) {
                   4242:                     if ($now>$endtime) { $active=0; }
                   4243:                 }
                   4244:                 if ($active) {
1.1058    raeburn  4245:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4246:                     if ($sec eq '') {
                   4247:                         $sec = 'none';
1.1058    raeburn  4248:                     } else {
                   4249:                         $value .= $sec;
                   4250:                     }
                   4251:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4252:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4253:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4254:                         }
                   4255:                     } else {
                   4256:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4257:                     }
1.474     raeburn  4258:                 }
                   4259:             }
1.51      www      4260:         }
                   4261:     }
1.474     raeburn  4262:     return %courses;
1.51      www      4263: }
1.37      matthew  4264: 
1.54      www      4265: ###############################################
1.474     raeburn  4266: 
                   4267: sub blockcheck {
1.1062    raeburn  4268:     my ($setters,$activity,$uname,$udom,$url) = @_;
1.490     raeburn  4269: 
                   4270:     if (!defined($udom)) {
                   4271:         $udom = $env{'user.domain'};
                   4272:     }
                   4273:     if (!defined($uname)) {
                   4274:         $uname = $env{'user.name'};
                   4275:     }
                   4276: 
                   4277:     # If uname and udom are for a course, check for blocks in the course.
                   4278: 
                   4279:     if (&Apache::lonnet::is_course($udom,$uname)) {
1.1062    raeburn  4280:         my ($startblock,$endblock,$triggerblock) = 
                   4281:             &get_blocks($setters,$activity,$udom,$uname,$url);
                   4282:         return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4283:     }
1.474     raeburn  4284: 
1.502     raeburn  4285:     my $startblock = 0;
                   4286:     my $endblock = 0;
1.1062    raeburn  4287:     my $triggerblock = '';
1.482     raeburn  4288:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4289: 
1.490     raeburn  4290:     # If uname is for a user, and activity is course-specific, i.e.,
                   4291:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4292: 
1.490     raeburn  4293:     if (($activity eq 'boards' || $activity eq 'chat' ||
                   4294:          $activity eq 'groups') && ($env{'request.course.id'})) {
                   4295:         foreach my $key (keys(%live_courses)) {
                   4296:             if ($key ne $env{'request.course.id'}) {
                   4297:                 delete($live_courses{$key});
                   4298:             }
                   4299:         }
                   4300:     }
                   4301: 
                   4302:     my $otheruser = 0;
                   4303:     my %own_courses;
                   4304:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4305:         # Resource belongs to user other than current user.
                   4306:         $otheruser = 1;
                   4307:         # Gather courses for current user
                   4308:         %own_courses = 
                   4309:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4310:     }
                   4311: 
                   4312:     # Gather active course roles - course coordinator, instructor, 
                   4313:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4314: 
                   4315:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4316:         my ($cdom,$cnum);
                   4317:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4318:             $cdom = $env{'course.'.$course.'.domain'};
                   4319:             $cnum = $env{'course.'.$course.'.num'};
                   4320:         } else {
1.490     raeburn  4321:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4322:         }
                   4323:         my $no_ownblock = 0;
                   4324:         my $no_userblock = 0;
1.533     raeburn  4325:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4326:             # Check if current user has 'evb' priv for this
                   4327:             if (defined($own_courses{$course})) {
                   4328:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4329:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4330:                     if ($sec ne 'none') {
                   4331:                         $checkrole .= '/'.$sec;
                   4332:                     }
                   4333:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4334:                         $no_ownblock = 1;
                   4335:                         last;
                   4336:                     }
                   4337:                 }
                   4338:             }
                   4339:             # if they have 'evb' priv and are currently not playing student
                   4340:             next if (($no_ownblock) &&
                   4341:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4342:         }
1.474     raeburn  4343:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4344:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4345:             if ($sec ne 'none') {
1.482     raeburn  4346:                 $checkrole .= '/'.$sec;
1.474     raeburn  4347:             }
1.490     raeburn  4348:             if ($otheruser) {
                   4349:                 # Resource belongs to user other than current user.
                   4350:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4351:                 my (%allroles,%userroles);
                   4352:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4353:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4354:                         my ($trole,$tdom,$tnum,$tsec);
                   4355:                         if ($entry =~ /^cr/) {
                   4356:                             ($trole,$tdom,$tnum,$tsec) = 
                   4357:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4358:                         } else {
                   4359:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4360:                         }
                   4361:                         my ($spec,$area,$trest);
                   4362:                         $area = '/'.$tdom.'/'.$tnum;
                   4363:                         $trest = $tnum;
                   4364:                         if ($tsec ne '') {
                   4365:                             $area .= '/'.$tsec;
                   4366:                             $trest .= '/'.$tsec;
                   4367:                         }
                   4368:                         $spec = $trole.'.'.$area;
                   4369:                         if ($trole =~ /^cr/) {
                   4370:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4371:                                                               $tdom,$spec,$trest,$area);
                   4372:                         } else {
                   4373:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4374:                                                                 $tdom,$spec,$trest,$area);
                   4375:                         }
                   4376:                     }
                   4377:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4378:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4379:                         if ($1) {
                   4380:                             $no_userblock = 1;
                   4381:                             last;
                   4382:                         }
1.486     raeburn  4383:                     }
                   4384:                 }
1.490     raeburn  4385:             } else {
                   4386:                 # Resource belongs to current user
                   4387:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4388:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4389:                     $no_ownblock = 1;
                   4390:                     last;
                   4391:                 }
1.474     raeburn  4392:             }
                   4393:         }
                   4394:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4395:         next if (($no_ownblock) &&
1.491     albertel 4396:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4397:         next if ($no_userblock);
1.474     raeburn  4398: 
1.866     kalberla 4399:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4400:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4401:         
1.1062    raeburn  4402:         my ($start,$end,$trigger) = 
                   4403:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4404:         if (($start != 0) && 
                   4405:             (($startblock == 0) || ($startblock > $start))) {
                   4406:             $startblock = $start;
1.1062    raeburn  4407:             if ($trigger ne '') {
                   4408:                 $triggerblock = $trigger;
                   4409:             }
1.502     raeburn  4410:         }
                   4411:         if (($end != 0)  &&
                   4412:             (($endblock == 0) || ($endblock < $end))) {
                   4413:             $endblock = $end;
1.1062    raeburn  4414:             if ($trigger ne '') {
                   4415:                 $triggerblock = $trigger;
                   4416:             }
1.502     raeburn  4417:         }
1.490     raeburn  4418:     }
1.1062    raeburn  4419:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4420: }
                   4421: 
                   4422: sub get_blocks {
1.1062    raeburn  4423:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4424:     my $startblock = 0;
                   4425:     my $endblock = 0;
1.1062    raeburn  4426:     my $triggerblock = '';
1.490     raeburn  4427:     my $course = $cdom.'_'.$cnum;
                   4428:     $setters->{$course} = {};
                   4429:     $setters->{$course}{'staff'} = [];
                   4430:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4431:     $setters->{$course}{'triggers'} = [];
                   4432:     my (@blockers,%triggered);
                   4433:     my $now = time;
                   4434:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4435:     if ($activity eq 'docs') {
                   4436:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4437:         foreach my $block (@blockers) {
                   4438:             if ($block =~ /^firstaccess____(.+)$/) {
                   4439:                 my $item = $1;
                   4440:                 my $type = 'map';
                   4441:                 my $timersymb = $item;
                   4442:                 if ($item eq 'course') {
                   4443:                     $type = 'course';
                   4444:                 } elsif ($item =~ /___\d+___/) {
                   4445:                     $type = 'resource';
                   4446:                 } else {
                   4447:                     $timersymb = &Apache::lonnet::symbread($item);
                   4448:                 }
                   4449:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4450:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4451:                 $triggered{$block} = {
                   4452:                                        start => $start,
                   4453:                                        end   => $end,
                   4454:                                        type  => $type,
                   4455:                                      };
                   4456:             }
                   4457:         }
                   4458:     } else {
                   4459:         foreach my $block (keys(%commblocks)) {
                   4460:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4461:                 my ($start,$end) = ($1,$2);
                   4462:                 if ($start <= time && $end >= time) {
                   4463:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4464:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4465:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4466:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4467:                                     push(@blockers,$block);
                   4468:                                 }
                   4469:                             }
                   4470:                         }
                   4471:                     }
                   4472:                 }
                   4473:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4474:                 my $item = $1;
                   4475:                 my $timersymb = $item; 
                   4476:                 my $type = 'map';
                   4477:                 if ($item eq 'course') {
                   4478:                     $type = 'course';
                   4479:                 } elsif ($item =~ /___\d+___/) {
                   4480:                     $type = 'resource';
                   4481:                 } else {
                   4482:                     $timersymb = &Apache::lonnet::symbread($item);
                   4483:                 }
                   4484:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4485:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4486:                 if ($start && $end) {
                   4487:                     if (($start <= time) && ($end >= time)) {
                   4488:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4489:                             push(@blockers,$block);
                   4490:                             $triggered{$block} = {
                   4491:                                                    start => $start,
                   4492:                                                    end   => $end,
                   4493:                                                    type  => $type,
                   4494:                                                  };
                   4495:                         }
                   4496:                     }
1.490     raeburn  4497:                 }
1.1062    raeburn  4498:             }
                   4499:         }
                   4500:     }
                   4501:     foreach my $blocker (@blockers) {
                   4502:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4503:             &parse_block_record($commblocks{$blocker});
                   4504:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4505:         my ($start,$end,$triggertype);
                   4506:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4507:             ($start,$end) = ($1,$2);
                   4508:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4509:             $start = $triggered{$blocker}{'start'};
                   4510:             $end = $triggered{$blocker}{'end'};
                   4511:             $triggertype = $triggered{$blocker}{'type'};
                   4512:         }
                   4513:         if ($start) {
                   4514:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4515:             if ($triggertype) {
                   4516:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4517:             } else {
                   4518:                 push(@{$$setters{$course}{'triggers'}},0);
                   4519:             }
                   4520:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4521:                 $startblock = $start;
                   4522:                 if ($triggertype) {
                   4523:                     $triggerblock = $blocker;
1.474     raeburn  4524:                 }
                   4525:             }
1.1062    raeburn  4526:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4527:                $endblock = $end;
                   4528:                if ($triggertype) {
                   4529:                    $triggerblock = $blocker;
                   4530:                }
                   4531:             }
1.474     raeburn  4532:         }
                   4533:     }
1.1062    raeburn  4534:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4535: }
                   4536: 
                   4537: sub parse_block_record {
                   4538:     my ($record) = @_;
                   4539:     my ($setuname,$setudom,$title,$blocks);
                   4540:     if (ref($record) eq 'HASH') {
                   4541:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4542:         $title = &unescape($record->{'event'});
                   4543:         $blocks = $record->{'blocks'};
                   4544:     } else {
                   4545:         my @data = split(/:/,$record,3);
                   4546:         if (scalar(@data) eq 2) {
                   4547:             $title = $data[1];
                   4548:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4549:         } else {
                   4550:             ($setuname,$setudom,$title) = @data;
                   4551:         }
                   4552:         $blocks = { 'com' => 'on' };
                   4553:     }
                   4554:     return ($setuname,$setudom,$title,$blocks);
                   4555: }
                   4556: 
1.854     kalberla 4557: sub blocking_status {
1.1062    raeburn  4558:     my ($activity,$uname,$udom,$url) = @_;
1.1061    raeburn  4559:     my %setters;
1.890     droeschl 4560: 
1.1061    raeburn  4561: # check for active blocking
1.1062    raeburn  4562:     my ($startblock,$endblock,$triggerblock) = 
                   4563:         &blockcheck(\%setters,$activity,$uname,$udom,$url);
                   4564:     my $blocked = 0;
                   4565:     if ($startblock && $endblock) {
                   4566:         $blocked = 1;
                   4567:     }
1.890     droeschl 4568: 
1.1061    raeburn  4569: # caller just wants to know whether a block is active
                   4570:     if (!wantarray) { return $blocked; }
                   4571: 
                   4572: # build a link to a popup window containing the details
                   4573:     my $querystring  = "?activity=$activity";
                   4574: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4575:     if ($activity eq 'port') {
                   4576:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4577:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4578:     } elsif ($activity eq 'docs') {
                   4579:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4580:     }
1.1061    raeburn  4581: 
                   4582:     my $output .= <<'END_MYBLOCK';
                   4583: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4584:     var options = "width=" + w + ",height=" + h + ",";
                   4585:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4586:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4587:     var newWin = window.open(url, wdwName, options);
                   4588:     newWin.focus();
                   4589: }
1.890     droeschl 4590: END_MYBLOCK
1.854     kalberla 4591: 
1.1061    raeburn  4592:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4593:   
1.1061    raeburn  4594:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4595:     my $text = &mt('Communication Blocked');
                   4596:     if ($activity eq 'docs') {
                   4597:         $text = &mt('Content Access Blocked');
1.1063    raeburn  4598:     } elsif ($activity eq 'printout') {
                   4599:         $text = &mt('Printing Blocked');
1.1062    raeburn  4600:     }
1.1061    raeburn  4601:     $output .= <<"END_BLOCK";
1.867     kalberla 4602: <div class='LC_comblock'>
1.869     kalberla 4603:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4604:   title='$text'>
                   4605:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4606:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4607:   title='$text'>$text</a>
1.867     kalberla 4608: </div>
                   4609: 
                   4610: END_BLOCK
1.474     raeburn  4611: 
1.1061    raeburn  4612:     return ($blocked, $output);
1.854     kalberla 4613: }
1.490     raeburn  4614: 
1.60      matthew  4615: ###############################################
                   4616: 
1.682     raeburn  4617: sub check_ip_acc {
                   4618:     my ($acc)=@_;
                   4619:     &Apache::lonxml::debug("acc is $acc");
                   4620:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4621:         return 1;
                   4622:     }
                   4623:     my $allowed=0;
                   4624:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4625: 
                   4626:     my $name;
                   4627:     foreach my $pattern (split(',',$acc)) {
                   4628:         $pattern =~ s/^\s*//;
                   4629:         $pattern =~ s/\s*$//;
                   4630:         if ($pattern =~ /\*$/) {
                   4631:             #35.8.*
                   4632:             $pattern=~s/\*//;
                   4633:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4634:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4635:             #35.8.3.[34-56]
                   4636:             my $low=$2;
                   4637:             my $high=$3;
                   4638:             $pattern=$1;
                   4639:             if ($ip =~ /^\Q$pattern\E/) {
                   4640:                 my $last=(split(/\./,$ip))[3];
                   4641:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4642:             }
                   4643:         } elsif ($pattern =~ /^\*/) {
                   4644:             #*.msu.edu
                   4645:             $pattern=~s/\*//;
                   4646:             if (!defined($name)) {
                   4647:                 use Socket;
                   4648:                 my $netaddr=inet_aton($ip);
                   4649:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4650:             }
                   4651:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4652:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4653:             #127.0.0.1
                   4654:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4655:         } else {
                   4656:             #some.name.com
                   4657:             if (!defined($name)) {
                   4658:                 use Socket;
                   4659:                 my $netaddr=inet_aton($ip);
                   4660:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4661:             }
                   4662:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4663:         }
                   4664:         if ($allowed) { last; }
                   4665:     }
                   4666:     return $allowed;
                   4667: }
                   4668: 
                   4669: ###############################################
                   4670: 
1.60      matthew  4671: =pod
                   4672: 
1.112     bowersj2 4673: =head1 Domain Template Functions
                   4674: 
                   4675: =over 4
                   4676: 
                   4677: =item * &determinedomain()
1.60      matthew  4678: 
                   4679: Inputs: $domain (usually will be undef)
                   4680: 
1.63      www      4681: Returns: Determines which domain should be used for designs
1.60      matthew  4682: 
                   4683: =cut
1.54      www      4684: 
1.60      matthew  4685: ###############################################
1.63      www      4686: sub determinedomain {
                   4687:     my $domain=shift;
1.531     albertel 4688:     if (! $domain) {
1.60      matthew  4689:         # Determine domain if we have not been given one
1.893     raeburn  4690:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4691:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4692:         if ($env{'request.role.domain'}) { 
                   4693:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4694:         }
                   4695:     }
1.63      www      4696:     return $domain;
                   4697: }
                   4698: ###############################################
1.517     raeburn  4699: 
1.518     albertel 4700: sub devalidate_domconfig_cache {
                   4701:     my ($udom)=@_;
                   4702:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4703: }
                   4704: 
                   4705: # ---------------------- Get domain configuration for a domain
                   4706: sub get_domainconf {
                   4707:     my ($udom) = @_;
                   4708:     my $cachetime=1800;
                   4709:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4710:     if (defined($cached)) { return %{$result}; }
                   4711: 
                   4712:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4713: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4714:     my (%designhash,%legacy);
1.518     albertel 4715:     if (keys(%domconfig) > 0) {
                   4716:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4717:             if (keys(%{$domconfig{'login'}})) {
                   4718:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4719:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.946     raeburn  4720:                         if ($key eq 'loginvia') {
                   4721:                             if (ref($domconfig{'login'}{'loginvia'}) eq 'HASH') {
1.1013    raeburn  4722:                                 foreach my $hostname (keys(%{$domconfig{'login'}{'loginvia'}})) {
1.948     raeburn  4723:                                     if (ref($domconfig{'login'}{'loginvia'}{$hostname}) eq 'HASH') {
                   4724:                                         if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4725:                                             my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4726:                                             $designhash{$udom.'.login.loginvia'} = $server;
                   4727:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4728: 
                   4729:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4730:                                             } else {
1.1013    raeburn  4731:                                                 $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
1.948     raeburn  4732:                                             }
                   4733:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'exempt'}) {
                   4734:                                                 $designhash{$udom.'.login.loginvia_exempt_'.$hostname} = $domconfig{'login'}{'loginvia'}{$hostname}{'exempt'};
                   4735:                                             }
1.946     raeburn  4736:                                         }
                   4737:                                     }
                   4738:                                 }
                   4739:                             }
                   4740:                         } else {
                   4741:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4742:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4743:                                     $domconfig{'login'}{$key}{$img};
                   4744:                             }
1.699     raeburn  4745:                         }
                   4746:                     } else {
                   4747:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4748:                     }
1.632     raeburn  4749:                 }
                   4750:             } else {
                   4751:                 $legacy{'login'} = 1;
1.518     albertel 4752:             }
1.632     raeburn  4753:         } else {
                   4754:             $legacy{'login'} = 1;
1.518     albertel 4755:         }
                   4756:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4757:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4758:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4759:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4760:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4761:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4762:                         }
1.518     albertel 4763:                     }
                   4764:                 }
1.632     raeburn  4765:             } else {
                   4766:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4767:             }
1.632     raeburn  4768:         } else {
                   4769:             $legacy{'rolecolors'} = 1;
1.518     albertel 4770:         }
1.948     raeburn  4771:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4772:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4773:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4774:             }
                   4775:         }
1.632     raeburn  4776:         if (keys(%legacy) > 0) {
                   4777:             my %legacyhash = &get_legacy_domconf($udom);
                   4778:             foreach my $item (keys(%legacyhash)) {
                   4779:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4780:                     if ($legacy{'login'}) { 
                   4781:                         $designhash{$item} = $legacyhash{$item};
                   4782:                     }
                   4783:                 } else {
                   4784:                     if ($legacy{'rolecolors'}) {
                   4785:                         $designhash{$item} = $legacyhash{$item};
                   4786:                     }
1.518     albertel 4787:                 }
                   4788:             }
                   4789:         }
1.632     raeburn  4790:     } else {
                   4791:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4792:     }
                   4793:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4794: 				  $cachetime);
                   4795:     return %designhash;
                   4796: }
                   4797: 
1.632     raeburn  4798: sub get_legacy_domconf {
                   4799:     my ($udom) = @_;
                   4800:     my %legacyhash;
                   4801:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4802:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4803:     if (-e $designfile) {
                   4804:         if ( open (my $fh,"<$designfile") ) {
                   4805:             while (my $line = <$fh>) {
                   4806:                 next if ($line =~ /^\#/);
                   4807:                 chomp($line);
                   4808:                 my ($key,$val)=(split(/\=/,$line));
                   4809:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4810:             }
                   4811:             close($fh);
                   4812:         }
                   4813:     }
1.1026    raeburn  4814:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4815:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4816:     }
                   4817:     return %legacyhash;
                   4818: }
                   4819: 
1.63      www      4820: =pod
                   4821: 
1.112     bowersj2 4822: =item * &domainlogo()
1.63      www      4823: 
                   4824: Inputs: $domain (usually will be undef)
                   4825: 
                   4826: Returns: A link to a domain logo, if the domain logo exists.
                   4827: If the domain logo does not exist, a description of the domain.
                   4828: 
                   4829: =cut
1.112     bowersj2 4830: 
1.63      www      4831: ###############################################
                   4832: sub domainlogo {
1.517     raeburn  4833:     my $domain = &determinedomain(shift);
1.518     albertel 4834:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4835:     # See if there is a logo
                   4836:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4837:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4838:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4839: 	    if ($imgsrc =~ m{^/res/}) {
                   4840: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4841: 		&Apache::lonnet::repcopy($local_name);
                   4842: 	    }
                   4843: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4844:         } 
                   4845:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4846:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4847:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4848:     } else {
1.60      matthew  4849:         return '';
1.59      www      4850:     }
                   4851: }
1.63      www      4852: ##############################################
                   4853: 
                   4854: =pod
                   4855: 
1.112     bowersj2 4856: =item * &designparm()
1.63      www      4857: 
                   4858: Inputs: $which parameter; $domain (usually will be undef)
                   4859: 
                   4860: Returns: value of designparamter $which
                   4861: 
                   4862: =cut
1.112     bowersj2 4863: 
1.397     albertel 4864: 
1.400     albertel 4865: ##############################################
1.397     albertel 4866: sub designparm {
                   4867:     my ($which,$domain)=@_;
                   4868:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4869:         return $env{'environment.color.'.$which};
1.96      www      4870:     }
1.63      www      4871:     $domain=&determinedomain($domain);
1.1016    raeburn  4872:     my %domdesign;
                   4873:     unless ($domain eq 'public') {
                   4874:         %domdesign = &get_domainconf($domain);
                   4875:     }
1.520     raeburn  4876:     my $output;
1.517     raeburn  4877:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4878:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4879:     } else {
1.520     raeburn  4880:         $output = $defaultdesign{$which};
                   4881:     }
                   4882:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4883:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4884:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4885:             if ($output =~ m{^/res/}) {
                   4886:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4887:                 &Apache::lonnet::repcopy($local_name);
                   4888:             }
1.520     raeburn  4889:             $output = &lonhttpdurl($output);
                   4890:         }
1.63      www      4891:     }
1.520     raeburn  4892:     return $output;
1.63      www      4893: }
1.59      www      4894: 
1.822     bisitz   4895: ##############################################
                   4896: =pod
                   4897: 
1.832     bisitz   4898: =item * &authorspace()
                   4899: 
1.1028    raeburn  4900: Inputs: $url (usually will be undef).
1.832     bisitz   4901: 
1.1028    raeburn  4902: Returns: Path to Construction Space containing the resource or 
                   4903:          directory being viewed (or for which action is being taken). 
                   4904:          If $url is provided, and begins /priv/<domain>/<uname>
                   4905:          the path will be that portion of the $context argument.
                   4906:          Otherwise the path will be for the author space of the current
                   4907:          user when the current role is author, or for that of the 
                   4908:          co-author/assistant co-author space when the current role 
                   4909:          is co-author or assistant co-author.
1.832     bisitz   4910: 
                   4911: =cut
                   4912: 
                   4913: sub authorspace {
1.1028    raeburn  4914:     my ($url) = @_;
                   4915:     if ($url ne '') {
                   4916:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4917:            return $1;
                   4918:         }
                   4919:     }
1.832     bisitz   4920:     my $caname = '';
1.1024    www      4921:     my $cadom = '';
1.1028    raeburn  4922:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4923:         ($cadom,$caname) =
1.832     bisitz   4924:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4925:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4926:         $caname = $env{'user.name'};
1.1024    www      4927:         $cadom = $env{'user.domain'};
1.832     bisitz   4928:     }
1.1028    raeburn  4929:     if (($caname ne '') && ($cadom ne '')) {
                   4930:         return "/priv/$cadom/$caname/";
                   4931:     }
                   4932:     return;
1.832     bisitz   4933: }
                   4934: 
                   4935: ##############################################
                   4936: =pod
                   4937: 
1.822     bisitz   4938: =item * &head_subbox()
                   4939: 
                   4940: Inputs: $content (contains HTML code with page functions, etc.)
                   4941: 
                   4942: Returns: HTML div with $content
                   4943:          To be included in page header
                   4944: 
                   4945: =cut
                   4946: 
                   4947: sub head_subbox {
                   4948:     my ($content)=@_;
                   4949:     my $output =
1.993     raeburn  4950:         '<div class="LC_head_subbox">'
1.822     bisitz   4951:        .$content
                   4952:        .'</div>'
                   4953: }
                   4954: 
                   4955: ##############################################
                   4956: =pod
                   4957: 
                   4958: =item * &CSTR_pageheader()
                   4959: 
1.1026    raeburn  4960: Input: (optional) filename from which breadcrumb trail is built.
                   4961:        In most cases no input as needed, as $env{'request.filename'}
                   4962:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   4963: 
                   4964: Returns: HTML div with CSTR path and recent box
                   4965:          To be included on Construction Space pages
                   4966: 
                   4967: =cut
                   4968: 
                   4969: sub CSTR_pageheader {
1.1026    raeburn  4970:     my ($trailfile) = @_;
                   4971:     if ($trailfile eq '') {
                   4972:         $trailfile = $env{'request.filename'};
                   4973:     }
                   4974: 
                   4975: # this is for resources; directories have customtitle, and crumbs
                   4976: # and select recent are created in lonpubdir.pm
                   4977: 
                   4978:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      4979:     my ($udom,$uname,$thisdisfn)=
1.1026    raeburn  4980:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)/(.*)$});
                   4981:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   4982:     $formaction =~ s{/+}{/}g;
1.822     bisitz   4983: 
                   4984:     my $parentpath = '';
                   4985:     my $lastitem = '';
                   4986:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   4987:         $parentpath = $1;
                   4988:         $lastitem = $2;
                   4989:     } else {
                   4990:         $lastitem = $thisdisfn;
                   4991:     }
1.921     bisitz   4992: 
                   4993:     my $output =
1.822     bisitz   4994:          '<div>'
                   4995:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
                   4996:         .'<b>'.&mt('Construction Space:').'</b> '
                   4997:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   4998:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      4999:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5000: 
                   5001:     if ($lastitem) {
                   5002:         $output .=
                   5003:              '<span class="LC_filename">'
                   5004:             .$lastitem
                   5005:             .'</span>';
                   5006:     }
                   5007:     $output .=
                   5008:          '<br />'
1.822     bisitz   5009:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5010:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5011:         .'</form>'
                   5012:         .&Apache::lonmenu::constspaceform()
                   5013:         .'</div>';
1.921     bisitz   5014: 
                   5015:     return $output;
1.822     bisitz   5016: }
                   5017: 
1.60      matthew  5018: ###############################################
                   5019: ###############################################
                   5020: 
                   5021: =pod
                   5022: 
1.112     bowersj2 5023: =back
                   5024: 
1.549     albertel 5025: =head1 HTML Helpers
1.112     bowersj2 5026: 
                   5027: =over 4
                   5028: 
                   5029: =item * &bodytag()
1.60      matthew  5030: 
                   5031: Returns a uniform header for LON-CAPA web pages.
                   5032: 
                   5033: Inputs: 
                   5034: 
1.112     bowersj2 5035: =over 4
                   5036: 
                   5037: =item * $title, A title to be displayed on the page.
                   5038: 
                   5039: =item * $function, the current role (can be undef).
                   5040: 
                   5041: =item * $addentries, extra parameters for the <body> tag.
                   5042: 
                   5043: =item * $bodyonly, if defined, only return the <body> tag.
                   5044: 
                   5045: =item * $domain, if defined, force a given domain.
                   5046: 
                   5047: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5048:             text interface only)
1.60      matthew  5049: 
1.814     bisitz   5050: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5051:                      navigational links
1.317     albertel 5052: 
1.338     albertel 5053: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5054: 
1.460     albertel 5055: =item * $args, optional argument valid values are
                   5056:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5057:             inherit_jsmath -> when creating popup window in a page,
                   5058:                               should it have jsmath forced on by the
                   5059:                               current page
1.460     albertel 5060: 
1.112     bowersj2 5061: =back
                   5062: 
1.60      matthew  5063: Returns: A uniform header for LON-CAPA web pages.  
                   5064: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5065: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5066: other decorations will be returned.
                   5067: 
                   5068: =cut
                   5069: 
1.54      www      5070: sub bodytag {
1.831     bisitz   5071:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.962     droeschl 5072:         $no_nav_bar,$bgcolor,$args)=@_;
1.339     albertel 5073: 
1.954     raeburn  5074:     my $public;
                   5075:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5076:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5077:         $public = 1;
                   5078:     }
1.460     albertel 5079:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.339     albertel 5080: 
1.183     matthew  5081:     $function = &get_users_function() if (!$function);
1.339     albertel 5082:     my $img =    &designparm($function.'.img',$domain);
                   5083:     my $font =   &designparm($function.'.font',$domain);
                   5084:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5085: 
1.803     bisitz   5086:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5087: 		   'bgcolor' => $pgbg,
1.339     albertel 5088: 		   'text'    => $font,
                   5089:                    'alink'   => &designparm($function.'.alink',$domain),
                   5090: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5091: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5092:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5093: 
1.63      www      5094:  # role and realm
1.378     raeburn  5095:     my ($role,$realm) = split(/\./,$env{'request.role'},2);
                   5096:     if ($role  eq 'ca') {
1.479     albertel 5097:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5098:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5099:     } 
1.55      www      5100: # realm
1.258     albertel 5101:     if ($env{'request.course.id'}) {
1.378     raeburn  5102:         if ($env{'request.role'} !~ /^cr/) {
                   5103:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5104:         }
1.898     raeburn  5105:         if ($env{'request.course.sec'}) {
                   5106:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5107:         }   
1.359     albertel 5108: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5109:     } else {
                   5110:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5111:     }
1.433     albertel 5112: 
1.359     albertel 5113:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5114: 
1.438     albertel 5115:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5116: 
1.101     www      5117: # construct main body tag
1.359     albertel 5118:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5119: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5120: 
1.530     albertel 5121:     if ($bodyonly) {
1.60      matthew  5122:         return $bodytag;
1.798     tempelho 5123:     } 
1.359     albertel 5124: 
1.410     albertel 5125:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
1.954     raeburn  5126:     if ($public) {
1.433     albertel 5127: 	undef($role);
1.434     albertel 5128:     } else {
1.1070    raeburn  5129: 	$name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5130:                                 undef,'LC_menubuttons_link');
1.433     albertel 5131:     }
1.359     albertel 5132:     
1.762     bisitz   5133:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5134:     #
                   5135:     # Extra info if you are the DC
                   5136:     my $dc_info = '';
                   5137:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5138:                         $env{'course.'.$env{'request.course.id'}.
                   5139:                                  '.domain'}.'/'})) {
                   5140:         my $cid = $env{'request.course.id'};
1.917     raeburn  5141:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5142:         $dc_info =~ s/\s+$//;
1.359     albertel 5143:     }
                   5144: 
1.898     raeburn  5145:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5146:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5147: 
1.916     droeschl 5148:         if ($no_nav_bar || $env{'form.inhibitmenu'} eq 'yes') { 
                   5149:             return $bodytag; 
                   5150:         } 
1.903     droeschl 5151: 
                   5152:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5153: 
                   5154:         #    if ($env{'request.state'} eq 'construct') {
                   5155:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5156:         #    }
                   5157: 
1.359     albertel 5158: 
                   5159: 
1.916     droeschl 5160:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5161:              if ($dc_info) {
                   5162:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5163:              }
1.916     droeschl 5164:              $bodytag .= qq|<div id="LC_nav_bar">$name $role<br />
                   5165:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5166:             return $bodytag;
                   5167:         }
1.894     droeschl 5168: 
1.927     raeburn  5169:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
                   5170:             $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>|;
                   5171:         }
1.916     droeschl 5172: 
1.903     droeschl 5173:         $bodytag .= Apache::lonhtmlcommon::scripttag(
                   5174:             Apache::lonmenu::utilityfunctions(), 'start');
1.816     bisitz   5175: 
1.903     droeschl 5176:         $bodytag .= Apache::lonmenu::primary_menu();
1.852     droeschl 5177: 
1.917     raeburn  5178:         if ($dc_info) {
                   5179:             $dc_info = &dc_courseid_toggle($dc_info);
                   5180:         }
                   5181:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5182: 
1.903     droeschl 5183:         #don't show menus for public users
1.954     raeburn  5184:         if (!$public){
1.903     droeschl 5185:             $bodytag .= Apache::lonmenu::secondary_menu();
                   5186:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5187:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5188:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5189:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5190:                                 $args->{'bread_crumbs'});
                   5191:             } elsif ($forcereg) { 
                   5192:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg);
                   5193:             }
1.903     droeschl 5194:         }else{
                   5195:             # this is to seperate menu from content when there's no secondary
                   5196:             # menu. Especially needed for public accessible ressources.
                   5197:             $bodytag .= '<hr style="clear:both" />';
                   5198:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5199:         }
1.903     droeschl 5200: 
1.235     raeburn  5201:         return $bodytag;
1.182     matthew  5202: }
                   5203: 
1.917     raeburn  5204: sub dc_courseid_toggle {
                   5205:     my ($dc_info) = @_;
1.980     raeburn  5206:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5207:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5208:            &mt('(More ...)').'</a></span>'.
                   5209:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5210: }
                   5211: 
1.330     albertel 5212: sub make_attr_string {
                   5213:     my ($register,$attr_ref) = @_;
                   5214: 
                   5215:     if ($attr_ref && !ref($attr_ref)) {
                   5216: 	die("addentries Must be a hash ref ".
                   5217: 	    join(':',caller(1))." ".
                   5218: 	    join(':',caller(0))." ");
                   5219:     }
                   5220: 
                   5221:     if ($register) {
1.339     albertel 5222: 	my ($on_load,$on_unload);
                   5223: 	foreach my $key (keys(%{$attr_ref})) {
                   5224: 	    if      (lc($key) eq 'onload') {
                   5225: 		$on_load.=$attr_ref->{$key}.';';
                   5226: 		delete($attr_ref->{$key});
                   5227: 
                   5228: 	    } elsif (lc($key) eq 'onunload') {
                   5229: 		$on_unload.=$attr_ref->{$key}.';';
                   5230: 		delete($attr_ref->{$key});
                   5231: 	    }
                   5232: 	}
1.953     droeschl 5233: 	$attr_ref->{'onload'}  = $on_load;
                   5234: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5235:     }
1.339     albertel 5236: 
1.330     albertel 5237:     my $attr_string;
                   5238:     foreach my $attr (keys(%$attr_ref)) {
                   5239: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5240:     }
                   5241:     return $attr_string;
                   5242: }
                   5243: 
                   5244: 
1.182     matthew  5245: ###############################################
1.251     albertel 5246: ###############################################
                   5247: 
                   5248: =pod
                   5249: 
                   5250: =item * &endbodytag()
                   5251: 
                   5252: Returns a uniform footer for LON-CAPA web pages.
                   5253: 
1.635     raeburn  5254: Inputs: 1 - optional reference to an args hash
                   5255: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5256: a 'Continue' link is not displayed if the page contains an
                   5257: internal redirect in the <head></head> section,
                   5258: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5259: 
                   5260: =cut
                   5261: 
                   5262: sub endbodytag {
1.635     raeburn  5263:     my ($args) = @_;
1.1080    raeburn  5264:     my $endbodytag;
                   5265:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5266:         $endbodytag='</body>';
                   5267:     }
1.269     albertel 5268:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5269:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5270:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5271: 	    $endbodytag=
                   5272: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5273: 	        &mt('Continue').'</a>'.
                   5274: 	        $endbodytag;
                   5275:         }
1.315     albertel 5276:     }
1.251     albertel 5277:     return $endbodytag;
                   5278: }
                   5279: 
1.352     albertel 5280: =pod
                   5281: 
                   5282: =item * &standard_css()
                   5283: 
                   5284: Returns a style sheet
                   5285: 
                   5286: Inputs: (all optional)
                   5287:             domain         -> force to color decorate a page for a specific
                   5288:                                domain
                   5289:             function       -> force usage of a specific rolish color scheme
                   5290:             bgcolor        -> override the default page bgcolor
                   5291: 
                   5292: =cut
                   5293: 
1.343     albertel 5294: sub standard_css {
1.345     albertel 5295:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5296:     $function  = &get_users_function() if (!$function);
                   5297:     my $img    = &designparm($function.'.img',   $domain);
                   5298:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5299:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5300:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5301: #second colour for later usage
1.345     albertel 5302:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5303:     my $pgbg_or_bgcolor =
                   5304: 	         $bgcolor ||
1.352     albertel 5305: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5306:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5307:     my $alink  = &designparm($function.'.alink', $domain);
                   5308:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5309:     my $link   = &designparm($function.'.link',  $domain);
                   5310: 
1.602     albertel 5311:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5312:     my $mono                 = 'monospace';
1.850     bisitz   5313:     my $data_table_head      = $sidebg;
                   5314:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5315:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5316:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5317:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5318:     my $mail_new             = '#FFBB77';
                   5319:     my $mail_new_hover       = '#DD9955';
                   5320:     my $mail_read            = '#BBBB77';
                   5321:     my $mail_read_hover      = '#999944';
                   5322:     my $mail_replied         = '#AAAA88';
                   5323:     my $mail_replied_hover   = '#888855';
                   5324:     my $mail_other           = '#99BBBB';
                   5325:     my $mail_other_hover     = '#669999';
1.391     albertel 5326:     my $table_header         = '#DDDDDD';
1.489     raeburn  5327:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5328:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5329:     my $button_hover         = '#BF2317';
1.392     albertel 5330: 
1.608     albertel 5331:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5332:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5333:                                              : '0 3px 0 4px';
1.448     albertel 5334: 
1.523     albertel 5335: 
1.343     albertel 5336:     return <<END;
1.947     droeschl 5337: 
                   5338: /* needed for iframe to allow 100% height in FF */
                   5339: body, html { 
                   5340:     margin: 0;
                   5341:     padding: 0 0.5%;
                   5342:     height: 99%; /* to avoid scrollbars */
                   5343: }
                   5344: 
1.795     www      5345: body {
1.911     bisitz   5346:   font-family: $sans;
                   5347:   line-height:130%;
                   5348:   font-size:0.83em;
                   5349:   color:$font;
1.795     www      5350: }
                   5351: 
1.959     onken    5352: a:focus,
                   5353: a:focus img {
1.795     www      5354:   color: red;
                   5355: }
1.698     harmsja  5356: 
1.911     bisitz   5357: form, .inline {
                   5358:   display: inline;
1.795     www      5359: }
1.721     harmsja  5360: 
1.795     www      5361: .LC_right {
1.911     bisitz   5362:   text-align:right;
1.795     www      5363: }
                   5364: 
                   5365: .LC_middle {
1.911     bisitz   5366:   vertical-align:middle;
1.795     www      5367: }
1.721     harmsja  5368: 
1.911     bisitz   5369: .LC_400Box {
                   5370:   width:400px;
                   5371: }
1.721     harmsja  5372: 
1.947     droeschl 5373: .LC_iframecontainer {
                   5374:     width: 98%;
                   5375:     margin: 0;
                   5376:     position: fixed;
                   5377:     top: 8.5em;
                   5378:     bottom: 0;
                   5379: }
                   5380: 
                   5381: .LC_iframecontainer iframe{
                   5382:     border: none;
                   5383:     width: 100%;
                   5384:     height: 100%;
                   5385: }
                   5386: 
1.778     bisitz   5387: .LC_filename {
                   5388:   font-family: $mono;
                   5389:   white-space:pre;
1.921     bisitz   5390:   font-size: 120%;
1.778     bisitz   5391: }
                   5392: 
                   5393: .LC_fileicon {
                   5394:   border: none;
                   5395:   height: 1.3em;
                   5396:   vertical-align: text-bottom;
                   5397:   margin-right: 0.3em;
                   5398:   text-decoration:none;
                   5399: }
                   5400: 
1.1008    www      5401: .LC_setting {
                   5402:   text-decoration:underline;
                   5403: }
                   5404: 
1.350     albertel 5405: .LC_error {
                   5406:   color: red;
                   5407:   font-size: larger;
                   5408: }
1.795     www      5409: 
1.457     albertel 5410: .LC_warning,
                   5411: .LC_diff_removed {
1.733     bisitz   5412:   color: red;
1.394     albertel 5413: }
1.532     albertel 5414: 
                   5415: .LC_info,
1.457     albertel 5416: .LC_success,
                   5417: .LC_diff_added {
1.350     albertel 5418:   color: green;
                   5419: }
1.795     www      5420: 
1.802     bisitz   5421: div.LC_confirm_box {
                   5422:   background-color: #FAFAFA;
                   5423:   border: 1px solid $lg_border_color;
                   5424:   margin-right: 0;
                   5425:   padding: 5px;
                   5426: }
                   5427: 
                   5428: div.LC_confirm_box .LC_error img,
                   5429: div.LC_confirm_box .LC_success img {
                   5430:   vertical-align: middle;
                   5431: }
                   5432: 
1.440     albertel 5433: .LC_icon {
1.771     droeschl 5434:   border: none;
1.790     droeschl 5435:   vertical-align: middle;
1.771     droeschl 5436: }
                   5437: 
1.543     albertel 5438: .LC_docs_spacer {
                   5439:   width: 25px;
                   5440:   height: 1px;
1.771     droeschl 5441:   border: none;
1.543     albertel 5442: }
1.346     albertel 5443: 
1.532     albertel 5444: .LC_internal_info {
1.735     bisitz   5445:   color: #999999;
1.532     albertel 5446: }
                   5447: 
1.794     www      5448: .LC_discussion {
1.1050    www      5449:   background: $data_table_dark;
1.911     bisitz   5450:   border: 1px solid black;
                   5451:   margin: 2px;
1.794     www      5452: }
                   5453: 
                   5454: .LC_disc_action_left {
1.1050    www      5455:   background: $sidebg;
1.911     bisitz   5456:   text-align: left;
1.1050    www      5457:   padding: 4px;
                   5458:   margin: 2px;
1.794     www      5459: }
                   5460: 
                   5461: .LC_disc_action_right {
1.1050    www      5462:   background: $sidebg;
1.911     bisitz   5463:   text-align: right;
1.1050    www      5464:   padding: 4px;
                   5465:   margin: 2px;
1.794     www      5466: }
                   5467: 
                   5468: .LC_disc_new_item {
1.911     bisitz   5469:   background: white;
                   5470:   border: 2px solid red;
1.1050    www      5471:   margin: 4px;
                   5472:   padding: 4px;
1.794     www      5473: }
                   5474: 
                   5475: .LC_disc_old_item {
1.911     bisitz   5476:   background: white;
1.1050    www      5477:   margin: 4px;
                   5478:   padding: 4px;
1.794     www      5479: }
                   5480: 
1.458     albertel 5481: table.LC_pastsubmission {
                   5482:   border: 1px solid black;
                   5483:   margin: 2px;
                   5484: }
                   5485: 
1.924     bisitz   5486: table#LC_menubuttons {
1.345     albertel 5487:   width: 100%;
                   5488:   background: $pgbg;
1.392     albertel 5489:   border: 2px;
1.402     albertel 5490:   border-collapse: separate;
1.803     bisitz   5491:   padding: 0;
1.345     albertel 5492: }
1.392     albertel 5493: 
1.801     tempelho 5494: table#LC_title_bar a {
                   5495:   color: $fontmenu;
                   5496: }
1.836     bisitz   5497: 
1.807     droeschl 5498: table#LC_title_bar {
1.819     tempelho 5499:   clear: both;
1.836     bisitz   5500:   display: none;
1.807     droeschl 5501: }
                   5502: 
1.795     www      5503: table#LC_title_bar,
1.933     droeschl 5504: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5505: table#LC_title_bar.LC_with_remote {
1.359     albertel 5506:   width: 100%;
1.392     albertel 5507:   border-color: $pgbg;
                   5508:   border-style: solid;
                   5509:   border-width: $border;
1.379     albertel 5510:   background: $pgbg;
1.801     tempelho 5511:   color: $fontmenu;
1.392     albertel 5512:   border-collapse: collapse;
1.803     bisitz   5513:   padding: 0;
1.819     tempelho 5514:   margin: 0;
1.359     albertel 5515: }
1.795     www      5516: 
1.933     droeschl 5517: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5518:     margin: 0;
                   5519:     padding: 0;
1.933     droeschl 5520:     position: relative;
                   5521:     list-style: none;
1.913     droeschl 5522: }
1.933     droeschl 5523: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5524:     display: inline;
                   5525: }
1.933     droeschl 5526: 
                   5527: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5528:     padding: 0;
1.933     droeschl 5529:     margin: 0;
                   5530:     float: left;
1.913     droeschl 5531: }
1.933     droeschl 5532: .LC_breadcrumb_tools_tools {
                   5533:     padding: 0;
                   5534:     margin: 0;
1.913     droeschl 5535:     float: right;
                   5536: }
                   5537: 
1.359     albertel 5538: table#LC_title_bar td {
                   5539:   background: $tabbg;
                   5540: }
1.795     www      5541: 
1.911     bisitz   5542: table#LC_menubuttons img {
1.803     bisitz   5543:   border: none;
1.346     albertel 5544: }
1.795     www      5545: 
1.842     droeschl 5546: .LC_breadcrumbs_component {
1.911     bisitz   5547:   float: right;
                   5548:   margin: 0 1em;
1.357     albertel 5549: }
1.842     droeschl 5550: .LC_breadcrumbs_component img {
1.911     bisitz   5551:   vertical-align: middle;
1.777     tempelho 5552: }
1.795     www      5553: 
1.383     albertel 5554: td.LC_table_cell_checkbox {
                   5555:   text-align: center;
                   5556: }
1.795     www      5557: 
                   5558: .LC_fontsize_small {
1.911     bisitz   5559:   font-size: 70%;
1.705     tempelho 5560: }
                   5561: 
1.844     bisitz   5562: #LC_breadcrumbs {
1.911     bisitz   5563:   clear:both;
                   5564:   background: $sidebg;
                   5565:   border-bottom: 1px solid $lg_border_color;
                   5566:   line-height: 2.5em;
1.933     droeschl 5567:   overflow: hidden;
1.911     bisitz   5568:   margin: 0;
                   5569:   padding: 0;
1.995     raeburn  5570:   text-align: left;
1.819     tempelho 5571: }
1.862     bisitz   5572: 
1.993     raeburn  5573: .LC_head_subbox {
1.911     bisitz   5574:   clear:both;
                   5575:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5576:   border: 1px solid $sidebg;
                   5577:   margin: 0 0 10px 0;      
1.966     bisitz   5578:   padding: 3px;
1.995     raeburn  5579:   text-align: left;
1.822     bisitz   5580: }
                   5581: 
1.795     www      5582: .LC_fontsize_medium {
1.911     bisitz   5583:   font-size: 85%;
1.705     tempelho 5584: }
                   5585: 
1.795     www      5586: .LC_fontsize_large {
1.911     bisitz   5587:   font-size: 120%;
1.705     tempelho 5588: }
                   5589: 
1.346     albertel 5590: .LC_menubuttons_inline_text {
                   5591:   color: $font;
1.698     harmsja  5592:   font-size: 90%;
1.701     harmsja  5593:   padding-left:3px;
1.346     albertel 5594: }
                   5595: 
1.934     droeschl 5596: .LC_menubuttons_inline_text img{
                   5597:   vertical-align: middle;
                   5598: }
                   5599: 
1.1051    www      5600: li.LC_menubuttons_inline_text img {
1.951     onken    5601:   cursor:pointer;
1.1002    droeschl 5602:   text-decoration: none;
1.951     onken    5603: }
                   5604: 
1.526     www      5605: .LC_menubuttons_link {
                   5606:   text-decoration: none;
                   5607: }
1.795     www      5608: 
1.522     albertel 5609: .LC_menubuttons_category {
1.521     www      5610:   color: $font;
1.526     www      5611:   background: $pgbg;
1.521     www      5612:   font-size: larger;
                   5613:   font-weight: bold;
                   5614: }
                   5615: 
1.346     albertel 5616: td.LC_menubuttons_text {
1.911     bisitz   5617:   color: $font;
1.346     albertel 5618: }
1.706     harmsja  5619: 
1.346     albertel 5620: .LC_current_location {
                   5621:   background: $tabbg;
                   5622: }
1.795     www      5623: 
1.938     bisitz   5624: table.LC_data_table {
1.347     albertel 5625:   border: 1px solid #000000;
1.402     albertel 5626:   border-collapse: separate;
1.426     albertel 5627:   border-spacing: 1px;
1.610     albertel 5628:   background: $pgbg;
1.347     albertel 5629: }
1.795     www      5630: 
1.422     albertel 5631: .LC_data_table_dense {
                   5632:   font-size: small;
                   5633: }
1.795     www      5634: 
1.507     raeburn  5635: table.LC_nested_outer {
                   5636:   border: 1px solid #000000;
1.589     raeburn  5637:   border-collapse: collapse;
1.803     bisitz   5638:   border-spacing: 0;
1.507     raeburn  5639:   width: 100%;
                   5640: }
1.795     www      5641: 
1.879     raeburn  5642: table.LC_innerpickbox,
1.507     raeburn  5643: table.LC_nested {
1.803     bisitz   5644:   border: none;
1.589     raeburn  5645:   border-collapse: collapse;
1.803     bisitz   5646:   border-spacing: 0;
1.507     raeburn  5647:   width: 100%;
                   5648: }
1.795     www      5649: 
1.911     bisitz   5650: table.LC_data_table tr th,
                   5651: table.LC_calendar tr th,
1.879     raeburn  5652: table.LC_prior_tries tr th,
                   5653: table.LC_innerpickbox tr th {
1.349     albertel 5654:   font-weight: bold;
                   5655:   background-color: $data_table_head;
1.801     tempelho 5656:   color:$fontmenu;
1.701     harmsja  5657:   font-size:90%;
1.347     albertel 5658: }
1.795     www      5659: 
1.879     raeburn  5660: table.LC_innerpickbox tr th,
                   5661: table.LC_innerpickbox tr td {
                   5662:   vertical-align: top;
                   5663: }
                   5664: 
1.711     raeburn  5665: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5666:   background-color: #CCCCCC;
1.711     raeburn  5667:   font-weight: bold;
                   5668:   text-align: left;
                   5669: }
1.795     www      5670: 
1.912     bisitz   5671: table.LC_data_table tr.LC_odd_row > td {
                   5672:   background-color: $data_table_light;
                   5673:   padding: 2px;
                   5674:   vertical-align: top;
                   5675: }
                   5676: 
1.809     bisitz   5677: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5678:   background-color: $data_table_light;
1.912     bisitz   5679:   vertical-align: top;
                   5680: }
                   5681: 
                   5682: table.LC_data_table tr.LC_even_row > td {
                   5683:   background-color: $data_table_dark;
1.425     albertel 5684:   padding: 2px;
1.900     bisitz   5685:   vertical-align: top;
1.347     albertel 5686: }
1.795     www      5687: 
1.809     bisitz   5688: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5689:   background-color: $data_table_dark;
1.900     bisitz   5690:   vertical-align: top;
1.347     albertel 5691: }
1.795     www      5692: 
1.425     albertel 5693: table.LC_data_table tr.LC_data_table_highlight td {
                   5694:   background-color: $data_table_darker;
                   5695: }
1.795     www      5696: 
1.639     raeburn  5697: table.LC_data_table tr td.LC_leftcol_header {
                   5698:   background-color: $data_table_head;
                   5699:   font-weight: bold;
                   5700: }
1.795     www      5701: 
1.451     albertel 5702: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5703: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5704:   font-weight: bold;
                   5705:   font-style: italic;
                   5706:   text-align: center;
                   5707:   padding: 8px;
1.347     albertel 5708: }
1.795     www      5709: 
1.940     bisitz   5710: table.LC_data_table tr.LC_empty_row td {
                   5711:   background-color: $sidebg;
                   5712: }
                   5713: 
                   5714: table.LC_nested tr.LC_empty_row td {
                   5715:   background-color: #FFFFFF;
                   5716: }
                   5717: 
1.890     droeschl 5718: table.LC_caption {
                   5719: }
                   5720: 
1.507     raeburn  5721: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5722:   padding: 4ex
                   5723: }
1.795     www      5724: 
1.507     raeburn  5725: table.LC_nested_outer tr th {
                   5726:   font-weight: bold;
1.801     tempelho 5727:   color:$fontmenu;
1.507     raeburn  5728:   background-color: $data_table_head;
1.701     harmsja  5729:   font-size: small;
1.507     raeburn  5730:   border-bottom: 1px solid #000000;
                   5731: }
1.795     www      5732: 
1.507     raeburn  5733: table.LC_nested_outer tr td.LC_subheader {
                   5734:   background-color: $data_table_head;
                   5735:   font-weight: bold;
                   5736:   font-size: small;
                   5737:   border-bottom: 1px solid #000000;
                   5738:   text-align: right;
1.451     albertel 5739: }
1.795     www      5740: 
1.507     raeburn  5741: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5742:   background-color: #CCCCCC;
1.451     albertel 5743:   font-weight: bold;
                   5744:   font-size: small;
1.507     raeburn  5745:   text-align: center;
                   5746: }
1.795     www      5747: 
1.589     raeburn  5748: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5749: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5750:   text-align: left;
1.451     albertel 5751: }
1.795     www      5752: 
1.507     raeburn  5753: table.LC_nested td {
1.735     bisitz   5754:   background-color: #FFFFFF;
1.451     albertel 5755:   font-size: small;
1.507     raeburn  5756: }
1.795     www      5757: 
1.507     raeburn  5758: table.LC_nested_outer tr th.LC_right_item,
                   5759: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5760: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5761: table.LC_nested tr td.LC_right_item {
1.451     albertel 5762:   text-align: right;
                   5763: }
                   5764: 
1.507     raeburn  5765: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5766:   background-color: #EEEEEE;
1.451     albertel 5767: }
                   5768: 
1.473     raeburn  5769: table.LC_createuser {
                   5770: }
                   5771: 
                   5772: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5773:   font-size: small;
1.473     raeburn  5774: }
                   5775: 
                   5776: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5777:   background-color: #CCCCCC;
1.473     raeburn  5778:   font-weight: bold;
                   5779:   text-align: center;
                   5780: }
                   5781: 
1.349     albertel 5782: table.LC_calendar {
                   5783:   border: 1px solid #000000;
                   5784:   border-collapse: collapse;
1.917     raeburn  5785:   width: 98%;
1.349     albertel 5786: }
1.795     www      5787: 
1.349     albertel 5788: table.LC_calendar_pickdate {
                   5789:   font-size: xx-small;
                   5790: }
1.795     www      5791: 
1.349     albertel 5792: table.LC_calendar tr td {
                   5793:   border: 1px solid #000000;
                   5794:   vertical-align: top;
1.917     raeburn  5795:   width: 14%;
1.349     albertel 5796: }
1.795     www      5797: 
1.349     albertel 5798: table.LC_calendar tr td.LC_calendar_day_empty {
                   5799:   background-color: $data_table_dark;
                   5800: }
1.795     www      5801: 
1.779     bisitz   5802: table.LC_calendar tr td.LC_calendar_day_current {
                   5803:   background-color: $data_table_highlight;
1.777     tempelho 5804: }
1.795     www      5805: 
1.938     bisitz   5806: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5807:   background-color: $mail_new;
                   5808: }
1.795     www      5809: 
1.938     bisitz   5810: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5811:   background-color: $mail_new_hover;
                   5812: }
1.795     www      5813: 
1.938     bisitz   5814: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5815:   background-color: $mail_read;
                   5816: }
1.795     www      5817: 
1.938     bisitz   5818: /*
                   5819: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5820:   background-color: $mail_read_hover;
                   5821: }
1.938     bisitz   5822: */
1.795     www      5823: 
1.938     bisitz   5824: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5825:   background-color: $mail_replied;
                   5826: }
1.795     www      5827: 
1.938     bisitz   5828: /*
                   5829: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5830:   background-color: $mail_replied_hover;
                   5831: }
1.938     bisitz   5832: */
1.795     www      5833: 
1.938     bisitz   5834: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 5835:   background-color: $mail_other;
                   5836: }
1.795     www      5837: 
1.938     bisitz   5838: /*
                   5839: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 5840:   background-color: $mail_other_hover;
                   5841: }
1.938     bisitz   5842: */
1.494     raeburn  5843: 
1.777     tempelho 5844: table.LC_data_table tr > td.LC_browser_file,
                   5845: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   5846:   background: #AAEE77;
1.389     albertel 5847: }
1.795     www      5848: 
1.777     tempelho 5849: table.LC_data_table tr > td.LC_browser_file_locked,
                   5850: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 5851:   background: #FFAA99;
1.387     albertel 5852: }
1.795     www      5853: 
1.777     tempelho 5854: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   5855:   background: #888888;
1.779     bisitz   5856: }
1.795     www      5857: 
1.777     tempelho 5858: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   5859: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   5860:   background: #F8F866;
1.777     tempelho 5861: }
1.795     www      5862: 
1.696     bisitz   5863: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   5864:   background: #E0E8FF;
1.387     albertel 5865: }
1.696     bisitz   5866: 
1.707     bisitz   5867: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   5868:   /* background: #77FF77; */
1.707     bisitz   5869: }
1.795     www      5870: 
1.707     bisitz   5871: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   5872:   border-right: 8px solid #FFFF77;
1.707     bisitz   5873: }
1.795     www      5874: 
1.707     bisitz   5875: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   5876:   border-right: 8px solid #FFAA77;
1.707     bisitz   5877: }
1.795     www      5878: 
1.707     bisitz   5879: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   5880:   border-right: 8px solid #FF7777;
1.707     bisitz   5881: }
1.795     www      5882: 
1.707     bisitz   5883: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   5884:   border-right: 8px solid #AAFF77;
1.707     bisitz   5885: }
1.795     www      5886: 
1.707     bisitz   5887: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   5888:   border-right: 8px solid #11CC55;
1.707     bisitz   5889: }
                   5890: 
1.388     albertel 5891: span.LC_current_location {
1.701     harmsja  5892:   font-size:larger;
1.388     albertel 5893:   background: $pgbg;
                   5894: }
1.387     albertel 5895: 
1.1029    www      5896: span.LC_current_nav_location {
                   5897:   font-weight:bold;
                   5898:   background: $sidebg;
                   5899: }
                   5900: 
1.395     albertel 5901: span.LC_parm_menu_item {
                   5902:   font-size: larger;
                   5903: }
1.795     www      5904: 
1.395     albertel 5905: span.LC_parm_scope_all {
                   5906:   color: red;
                   5907: }
1.795     www      5908: 
1.395     albertel 5909: span.LC_parm_scope_folder {
                   5910:   color: green;
                   5911: }
1.795     www      5912: 
1.395     albertel 5913: span.LC_parm_scope_resource {
                   5914:   color: orange;
                   5915: }
1.795     www      5916: 
1.395     albertel 5917: span.LC_parm_part {
                   5918:   color: blue;
                   5919: }
1.795     www      5920: 
1.911     bisitz   5921: span.LC_parm_folder,
                   5922: span.LC_parm_symb {
1.395     albertel 5923:   font-size: x-small;
                   5924:   font-family: $mono;
                   5925:   color: #AAAAAA;
                   5926: }
                   5927: 
1.977     bisitz   5928: ul.LC_parm_parmlist li {
                   5929:   display: inline-block;
                   5930:   padding: 0.3em 0.8em;
                   5931:   vertical-align: top;
                   5932:   width: 150px;
                   5933:   border-top:1px solid $lg_border_color;
                   5934: }
                   5935: 
1.795     www      5936: td.LC_parm_overview_level_menu,
                   5937: td.LC_parm_overview_map_menu,
                   5938: td.LC_parm_overview_parm_selectors,
                   5939: td.LC_parm_overview_restrictions  {
1.396     albertel 5940:   border: 1px solid black;
                   5941:   border-collapse: collapse;
                   5942: }
1.795     www      5943: 
1.396     albertel 5944: table.LC_parm_overview_restrictions td {
                   5945:   border-width: 1px 4px 1px 4px;
                   5946:   border-style: solid;
                   5947:   border-color: $pgbg;
                   5948:   text-align: center;
                   5949: }
1.795     www      5950: 
1.396     albertel 5951: table.LC_parm_overview_restrictions th {
                   5952:   background: $tabbg;
                   5953:   border-width: 1px 4px 1px 4px;
                   5954:   border-style: solid;
                   5955:   border-color: $pgbg;
                   5956: }
1.795     www      5957: 
1.398     albertel 5958: table#LC_helpmenu {
1.803     bisitz   5959:   border: none;
1.398     albertel 5960:   height: 55px;
1.803     bisitz   5961:   border-spacing: 0;
1.398     albertel 5962: }
                   5963: 
                   5964: table#LC_helpmenu fieldset legend {
                   5965:   font-size: larger;
                   5966: }
1.795     www      5967: 
1.397     albertel 5968: table#LC_helpmenu_links {
                   5969:   width: 100%;
                   5970:   border: 1px solid black;
                   5971:   background: $pgbg;
1.803     bisitz   5972:   padding: 0;
1.397     albertel 5973:   border-spacing: 1px;
                   5974: }
1.795     www      5975: 
1.397     albertel 5976: table#LC_helpmenu_links tr td {
                   5977:   padding: 1px;
                   5978:   background: $tabbg;
1.399     albertel 5979:   text-align: center;
                   5980:   font-weight: bold;
1.397     albertel 5981: }
1.396     albertel 5982: 
1.795     www      5983: table#LC_helpmenu_links a:link,
                   5984: table#LC_helpmenu_links a:visited,
1.397     albertel 5985: table#LC_helpmenu_links a:active {
                   5986:   text-decoration: none;
                   5987:   color: $font;
                   5988: }
1.795     www      5989: 
1.397     albertel 5990: table#LC_helpmenu_links a:hover {
                   5991:   text-decoration: underline;
                   5992:   color: $vlink;
                   5993: }
1.396     albertel 5994: 
1.417     albertel 5995: .LC_chrt_popup_exists {
                   5996:   border: 1px solid #339933;
                   5997:   margin: -1px;
                   5998: }
1.795     www      5999: 
1.417     albertel 6000: .LC_chrt_popup_up {
                   6001:   border: 1px solid yellow;
                   6002:   margin: -1px;
                   6003: }
1.795     www      6004: 
1.417     albertel 6005: .LC_chrt_popup {
                   6006:   border: 1px solid #8888FF;
                   6007:   background: #CCCCFF;
                   6008: }
1.795     www      6009: 
1.421     albertel 6010: table.LC_pick_box {
                   6011:   border-collapse: separate;
                   6012:   background: white;
                   6013:   border: 1px solid black;
                   6014:   border-spacing: 1px;
                   6015: }
1.795     www      6016: 
1.421     albertel 6017: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6018:   background: $sidebg;
1.421     albertel 6019:   font-weight: bold;
1.900     bisitz   6020:   text-align: left;
1.740     bisitz   6021:   vertical-align: top;
1.421     albertel 6022:   width: 184px;
                   6023:   padding: 8px;
                   6024: }
1.795     www      6025: 
1.579     raeburn  6026: table.LC_pick_box td.LC_pick_box_value {
                   6027:   text-align: left;
                   6028:   padding: 8px;
                   6029: }
1.795     www      6030: 
1.579     raeburn  6031: table.LC_pick_box td.LC_pick_box_select {
                   6032:   text-align: left;
                   6033:   padding: 8px;
                   6034: }
1.795     www      6035: 
1.424     albertel 6036: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6037:   padding: 0;
1.421     albertel 6038:   height: 1px;
                   6039:   background: black;
                   6040: }
1.795     www      6041: 
1.421     albertel 6042: table.LC_pick_box td.LC_pick_box_submit {
                   6043:   text-align: right;
                   6044: }
1.795     www      6045: 
1.579     raeburn  6046: table.LC_pick_box td.LC_evenrow_value {
                   6047:   text-align: left;
                   6048:   padding: 8px;
                   6049:   background-color: $data_table_light;
                   6050: }
1.795     www      6051: 
1.579     raeburn  6052: table.LC_pick_box td.LC_oddrow_value {
                   6053:   text-align: left;
                   6054:   padding: 8px;
                   6055:   background-color: $data_table_light;
                   6056: }
1.795     www      6057: 
1.579     raeburn  6058: span.LC_helpform_receipt_cat {
                   6059:   font-weight: bold;
                   6060: }
1.795     www      6061: 
1.424     albertel 6062: table.LC_group_priv_box {
                   6063:   background: white;
                   6064:   border: 1px solid black;
                   6065:   border-spacing: 1px;
                   6066: }
1.795     www      6067: 
1.424     albertel 6068: table.LC_group_priv_box td.LC_pick_box_title {
                   6069:   background: $tabbg;
                   6070:   font-weight: bold;
                   6071:   text-align: right;
                   6072:   width: 184px;
                   6073: }
1.795     www      6074: 
1.424     albertel 6075: table.LC_group_priv_box td.LC_groups_fixed {
                   6076:   background: $data_table_light;
                   6077:   text-align: center;
                   6078: }
1.795     www      6079: 
1.424     albertel 6080: table.LC_group_priv_box td.LC_groups_optional {
                   6081:   background: $data_table_dark;
                   6082:   text-align: center;
                   6083: }
1.795     www      6084: 
1.424     albertel 6085: table.LC_group_priv_box td.LC_groups_functionality {
                   6086:   background: $data_table_darker;
                   6087:   text-align: center;
                   6088:   font-weight: bold;
                   6089: }
1.795     www      6090: 
1.424     albertel 6091: table.LC_group_priv td {
                   6092:   text-align: left;
1.803     bisitz   6093:   padding: 0;
1.424     albertel 6094: }
                   6095: 
                   6096: .LC_navbuttons {
                   6097:   margin: 2ex 0ex 2ex 0ex;
                   6098: }
1.795     www      6099: 
1.423     albertel 6100: .LC_topic_bar {
                   6101:   font-weight: bold;
                   6102:   background: $tabbg;
1.918     wenzelju 6103:   margin: 1em 0em 1em 2em;
1.805     bisitz   6104:   padding: 3px;
1.918     wenzelju 6105:   font-size: 1.2em;
1.423     albertel 6106: }
1.795     www      6107: 
1.423     albertel 6108: .LC_topic_bar span {
1.918     wenzelju 6109:   left: 0.5em;
                   6110:   position: absolute;
1.423     albertel 6111:   vertical-align: middle;
1.918     wenzelju 6112:   font-size: 1.2em;
1.423     albertel 6113: }
1.795     www      6114: 
1.423     albertel 6115: table.LC_course_group_status {
                   6116:   margin: 20px;
                   6117: }
1.795     www      6118: 
1.423     albertel 6119: table.LC_status_selector td {
                   6120:   vertical-align: top;
                   6121:   text-align: center;
1.424     albertel 6122:   padding: 4px;
                   6123: }
1.795     www      6124: 
1.599     albertel 6125: div.LC_feedback_link {
1.616     albertel 6126:   clear: both;
1.829     kalberla 6127:   background: $sidebg;
1.779     bisitz   6128:   width: 100%;
1.829     kalberla 6129:   padding-bottom: 10px;
                   6130:   border: 1px $tabbg solid;
1.833     kalberla 6131:   height: 22px;
                   6132:   line-height: 22px;
                   6133:   padding-top: 5px;
                   6134: }
                   6135: 
                   6136: div.LC_feedback_link img {
                   6137:   height: 22px;
1.867     kalberla 6138:   vertical-align:middle;
1.829     kalberla 6139: }
                   6140: 
1.911     bisitz   6141: div.LC_feedback_link a {
1.829     kalberla 6142:   text-decoration: none;
1.489     raeburn  6143: }
1.795     www      6144: 
1.867     kalberla 6145: div.LC_comblock {
1.911     bisitz   6146:   display:inline;
1.867     kalberla 6147:   color:$font;
                   6148:   font-size:90%;
                   6149: }
                   6150: 
                   6151: div.LC_feedback_link div.LC_comblock {
                   6152:   padding-left:5px;
                   6153: }
                   6154: 
                   6155: div.LC_feedback_link div.LC_comblock a {
                   6156:   color:$font;
                   6157: }
                   6158: 
1.489     raeburn  6159: span.LC_feedback_link {
1.858     bisitz   6160:   /* background: $feedback_link_bg; */
1.599     albertel 6161:   font-size: larger;
                   6162: }
1.795     www      6163: 
1.599     albertel 6164: span.LC_message_link {
1.858     bisitz   6165:   /* background: $feedback_link_bg; */
1.599     albertel 6166:   font-size: larger;
                   6167:   position: absolute;
                   6168:   right: 1em;
1.489     raeburn  6169: }
1.421     albertel 6170: 
1.515     albertel 6171: table.LC_prior_tries {
1.524     albertel 6172:   border: 1px solid #000000;
                   6173:   border-collapse: separate;
                   6174:   border-spacing: 1px;
1.515     albertel 6175: }
1.523     albertel 6176: 
1.515     albertel 6177: table.LC_prior_tries td {
1.524     albertel 6178:   padding: 2px;
1.515     albertel 6179: }
1.523     albertel 6180: 
                   6181: .LC_answer_correct {
1.795     www      6182:   background: lightgreen;
                   6183:   color: darkgreen;
                   6184:   padding: 6px;
1.523     albertel 6185: }
1.795     www      6186: 
1.523     albertel 6187: .LC_answer_charged_try {
1.797     www      6188:   background: #FFAAAA;
1.795     www      6189:   color: darkred;
                   6190:   padding: 6px;
1.523     albertel 6191: }
1.795     www      6192: 
1.779     bisitz   6193: .LC_answer_not_charged_try,
1.523     albertel 6194: .LC_answer_no_grade,
                   6195: .LC_answer_late {
1.795     www      6196:   background: lightyellow;
1.523     albertel 6197:   color: black;
1.795     www      6198:   padding: 6px;
1.523     albertel 6199: }
1.795     www      6200: 
1.523     albertel 6201: .LC_answer_previous {
1.795     www      6202:   background: lightblue;
                   6203:   color: darkblue;
                   6204:   padding: 6px;
1.523     albertel 6205: }
1.795     www      6206: 
1.779     bisitz   6207: .LC_answer_no_message {
1.777     tempelho 6208:   background: #FFFFFF;
                   6209:   color: black;
1.795     www      6210:   padding: 6px;
1.779     bisitz   6211: }
1.795     www      6212: 
1.779     bisitz   6213: .LC_answer_unknown {
                   6214:   background: orange;
                   6215:   color: black;
1.795     www      6216:   padding: 6px;
1.777     tempelho 6217: }
1.795     www      6218: 
1.529     albertel 6219: span.LC_prior_numerical,
                   6220: span.LC_prior_string,
                   6221: span.LC_prior_custom,
                   6222: span.LC_prior_reaction,
                   6223: span.LC_prior_math {
1.925     bisitz   6224:   font-family: $mono;
1.523     albertel 6225:   white-space: pre;
                   6226: }
                   6227: 
1.525     albertel 6228: span.LC_prior_string {
1.925     bisitz   6229:   font-family: $mono;
1.525     albertel 6230:   white-space: pre;
                   6231: }
                   6232: 
1.523     albertel 6233: table.LC_prior_option {
                   6234:   width: 100%;
                   6235:   border-collapse: collapse;
                   6236: }
1.795     www      6237: 
1.911     bisitz   6238: table.LC_prior_rank,
1.795     www      6239: table.LC_prior_match {
1.528     albertel 6240:   border-collapse: collapse;
                   6241: }
1.795     www      6242: 
1.528     albertel 6243: table.LC_prior_option tr td,
                   6244: table.LC_prior_rank tr td,
                   6245: table.LC_prior_match tr td {
1.524     albertel 6246:   border: 1px solid #000000;
1.515     albertel 6247: }
                   6248: 
1.855     bisitz   6249: .LC_nobreak {
1.544     albertel 6250:   white-space: nowrap;
1.519     raeburn  6251: }
                   6252: 
1.576     raeburn  6253: span.LC_cusr_emph {
                   6254:   font-style: italic;
                   6255: }
                   6256: 
1.633     raeburn  6257: span.LC_cusr_subheading {
                   6258:   font-weight: normal;
                   6259:   font-size: 85%;
                   6260: }
                   6261: 
1.861     bisitz   6262: div.LC_docs_entry_move {
1.859     bisitz   6263:   border: 1px solid #BBBBBB;
1.545     albertel 6264:   background: #DDDDDD;
1.861     bisitz   6265:   width: 22px;
1.859     bisitz   6266:   padding: 1px;
                   6267:   margin: 0;
1.545     albertel 6268: }
                   6269: 
1.861     bisitz   6270: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6271: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6272:   background: #DDDDDD;
                   6273:   font-size: x-small;
                   6274: }
1.795     www      6275: 
1.861     bisitz   6276: .LC_docs_entry_parameter {
                   6277:   white-space: nowrap;
                   6278: }
                   6279: 
1.544     albertel 6280: .LC_docs_copy {
1.545     albertel 6281:   color: #000099;
1.544     albertel 6282: }
1.795     www      6283: 
1.544     albertel 6284: .LC_docs_cut {
1.545     albertel 6285:   color: #550044;
1.544     albertel 6286: }
1.795     www      6287: 
1.544     albertel 6288: .LC_docs_rename {
1.545     albertel 6289:   color: #009900;
1.544     albertel 6290: }
1.795     www      6291: 
1.544     albertel 6292: .LC_docs_remove {
1.545     albertel 6293:   color: #990000;
                   6294: }
                   6295: 
1.547     albertel 6296: .LC_docs_reinit_warn,
                   6297: .LC_docs_ext_edit {
                   6298:   font-size: x-small;
                   6299: }
                   6300: 
1.545     albertel 6301: table.LC_docs_adddocs td,
                   6302: table.LC_docs_adddocs th {
                   6303:   border: 1px solid #BBBBBB;
                   6304:   padding: 4px;
                   6305:   background: #DDDDDD;
1.543     albertel 6306: }
                   6307: 
1.584     albertel 6308: table.LC_sty_begin {
                   6309:   background: #BBFFBB;
                   6310: }
1.795     www      6311: 
1.584     albertel 6312: table.LC_sty_end {
                   6313:   background: #FFBBBB;
                   6314: }
                   6315: 
1.589     raeburn  6316: table.LC_double_column {
1.803     bisitz   6317:   border-width: 0;
1.589     raeburn  6318:   border-collapse: collapse;
                   6319:   width: 100%;
                   6320:   padding: 2px;
                   6321: }
                   6322: 
                   6323: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6324:   top: 2px;
1.589     raeburn  6325:   left: 2px;
                   6326:   width: 47%;
                   6327:   vertical-align: top;
                   6328: }
                   6329: 
                   6330: table.LC_double_column tr td.LC_right_col {
                   6331:   top: 2px;
1.779     bisitz   6332:   right: 2px;
1.589     raeburn  6333:   width: 47%;
                   6334:   vertical-align: top;
                   6335: }
                   6336: 
1.591     raeburn  6337: div.LC_left_float {
                   6338:   float: left;
                   6339:   padding-right: 5%;
1.597     albertel 6340:   padding-bottom: 4px;
1.591     raeburn  6341: }
                   6342: 
                   6343: div.LC_clear_float_header {
1.597     albertel 6344:   padding-bottom: 2px;
1.591     raeburn  6345: }
                   6346: 
                   6347: div.LC_clear_float_footer {
1.597     albertel 6348:   padding-top: 10px;
1.591     raeburn  6349:   clear: both;
                   6350: }
                   6351: 
1.597     albertel 6352: div.LC_grade_show_user {
1.941     bisitz   6353: /*  border-left: 5px solid $sidebg; */
                   6354:   border-top: 5px solid #000000;
                   6355:   margin: 50px 0 0 0;
1.936     bisitz   6356:   padding: 15px 0 5px 10px;
1.597     albertel 6357: }
1.795     www      6358: 
1.936     bisitz   6359: div.LC_grade_show_user_odd_row {
1.941     bisitz   6360: /*  border-left: 5px solid #000000; */
                   6361: }
                   6362: 
                   6363: div.LC_grade_show_user div.LC_Box {
                   6364:   margin-right: 50px;
1.597     albertel 6365: }
                   6366: 
                   6367: div.LC_grade_submissions,
                   6368: div.LC_grade_message_center,
1.936     bisitz   6369: div.LC_grade_info_links {
1.597     albertel 6370:   margin: 5px;
                   6371:   width: 99%;
                   6372:   background: #FFFFFF;
                   6373: }
1.795     www      6374: 
1.597     albertel 6375: div.LC_grade_submissions_header,
1.936     bisitz   6376: div.LC_grade_message_center_header {
1.705     tempelho 6377:   font-weight: bold;
                   6378:   font-size: large;
1.597     albertel 6379: }
1.795     www      6380: 
1.597     albertel 6381: div.LC_grade_submissions_body,
1.936     bisitz   6382: div.LC_grade_message_center_body {
1.597     albertel 6383:   border: 1px solid black;
                   6384:   width: 99%;
                   6385:   background: #FFFFFF;
                   6386: }
1.795     www      6387: 
1.613     albertel 6388: table.LC_scantron_action {
                   6389:   width: 100%;
                   6390: }
1.795     www      6391: 
1.613     albertel 6392: table.LC_scantron_action tr th {
1.698     harmsja  6393:   font-weight:bold;
                   6394:   font-style:normal;
1.613     albertel 6395: }
1.795     www      6396: 
1.779     bisitz   6397: .LC_edit_problem_header,
1.614     albertel 6398: div.LC_edit_problem_footer {
1.705     tempelho 6399:   font-weight: normal;
                   6400:   font-size:  medium;
1.602     albertel 6401:   margin: 2px;
1.1060    bisitz   6402:   background-color: $sidebg;
1.600     albertel 6403: }
1.795     www      6404: 
1.600     albertel 6405: div.LC_edit_problem_header,
1.602     albertel 6406: div.LC_edit_problem_header div,
1.614     albertel 6407: div.LC_edit_problem_footer,
                   6408: div.LC_edit_problem_footer div,
1.602     albertel 6409: div.LC_edit_problem_editxml_header,
                   6410: div.LC_edit_problem_editxml_header div {
1.600     albertel 6411:   margin-top: 5px;
                   6412: }
1.795     www      6413: 
1.600     albertel 6414: div.LC_edit_problem_header_title {
1.705     tempelho 6415:   font-weight: bold;
                   6416:   font-size: larger;
1.602     albertel 6417:   background: $tabbg;
                   6418:   padding: 3px;
1.1060    bisitz   6419:   margin: 0 0 5px 0;
1.602     albertel 6420: }
1.795     www      6421: 
1.602     albertel 6422: table.LC_edit_problem_header_title {
                   6423:   width: 100%;
1.600     albertel 6424:   background: $tabbg;
1.602     albertel 6425: }
                   6426: 
                   6427: div.LC_edit_problem_discards {
                   6428:   float: left;
                   6429:   padding-bottom: 5px;
                   6430: }
1.795     www      6431: 
1.602     albertel 6432: div.LC_edit_problem_saves {
                   6433:   float: right;
                   6434:   padding-bottom: 5px;
1.600     albertel 6435: }
1.795     www      6436: 
1.911     bisitz   6437: img.stift {
1.803     bisitz   6438:   border-width: 0;
                   6439:   vertical-align: middle;
1.677     riegler  6440: }
1.680     riegler  6441: 
1.923     bisitz   6442: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6443:   vertical-align: top;
1.777     tempelho 6444: }
1.795     www      6445: 
1.716     raeburn  6446: div.LC_createcourse {
1.911     bisitz   6447:   margin: 10px 10px 10px 10px;
1.716     raeburn  6448: }
                   6449: 
1.917     raeburn  6450: .LC_dccid {
                   6451:   margin: 0.2em 0 0 0;
                   6452:   padding: 0;
                   6453:   font-size: 90%;
                   6454:   display:none;
                   6455: }
                   6456: 
1.897     wenzelju 6457: ol.LC_primary_menu a:hover,
1.721     harmsja  6458: ol#LC_MenuBreadcrumbs a:hover,
                   6459: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6460: ul#LC_secondary_menu a:hover,
1.721     harmsja  6461: .LC_FormSectionClearButton input:hover
1.795     www      6462: ul.LC_TabContent   li:hover a {
1.952     onken    6463:   color:$button_hover;
1.911     bisitz   6464:   text-decoration:none;
1.693     droeschl 6465: }
                   6466: 
1.779     bisitz   6467: h1 {
1.911     bisitz   6468:   padding: 0;
                   6469:   line-height:130%;
1.693     droeschl 6470: }
1.698     harmsja  6471: 
1.911     bisitz   6472: h2,
                   6473: h3,
                   6474: h4,
                   6475: h5,
                   6476: h6 {
                   6477:   margin: 5px 0 5px 0;
                   6478:   padding: 0;
                   6479:   line-height:130%;
1.693     droeschl 6480: }
1.795     www      6481: 
                   6482: .LC_hcell {
1.911     bisitz   6483:   padding:3px 15px 3px 15px;
                   6484:   margin: 0;
                   6485:   background-color:$tabbg;
                   6486:   color:$fontmenu;
                   6487:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6488: }
1.795     www      6489: 
1.840     bisitz   6490: .LC_Box > .LC_hcell {
1.911     bisitz   6491:   margin: 0 -10px 10px -10px;
1.835     bisitz   6492: }
                   6493: 
1.721     harmsja  6494: .LC_noBorder {
1.911     bisitz   6495:   border: 0;
1.698     harmsja  6496: }
1.693     droeschl 6497: 
1.721     harmsja  6498: .LC_FormSectionClearButton input {
1.911     bisitz   6499:   background-color:transparent;
                   6500:   border: none;
                   6501:   cursor:pointer;
                   6502:   text-decoration:underline;
1.693     droeschl 6503: }
1.763     bisitz   6504: 
                   6505: .LC_help_open_topic {
1.911     bisitz   6506:   color: #FFFFFF;
                   6507:   background-color: #EEEEFF;
                   6508:   margin: 1px;
                   6509:   padding: 4px;
                   6510:   border: 1px solid #000033;
                   6511:   white-space: nowrap;
                   6512:   /* vertical-align: middle; */
1.759     neumanie 6513: }
1.693     droeschl 6514: 
1.911     bisitz   6515: dl,
                   6516: ul,
                   6517: div,
                   6518: fieldset {
                   6519:   margin: 10px 10px 10px 0;
                   6520:   /* overflow: hidden; */
1.693     droeschl 6521: }
1.795     www      6522: 
1.838     bisitz   6523: fieldset > legend {
1.911     bisitz   6524:   font-weight: bold;
                   6525:   padding: 0 5px 0 5px;
1.838     bisitz   6526: }
                   6527: 
1.813     bisitz   6528: #LC_nav_bar {
1.911     bisitz   6529:   float: left;
1.995     raeburn  6530:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6531:   margin: 0 0 2px 0;
1.807     droeschl 6532: }
                   6533: 
1.916     droeschl 6534: #LC_realm {
                   6535:   margin: 0.2em 0 0 0;
                   6536:   padding: 0;
                   6537:   font-weight: bold;
                   6538:   text-align: center;
1.995     raeburn  6539:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6540: }
                   6541: 
1.911     bisitz   6542: #LC_nav_bar em {
                   6543:   font-weight: bold;
                   6544:   font-style: normal;
1.807     droeschl 6545: }
                   6546: 
1.897     wenzelju 6547: ol.LC_primary_menu {
1.911     bisitz   6548:   float: right;
1.934     droeschl 6549:   margin: 0;
1.1076    raeburn  6550:   padding: 0;
1.995     raeburn  6551:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6552: }
                   6553: 
1.852     droeschl 6554: ol#LC_PathBreadcrumbs {
1.911     bisitz   6555:   margin: 0;
1.693     droeschl 6556: }
                   6557: 
1.897     wenzelju 6558: ol.LC_primary_menu li {
1.1076    raeburn  6559:   color: RGB(80, 80, 80);
                   6560:   vertical-align: middle;
                   6561:   text-align: left;
                   6562:   list-style: none;
                   6563:   float: left;
                   6564: }
                   6565: 
                   6566: ol.LC_primary_menu li a {
                   6567:   display: block;
                   6568:   margin: 0;
                   6569:   padding: 0 5px 0 10px;
                   6570:   text-decoration: none;
                   6571: }
                   6572: 
                   6573: ol.LC_primary_menu li ul {
                   6574:   display: none;
                   6575:   width: 10em;
                   6576:   background-color: $data_table_light;
                   6577: }
                   6578: 
                   6579: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6580:   display: block;
                   6581:   position: absolute;
                   6582:   margin: 0;
                   6583:   padding: 0;
1.1078    raeburn  6584:   z-index: 2;
1.1076    raeburn  6585: }
                   6586: 
                   6587: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6588:   font-size: 90%;
1.911     bisitz   6589:   vertical-align: top;
1.1076    raeburn  6590:   float: none;
1.1079    raeburn  6591:   border-left: 1px solid black;
                   6592:   border-right: 1px solid black;
1.1076    raeburn  6593: }
                   6594: 
                   6595: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1078    raeburn  6596:   background-color:$data_table_light;
1.1076    raeburn  6597: }
                   6598: 
                   6599: ol.LC_primary_menu li li a:hover {
                   6600:    color:$button_hover;
                   6601:    background-color:$data_table_dark;
1.693     droeschl 6602: }
                   6603: 
1.897     wenzelju 6604: ol.LC_primary_menu li img {
1.911     bisitz   6605:   vertical-align: bottom;
1.934     droeschl 6606:   height: 1.1em;
1.1077    raeburn  6607:   margin: 0.2em 0 0 0;
1.693     droeschl 6608: }
                   6609: 
1.897     wenzelju 6610: ol.LC_primary_menu a {
1.911     bisitz   6611:   color: RGB(80, 80, 80);
                   6612:   text-decoration: none;
1.693     droeschl 6613: }
1.795     www      6614: 
1.949     droeschl 6615: ol.LC_primary_menu a.LC_new_message {
                   6616:   font-weight:bold;
                   6617:   color: darkred;
                   6618: }
                   6619: 
1.975     raeburn  6620: ol.LC_docs_parameters {
                   6621:   margin-left: 0;
                   6622:   padding: 0;
                   6623:   list-style: none;
                   6624: }
                   6625: 
                   6626: ol.LC_docs_parameters li {
                   6627:   margin: 0;
                   6628:   padding-right: 20px;
                   6629:   display: inline;
                   6630: }
                   6631: 
1.976     raeburn  6632: ol.LC_docs_parameters li:before {
                   6633:   content: "\\002022 \\0020";
                   6634: }
                   6635: 
                   6636: li.LC_docs_parameters_title {
                   6637:   font-weight: bold;
                   6638: }
                   6639: 
                   6640: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6641:   content: "";
                   6642: }
                   6643: 
1.897     wenzelju 6644: ul#LC_secondary_menu {
1.911     bisitz   6645:   clear: both;
                   6646:   color: $fontmenu;
                   6647:   background: $tabbg;
                   6648:   list-style: none;
                   6649:   padding: 0;
                   6650:   margin: 0;
                   6651:   width: 100%;
1.995     raeburn  6652:   text-align: left;
1.808     droeschl 6653: }
                   6654: 
1.897     wenzelju 6655: ul#LC_secondary_menu li {
1.911     bisitz   6656:   font-weight: bold;
                   6657:   line-height: 1.8em;
                   6658:   padding: 0 0.8em;
                   6659:   border-right: 1px solid black;
                   6660:   display: inline;
                   6661:   vertical-align: middle;
1.807     droeschl 6662: }
                   6663: 
1.847     tempelho 6664: ul.LC_TabContent {
1.911     bisitz   6665:   display:block;
                   6666:   background: $sidebg;
                   6667:   border-bottom: solid 1px $lg_border_color;
                   6668:   list-style:none;
1.1020    raeburn  6669:   margin: -1px -10px 0 -10px;
1.911     bisitz   6670:   padding: 0;
1.693     droeschl 6671: }
                   6672: 
1.795     www      6673: ul.LC_TabContent li,
                   6674: ul.LC_TabContentBigger li {
1.911     bisitz   6675:   float:left;
1.741     harmsja  6676: }
1.795     www      6677: 
1.897     wenzelju 6678: ul#LC_secondary_menu li a {
1.911     bisitz   6679:   color: $fontmenu;
                   6680:   text-decoration: none;
1.693     droeschl 6681: }
1.795     www      6682: 
1.721     harmsja  6683: ul.LC_TabContent {
1.952     onken    6684:   min-height:20px;
1.721     harmsja  6685: }
1.795     www      6686: 
                   6687: ul.LC_TabContent li {
1.911     bisitz   6688:   vertical-align:middle;
1.959     onken    6689:   padding: 0 16px 0 10px;
1.911     bisitz   6690:   background-color:$tabbg;
                   6691:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6692:   border-left: solid 1px $font;
1.721     harmsja  6693: }
1.795     www      6694: 
1.847     tempelho 6695: ul.LC_TabContent .right {
1.911     bisitz   6696:   float:right;
1.847     tempelho 6697: }
                   6698: 
1.911     bisitz   6699: ul.LC_TabContent li a,
                   6700: ul.LC_TabContent li {
                   6701:   color:rgb(47,47,47);
                   6702:   text-decoration:none;
                   6703:   font-size:95%;
                   6704:   font-weight:bold;
1.952     onken    6705:   min-height:20px;
                   6706: }
                   6707: 
1.959     onken    6708: ul.LC_TabContent li a:hover,
                   6709: ul.LC_TabContent li a:focus {
1.952     onken    6710:   color: $button_hover;
1.959     onken    6711:   background:none;
                   6712:   outline:none;
1.952     onken    6713: }
                   6714: 
                   6715: ul.LC_TabContent li:hover {
                   6716:   color: $button_hover;
                   6717:   cursor:pointer;
1.721     harmsja  6718: }
1.795     www      6719: 
1.911     bisitz   6720: ul.LC_TabContent li.active {
1.952     onken    6721:   color: $font;
1.911     bisitz   6722:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6723:   border-bottom:solid 1px #FFFFFF;
                   6724:   cursor: default;
1.744     ehlerst  6725: }
1.795     www      6726: 
1.959     onken    6727: ul.LC_TabContent li.active a {
                   6728:   color:$font;
                   6729:   background:#FFFFFF;
                   6730:   outline: none;
                   6731: }
1.1047    raeburn  6732: 
                   6733: ul.LC_TabContent li.goback {
                   6734:   float: left;
                   6735:   border-left: none;
                   6736: }
                   6737: 
1.870     tempelho 6738: #maincoursedoc {
1.911     bisitz   6739:   clear:both;
1.870     tempelho 6740: }
                   6741: 
                   6742: ul.LC_TabContentBigger {
1.911     bisitz   6743:   display:block;
                   6744:   list-style:none;
                   6745:   padding: 0;
1.870     tempelho 6746: }
                   6747: 
1.795     www      6748: ul.LC_TabContentBigger li {
1.911     bisitz   6749:   vertical-align:bottom;
                   6750:   height: 30px;
                   6751:   font-size:110%;
                   6752:   font-weight:bold;
                   6753:   color: #737373;
1.841     tempelho 6754: }
                   6755: 
1.957     onken    6756: ul.LC_TabContentBigger li.active {
                   6757:   position: relative;
                   6758:   top: 1px;
                   6759: }
                   6760: 
1.870     tempelho 6761: ul.LC_TabContentBigger li a {
1.911     bisitz   6762:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6763:   height: 30px;
                   6764:   line-height: 30px;
                   6765:   text-align: center;
                   6766:   display: block;
                   6767:   text-decoration: none;
1.958     onken    6768:   outline: none;  
1.741     harmsja  6769: }
1.795     www      6770: 
1.870     tempelho 6771: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6772:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6773:   color:$font;
1.744     ehlerst  6774: }
1.795     www      6775: 
1.870     tempelho 6776: ul.LC_TabContentBigger li b {
1.911     bisitz   6777:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6778:   display: block;
                   6779:   float: left;
                   6780:   padding: 0 30px;
1.957     onken    6781:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 6782: }
                   6783: 
1.956     onken    6784: ul.LC_TabContentBigger li:hover b {
                   6785:   color:$button_hover;
                   6786: }
                   6787: 
1.870     tempelho 6788: ul.LC_TabContentBigger li.active b {
1.911     bisitz   6789:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   6790:   color:$font;
1.957     onken    6791:   border: 0;
1.741     harmsja  6792: }
1.693     droeschl 6793: 
1.870     tempelho 6794: 
1.862     bisitz   6795: ul.LC_CourseBreadcrumbs {
                   6796:   background: $sidebg;
1.1020    raeburn  6797:   height: 2em;
1.862     bisitz   6798:   padding-left: 10px;
1.1020    raeburn  6799:   margin: 0;
1.862     bisitz   6800:   list-style-position: inside;
                   6801: }
                   6802: 
1.911     bisitz   6803: ol#LC_MenuBreadcrumbs,
1.862     bisitz   6804: ol#LC_PathBreadcrumbs {
1.911     bisitz   6805:   padding-left: 10px;
                   6806:   margin: 0;
1.933     droeschl 6807:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 6808: }
                   6809: 
1.911     bisitz   6810: ol#LC_MenuBreadcrumbs li,
                   6811: ol#LC_PathBreadcrumbs li,
1.862     bisitz   6812: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   6813:   display: inline;
1.933     droeschl 6814:   white-space: normal;  
1.693     droeschl 6815: }
                   6816: 
1.823     bisitz   6817: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   6818: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   6819:   text-decoration: none;
                   6820:   font-size:90%;
1.693     droeschl 6821: }
1.795     www      6822: 
1.969     droeschl 6823: ol#LC_MenuBreadcrumbs h1 {
                   6824:   display: inline;
                   6825:   font-size: 90%;
                   6826:   line-height: 2.5em;
                   6827:   margin: 0;
                   6828:   padding: 0;
                   6829: }
                   6830: 
1.795     www      6831: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   6832:   text-decoration:none;
                   6833:   font-size:100%;
                   6834:   font-weight:bold;
1.693     droeschl 6835: }
1.795     www      6836: 
1.840     bisitz   6837: .LC_Box {
1.911     bisitz   6838:   border: solid 1px $lg_border_color;
                   6839:   padding: 0 10px 10px 10px;
1.746     neumanie 6840: }
1.795     www      6841: 
1.1020    raeburn  6842: .LC_DocsBox {
                   6843:   border: solid 1px $lg_border_color;
                   6844:   padding: 0 0 10px 10px;
                   6845: }
                   6846: 
1.795     www      6847: .LC_AboutMe_Image {
1.911     bisitz   6848:   float:left;
                   6849:   margin-right:10px;
1.747     neumanie 6850: }
1.795     www      6851: 
                   6852: .LC_Clear_AboutMe_Image {
1.911     bisitz   6853:   clear:left;
1.747     neumanie 6854: }
1.795     www      6855: 
1.721     harmsja  6856: dl.LC_ListStyleClean dt {
1.911     bisitz   6857:   padding-right: 5px;
                   6858:   display: table-header-group;
1.693     droeschl 6859: }
                   6860: 
1.721     harmsja  6861: dl.LC_ListStyleClean dd {
1.911     bisitz   6862:   display: table-row;
1.693     droeschl 6863: }
                   6864: 
1.721     harmsja  6865: .LC_ListStyleClean,
                   6866: .LC_ListStyleSimple,
                   6867: .LC_ListStyleNormal,
1.795     www      6868: .LC_ListStyleSpecial {
1.911     bisitz   6869:   /* display:block; */
                   6870:   list-style-position: inside;
                   6871:   list-style-type: none;
                   6872:   overflow: hidden;
                   6873:   padding: 0;
1.693     droeschl 6874: }
                   6875: 
1.721     harmsja  6876: .LC_ListStyleSimple li,
                   6877: .LC_ListStyleSimple dd,
                   6878: .LC_ListStyleNormal li,
                   6879: .LC_ListStyleNormal dd,
                   6880: .LC_ListStyleSpecial li,
1.795     www      6881: .LC_ListStyleSpecial dd {
1.911     bisitz   6882:   margin: 0;
                   6883:   padding: 5px 5px 5px 10px;
                   6884:   clear: both;
1.693     droeschl 6885: }
                   6886: 
1.721     harmsja  6887: .LC_ListStyleClean li,
                   6888: .LC_ListStyleClean dd {
1.911     bisitz   6889:   padding-top: 0;
                   6890:   padding-bottom: 0;
1.693     droeschl 6891: }
                   6892: 
1.721     harmsja  6893: .LC_ListStyleSimple dd,
1.795     www      6894: .LC_ListStyleSimple li {
1.911     bisitz   6895:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 6896: }
                   6897: 
1.721     harmsja  6898: .LC_ListStyleSpecial li,
                   6899: .LC_ListStyleSpecial dd {
1.911     bisitz   6900:   list-style-type: none;
                   6901:   background-color: RGB(220, 220, 220);
                   6902:   margin-bottom: 4px;
1.693     droeschl 6903: }
                   6904: 
1.721     harmsja  6905: table.LC_SimpleTable {
1.911     bisitz   6906:   margin:5px;
                   6907:   border:solid 1px $lg_border_color;
1.795     www      6908: }
1.693     droeschl 6909: 
1.721     harmsja  6910: table.LC_SimpleTable tr {
1.911     bisitz   6911:   padding: 0;
                   6912:   border:solid 1px $lg_border_color;
1.693     droeschl 6913: }
1.795     www      6914: 
                   6915: table.LC_SimpleTable thead {
1.911     bisitz   6916:   background:rgb(220,220,220);
1.693     droeschl 6917: }
                   6918: 
1.721     harmsja  6919: div.LC_columnSection {
1.911     bisitz   6920:   display: block;
                   6921:   clear: both;
                   6922:   overflow: hidden;
                   6923:   margin: 0;
1.693     droeschl 6924: }
                   6925: 
1.721     harmsja  6926: div.LC_columnSection>* {
1.911     bisitz   6927:   float: left;
                   6928:   margin: 10px 20px 10px 0;
                   6929:   overflow:hidden;
1.693     droeschl 6930: }
1.721     harmsja  6931: 
1.795     www      6932: table em {
1.911     bisitz   6933:   font-weight: bold;
                   6934:   font-style: normal;
1.748     schulted 6935: }
1.795     www      6936: 
1.779     bisitz   6937: table.LC_tableBrowseRes,
1.795     www      6938: table.LC_tableOfContent {
1.911     bisitz   6939:   border:none;
                   6940:   border-spacing: 1px;
                   6941:   padding: 3px;
                   6942:   background-color: #FFFFFF;
                   6943:   font-size: 90%;
1.753     droeschl 6944: }
1.789     droeschl 6945: 
1.911     bisitz   6946: table.LC_tableOfContent {
                   6947:   border-collapse: collapse;
1.789     droeschl 6948: }
                   6949: 
1.771     droeschl 6950: table.LC_tableBrowseRes a,
1.768     schulted 6951: table.LC_tableOfContent a {
1.911     bisitz   6952:   background-color: transparent;
                   6953:   text-decoration: none;
1.753     droeschl 6954: }
                   6955: 
1.795     www      6956: table.LC_tableOfContent img {
1.911     bisitz   6957:   border: none;
                   6958:   height: 1.3em;
                   6959:   vertical-align: text-bottom;
                   6960:   margin-right: 0.3em;
1.753     droeschl 6961: }
1.757     schulted 6962: 
1.795     www      6963: a#LC_content_toolbar_firsthomework {
1.911     bisitz   6964:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  6965: }
                   6966: 
1.795     www      6967: a#LC_content_toolbar_everything {
1.911     bisitz   6968:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  6969: }
                   6970: 
1.795     www      6971: a#LC_content_toolbar_uncompleted {
1.911     bisitz   6972:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  6973: }
                   6974: 
1.795     www      6975: #LC_content_toolbar_clearbubbles {
1.911     bisitz   6976:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  6977: }
                   6978: 
1.795     www      6979: a#LC_content_toolbar_changefolder {
1.911     bisitz   6980:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 6981: }
                   6982: 
1.795     www      6983: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   6984:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 6985: }
                   6986: 
1.1043    raeburn  6987: a#LC_content_toolbar_edittoplevel {
                   6988:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   6989: }
                   6990: 
1.795     www      6991: ul#LC_toolbar li a:hover {
1.911     bisitz   6992:   background-position: bottom center;
1.757     schulted 6993: }
                   6994: 
1.795     www      6995: ul#LC_toolbar {
1.911     bisitz   6996:   padding: 0;
                   6997:   margin: 2px;
                   6998:   list-style:none;
                   6999:   position:relative;
                   7000:   background-color:white;
1.1082    raeburn  7001:   overflow: auto;
1.757     schulted 7002: }
                   7003: 
1.795     www      7004: ul#LC_toolbar li {
1.911     bisitz   7005:   border:1px solid white;
                   7006:   padding: 0;
                   7007:   margin: 0;
                   7008:   float: left;
                   7009:   display:inline;
                   7010:   vertical-align:middle;
1.1082    raeburn  7011:   white-space: nowrap;
1.911     bisitz   7012: }
1.757     schulted 7013: 
1.783     amueller 7014: 
1.795     www      7015: a.LC_toolbarItem {
1.911     bisitz   7016:   display:block;
                   7017:   padding: 0;
                   7018:   margin: 0;
                   7019:   height: 32px;
                   7020:   width: 32px;
                   7021:   color:white;
                   7022:   border: none;
                   7023:   background-repeat:no-repeat;
                   7024:   background-color:transparent;
1.757     schulted 7025: }
                   7026: 
1.915     droeschl 7027: ul.LC_funclist {
                   7028:     margin: 0;
                   7029:     padding: 0.5em 1em 0.5em 0;
                   7030: }
                   7031: 
1.933     droeschl 7032: ul.LC_funclist > li:first-child {
                   7033:     font-weight:bold; 
                   7034:     margin-left:0.8em;
                   7035: }
                   7036: 
1.915     droeschl 7037: ul.LC_funclist + ul.LC_funclist {
                   7038:     /* 
                   7039:        left border as a seperator if we have more than
                   7040:        one list 
                   7041:     */
                   7042:     border-left: 1px solid $sidebg;
                   7043:     /* 
                   7044:        this hides the left border behind the border of the 
                   7045:        outer box if element is wrapped to the next 'line' 
                   7046:     */
                   7047:     margin-left: -1px;
                   7048: }
                   7049: 
1.843     bisitz   7050: ul.LC_funclist li {
1.915     droeschl 7051:   display: inline;
1.782     bisitz   7052:   white-space: nowrap;
1.915     droeschl 7053:   margin: 0 0 0 25px;
                   7054:   line-height: 150%;
1.782     bisitz   7055: }
                   7056: 
1.974     wenzelju 7057: .LC_hidden {
                   7058:   display: none;
                   7059: }
                   7060: 
1.1030    www      7061: .LCmodal-overlay {
                   7062: 		position:fixed;
                   7063: 		top:0;
                   7064: 		right:0;
                   7065: 		bottom:0;
                   7066: 		left:0;
                   7067: 		height:100%;
                   7068: 		width:100%;
                   7069: 		margin:0;
                   7070: 		padding:0;
                   7071: 		background:#999;
                   7072: 		opacity:.75;
                   7073: 		filter: alpha(opacity=75);
                   7074: 		-moz-opacity: 0.75;
                   7075: 		z-index:101;
                   7076: }
                   7077: 
                   7078: * html .LCmodal-overlay {   
                   7079: 		position: absolute;
                   7080: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7081: }
                   7082: 
                   7083: .LCmodal-window {
                   7084: 		position:fixed;
                   7085: 		top:50%;
                   7086: 		left:50%;
                   7087: 		margin:0;
                   7088: 		padding:0;
                   7089: 		z-index:102;
                   7090: 	}
                   7091: 
                   7092: * html .LCmodal-window {
                   7093: 		position:absolute;
                   7094: }
                   7095: 
                   7096: .LCclose-window {
                   7097: 		position:absolute;
                   7098: 		width:32px;
                   7099: 		height:32px;
                   7100: 		right:8px;
                   7101: 		top:8px;
                   7102: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7103: 		text-indent:-99999px;
                   7104: 		overflow:hidden;
                   7105: 		cursor:pointer;
                   7106: }
                   7107: 
1.343     albertel 7108: END
                   7109: }
                   7110: 
1.306     albertel 7111: =pod
                   7112: 
                   7113: =item * &headtag()
                   7114: 
                   7115: Returns a uniform footer for LON-CAPA web pages.
                   7116: 
1.307     albertel 7117: Inputs: $title - optional title for the head
                   7118:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7119:         $args - optional arguments
1.319     albertel 7120:             force_register - if is true call registerurl so the remote is 
                   7121:                              informed
1.415     albertel 7122:             redirect       -> array ref of
                   7123:                                    1- seconds before redirect occurs
                   7124:                                    2- url to redirect to
                   7125:                                    3- whether the side effect should occur
1.315     albertel 7126:                            (side effect of setting 
                   7127:                                $env{'internal.head.redirect'} to the url 
                   7128:                                redirected too)
1.352     albertel 7129:             domain         -> force to color decorate a page for a specific
                   7130:                                domain
                   7131:             function       -> force usage of a specific rolish color scheme
                   7132:             bgcolor        -> override the default page bgcolor
1.460     albertel 7133:             no_auto_mt_title
                   7134:                            -> prevent &mt()ing the title arg
1.464     albertel 7135: 
1.306     albertel 7136: =cut
                   7137: 
                   7138: sub headtag {
1.313     albertel 7139:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7140:     
1.363     albertel 7141:     my $function = $args->{'function'} || &get_users_function();
                   7142:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7143:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.418     albertel 7144:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7145: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7146: 		   #time(),
1.418     albertel 7147: 		   $env{'environment.color.timestamp'},
1.363     albertel 7148: 		   $function,$domain,$bgcolor);
                   7149: 
1.369     www      7150:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7151: 
1.308     albertel 7152:     my $result =
                   7153: 	'<head>'.
1.461     albertel 7154: 	&font_settings();
1.319     albertel 7155: 
1.1064    raeburn  7156:     my $inhibitprint = &print_suppression();
                   7157: 
1.461     albertel 7158:     if (!$args->{'frameset'}) {
                   7159: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7160:     }
1.962     droeschl 7161:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7162:         $result .= Apache::lonxml::display_title();
1.319     albertel 7163:     }
1.436     albertel 7164:     if (!$args->{'no_nav_bar'} 
                   7165: 	&& !$args->{'only_body'}
                   7166: 	&& !$args->{'frameset'}) {
                   7167: 	$result .= &help_menu_js();
1.1032    www      7168:         $result.=&modal_window();
1.1038    www      7169:         $result.=&togglebox_script();
1.1034    www      7170:         $result.=&wishlist_window();
1.1041    www      7171:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7172:     } else {
                   7173:         if ($args->{'add_modal'}) {
                   7174:            $result.=&modal_window();
                   7175:         }
                   7176:         if ($args->{'add_wishlist'}) {
                   7177:            $result.=&wishlist_window();
                   7178:         }
1.1038    www      7179:         if ($args->{'add_togglebox'}) {
                   7180:            $result.=&togglebox_script();
                   7181:         }
1.1041    www      7182:         if ($args->{'add_progressbar'}) {
                   7183:            $result.=&LCprogressbarUpdate_script();
                   7184:         }
1.436     albertel 7185:     }
1.314     albertel 7186:     if (ref($args->{'redirect'})) {
1.414     albertel 7187: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7188: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7189: 	if (!$inhibit_continue) {
                   7190: 	    $env{'internal.head.redirect'} = $url;
                   7191: 	}
1.313     albertel 7192: 	$result.=<<ADDMETA
                   7193: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7194: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7195: ADDMETA
                   7196:     }
1.306     albertel 7197:     if (!defined($title)) {
                   7198: 	$title = 'The LearningOnline Network with CAPA';
                   7199:     }
1.460     albertel 7200:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7201:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.414     albertel 7202: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'" />'
1.1064    raeburn  7203:         .$inhibitprint
1.414     albertel 7204: 	.$head_extra;
1.962     droeschl 7205:     return $result.'</head>';
1.306     albertel 7206: }
                   7207: 
                   7208: =pod
                   7209: 
1.340     albertel 7210: =item * &font_settings()
                   7211: 
                   7212: Returns neccessary <meta> to set the proper encoding
                   7213: 
                   7214: Inputs: none
                   7215: 
                   7216: =cut
                   7217: 
                   7218: sub font_settings {
                   7219:     my $headerstring='';
1.647     www      7220:     if (!$env{'browser.mathml'} && $env{'browser.unicode'}) {
1.340     albertel 7221: 	$headerstring.=
                   7222: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />';
                   7223:     }
                   7224:     return $headerstring;
                   7225: }
                   7226: 
1.341     albertel 7227: =pod
                   7228: 
1.1064    raeburn  7229: =item * &print_suppression()
                   7230: 
                   7231: In course context returns css which causes the body to be blank when media="print",
                   7232: if printout generation is unavailable for the current resource.
                   7233: 
                   7234: This could be because:
                   7235: 
                   7236: (a) printstartdate is in the future
                   7237: 
                   7238: (b) printenddate is in the past
                   7239: 
                   7240: (c) there is an active exam block with "printout"
                   7241: functionality blocked
                   7242: 
                   7243: Users with pav, pfo or evb privileges are exempt.
                   7244: 
                   7245: Inputs: none
                   7246: 
                   7247: =cut
                   7248: 
                   7249: 
                   7250: sub print_suppression {
                   7251:     my $noprint;
                   7252:     if ($env{'request.course.id'}) {
                   7253:         my $scope = $env{'request.course.id'};
                   7254:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7255:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7256:             return;
                   7257:         }
                   7258:         if ($env{'request.course.sec'} ne '') {
                   7259:             $scope .= "/$env{'request.course.sec'}";
                   7260:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7261:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7262:                 return;
1.1064    raeburn  7263:             }
                   7264:         }
                   7265:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7266:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1065    raeburn  7267:         my $blocked = &blocking_status('printout',$cnum,$cdom);
1.1064    raeburn  7268:         if ($blocked) {
                   7269:             my $checkrole = "cm./$cdom/$cnum";
                   7270:             if ($env{'request.course.sec'} ne '') {
                   7271:                 $checkrole .= "/$env{'request.course.sec'}";
                   7272:             }
                   7273:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7274:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7275:                 $noprint = 1;
                   7276:             }
                   7277:         }
                   7278:         unless ($noprint) {
                   7279:             my $symb = &Apache::lonnet::symbread();
                   7280:             if ($symb ne '') {
                   7281:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7282:                 if (ref($navmap)) {
                   7283:                     my $res = $navmap->getBySymb($symb);
                   7284:                     if (ref($res)) {
                   7285:                         if (!$res->resprintable()) {
                   7286:                             $noprint = 1;
                   7287:                         }
                   7288:                     }
                   7289:                 }
                   7290:             }
                   7291:         }
                   7292:         if ($noprint) {
                   7293:             return <<"ENDSTYLE";
                   7294: <style type="text/css" media="print">
                   7295:     body { display:none }
                   7296: </style>
                   7297: ENDSTYLE
                   7298:         }
                   7299:     }
                   7300:     return;
                   7301: }
                   7302: 
                   7303: =pod
                   7304: 
1.341     albertel 7305: =item * &xml_begin()
                   7306: 
                   7307: Returns the needed doctype and <html>
                   7308: 
                   7309: Inputs: none
                   7310: 
                   7311: =cut
                   7312: 
                   7313: sub xml_begin {
                   7314:     my $output='';
                   7315: 
                   7316:     if ($env{'browser.mathml'}) {
                   7317: 	$output='<?xml version="1.0"?>'
                   7318:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7319: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7320:             
                   7321: #	    .'<!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">] >'
                   7322: 	    .'<!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">'
                   7323:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7324: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
                   7325:     } else {
1.849     bisitz   7326: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'
                   7327:            .'<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">';
1.341     albertel 7328:     }
                   7329:     return $output;
                   7330: }
1.340     albertel 7331: 
                   7332: =pod
                   7333: 
1.306     albertel 7334: =item * &start_page()
                   7335: 
                   7336: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7337: 
1.648     raeburn  7338: Inputs:
                   7339: 
                   7340: =over 4
                   7341: 
                   7342: $title - optional title for the page
                   7343: 
                   7344: $head_extra - optional extra HTML to incude inside the <head>
                   7345: 
                   7346: $args - additional optional args supported are:
                   7347: 
                   7348: =over 8
                   7349: 
                   7350:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7351:                                     arg on
1.814     bisitz   7352:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7353:              add_entries    -> additional attributes to add to the  <body>
                   7354:              domain         -> force to color decorate a page for a 
1.317     albertel 7355:                                     specific domain
1.648     raeburn  7356:              function       -> force usage of a specific rolish color
1.317     albertel 7357:                                     scheme
1.648     raeburn  7358:              redirect       -> see &headtag()
                   7359:              bgcolor        -> override the default page bg color
                   7360:              js_ready       -> return a string ready for being used in 
1.317     albertel 7361:                                     a javascript writeln
1.648     raeburn  7362:              html_encode    -> return a string ready for being used in 
1.320     albertel 7363:                                     a html attribute
1.648     raeburn  7364:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7365:                                     $forcereg arg
1.648     raeburn  7366:              frameset       -> if true will start with a <frameset>
1.330     albertel 7367:                                     rather than <body>
1.648     raeburn  7368:              skip_phases    -> hash ref of 
1.338     albertel 7369:                                     head -> skip the <html><head> generation
                   7370:                                     body -> skip all <body> generation
1.648     raeburn  7371:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7372:              inherit_jsmath -> when creating popup window in a page,
                   7373:                                     should it have jsmath forced on by the
                   7374:                                     current page
1.867     kalberla 7375:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7376:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.361     albertel 7377: 
1.648     raeburn  7378: =back
1.460     albertel 7379: 
1.648     raeburn  7380: =back
1.562     albertel 7381: 
1.306     albertel 7382: =cut
                   7383: 
                   7384: sub start_page {
1.309     albertel 7385:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7386:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7387: 
1.315     albertel 7388:     $env{'internal.start_page'}++;
1.338     albertel 7389:     my $result;
1.964     droeschl 7390: 
1.338     albertel 7391:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1030    www      7392:         $result .= &xml_begin() . &headtag($title, $head_extra, $args);
1.338     albertel 7393:     }
                   7394:     
                   7395:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7396: 	if ($args->{'frameset'}) {
                   7397: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7398: 						$args->{'add_entries'});
                   7399: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7400:         } else {
                   7401:             $result .=
                   7402:                 &bodytag($title, 
                   7403:                          $args->{'function'},       $args->{'add_entries'},
                   7404:                          $args->{'only_body'},      $args->{'domain'},
                   7405:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.962     droeschl 7406:                          $args->{'bgcolor'},        $args);
1.831     bisitz   7407:         }
1.330     albertel 7408:     }
1.338     albertel 7409: 
1.315     albertel 7410:     if ($args->{'js_ready'}) {
1.713     kaisler  7411: 		$result = &js_ready($result);
1.315     albertel 7412:     }
1.320     albertel 7413:     if ($args->{'html_encode'}) {
1.713     kaisler  7414: 		$result = &html_encode($result);
                   7415:     }
                   7416: 
1.813     bisitz   7417:     # Preparation for new and consistent functionlist at top of screen
                   7418:     # if ($args->{'functionlist'}) {
                   7419:     #            $result .= &build_functionlist();
                   7420:     #}
                   7421: 
1.964     droeschl 7422:     # Don't add anything more if only_body wanted or in const space
                   7423:     return $result if    $args->{'only_body'} 
                   7424:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7425: 
                   7426:     #Breadcrumbs
1.758     kaisler  7427:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7428: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7429: 		#if any br links exists, add them to the breadcrumbs
                   7430: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7431: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7432: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7433: 			}
                   7434: 		}
                   7435: 
                   7436: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7437: 		if(exists($args->{'bread_crumbs_component'})){
                   7438: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7439: 		}else{
                   7440: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7441: 		}
1.320     albertel 7442:     }
1.315     albertel 7443:     return $result;
1.306     albertel 7444: }
                   7445: 
                   7446: sub end_page {
1.315     albertel 7447:     my ($args) = @_;
                   7448:     $env{'internal.end_page'}++;
1.330     albertel 7449:     my $result;
1.335     albertel 7450:     if ($args->{'discussion'}) {
                   7451: 	my ($target,$parser);
                   7452: 	if (ref($args->{'discussion'})) {
                   7453: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7454: 				$args->{'discussion'}{'parser'});
                   7455: 	}
                   7456: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7457:     }
1.330     albertel 7458:     if ($args->{'frameset'}) {
                   7459: 	$result .= '</frameset>';
                   7460:     } else {
1.635     raeburn  7461: 	$result .= &endbodytag($args);
1.330     albertel 7462:     }
1.1080    raeburn  7463:     unless ($args->{'notbody'}) {
                   7464:         $result .= "\n</html>";
                   7465:     }
1.330     albertel 7466: 
1.315     albertel 7467:     if ($args->{'js_ready'}) {
1.317     albertel 7468: 	$result = &js_ready($result);
1.315     albertel 7469:     }
1.335     albertel 7470: 
1.320     albertel 7471:     if ($args->{'html_encode'}) {
                   7472: 	$result = &html_encode($result);
                   7473:     }
1.335     albertel 7474: 
1.315     albertel 7475:     return $result;
                   7476: }
                   7477: 
1.1034    www      7478: sub wishlist_window {
                   7479:     return(<<'ENDWISHLIST');
1.1046    raeburn  7480: <script type="text/javascript">
1.1034    www      7481: // <![CDATA[
                   7482: // <!-- BEGIN LON-CAPA Internal
                   7483: function set_wishlistlink(title, path) {
                   7484:     if (!title) {
                   7485:         title = document.title;
                   7486:         title = title.replace(/^LON-CAPA /,'');
                   7487:     }
                   7488:     if (!path) {
                   7489:         path = location.pathname;
                   7490:     }
                   7491:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7492:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7493: }
                   7494: // END LON-CAPA Internal -->
                   7495: // ]]>
                   7496: </script>
                   7497: ENDWISHLIST
                   7498: }
                   7499: 
1.1030    www      7500: sub modal_window {
                   7501:     return(<<'ENDMODAL');
1.1046    raeburn  7502: <script type="text/javascript">
1.1030    www      7503: // <![CDATA[
                   7504: // <!-- BEGIN LON-CAPA Internal
                   7505: var modalWindow = {
                   7506: 	parent:"body",
                   7507: 	windowId:null,
                   7508: 	content:null,
                   7509: 	width:null,
                   7510: 	height:null,
                   7511: 	close:function()
                   7512: 	{
                   7513: 	        $(".LCmodal-window").remove();
                   7514: 	        $(".LCmodal-overlay").remove();
                   7515: 	},
                   7516: 	open:function()
                   7517: 	{
                   7518: 		var modal = "";
                   7519: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7520: 		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;\">";
                   7521: 		modal += this.content;
                   7522: 		modal += "</div>";	
                   7523: 
                   7524: 		$(this.parent).append(modal);
                   7525: 
                   7526: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7527: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7528: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7529: 	}
                   7530: };
1.1031    www      7531: 	var openMyModal = function(source,width,height,scrolling)
1.1030    www      7532: 	{
                   7533: 		modalWindow.windowId = "myModal";
                   7534: 		modalWindow.width = width;
                   7535: 		modalWindow.height = height;
1.1031    www      7536: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='true' src='" + source + "'>&lt/iframe>";
1.1030    www      7537: 		modalWindow.open();
                   7538: 	};	
                   7539: // END LON-CAPA Internal -->
                   7540: // ]]>
                   7541: </script>
                   7542: ENDMODAL
                   7543: }
                   7544: 
                   7545: sub modal_link {
1.1052    www      7546:     my ($link,$linktext,$width,$height,$target,$scrolling,$title)=@_;
1.1030    www      7547:     unless ($width) { $width=480; }
                   7548:     unless ($height) { $height=400; }
1.1031    www      7549:     unless ($scrolling) { $scrolling='yes'; }
1.1074    raeburn  7550:     my $target_attr;
                   7551:     if (defined($target)) {
                   7552:         $target_attr = 'target="'.$target.'"';
                   7553:     }
                   7554:     return <<"ENDLINK";
                   7555: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling'); return false;">
                   7556:            $linktext</a>
                   7557: ENDLINK
1.1030    www      7558: }
                   7559: 
1.1032    www      7560: sub modal_adhoc_script {
                   7561:     my ($funcname,$width,$height,$content)=@_;
                   7562:     return (<<ENDADHOC);
1.1046    raeburn  7563: <script type="text/javascript">
1.1032    www      7564: // <![CDATA[
                   7565:         var $funcname = function()
                   7566:         {
                   7567:                 modalWindow.windowId = "myModal";
                   7568:                 modalWindow.width = $width;
                   7569:                 modalWindow.height = $height;
                   7570:                 modalWindow.content = '$content';
                   7571:                 modalWindow.open();
                   7572:         };  
                   7573: // ]]>
                   7574: </script>
                   7575: ENDADHOC
                   7576: }
                   7577: 
1.1041    www      7578: sub modal_adhoc_inner {
                   7579:     my ($funcname,$width,$height,$content)=@_;
                   7580:     my $innerwidth=$width-20;
                   7581:     $content=&js_ready(
1.1042    www      7582:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1041    www      7583:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px').
                   7584:                     $content.
                   7585:                  &end_scrollbox().
                   7586:                &end_page()
                   7587:              );
                   7588:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7589: }
                   7590: 
                   7591: sub modal_adhoc_window {
                   7592:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7593:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7594:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7595: }
                   7596: 
                   7597: sub modal_adhoc_launch {
                   7598:     my ($funcname,$width,$height,$content)=@_;
                   7599:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7600: <script type="text/javascript">
                   7601: // <![CDATA[
                   7602: $funcname();
                   7603: // ]]>
                   7604: </script>
                   7605: ENDLAUNCH
                   7606: }
                   7607: 
                   7608: sub modal_adhoc_close {
                   7609:     return (<<ENDCLOSE);
                   7610: <script type="text/javascript">
                   7611: // <![CDATA[
                   7612: modalWindow.close();
                   7613: // ]]>
                   7614: </script>
                   7615: ENDCLOSE
                   7616: }
                   7617: 
1.1038    www      7618: sub togglebox_script {
                   7619:    return(<<ENDTOGGLE);
                   7620: <script type="text/javascript"> 
                   7621: // <![CDATA[
                   7622: function LCtoggleDisplay(id,hidetext,showtext) {
                   7623:    link = document.getElementById(id + "link").childNodes[0];
                   7624:    with (document.getElementById(id).style) {
                   7625:       if (display == "none" ) {
                   7626:           display = "inline";
                   7627:           link.nodeValue = hidetext;
                   7628:         } else {
                   7629:           display = "none";
                   7630:           link.nodeValue = showtext;
                   7631:        }
                   7632:    }
                   7633: }
                   7634: // ]]>
                   7635: </script>
                   7636: ENDTOGGLE
                   7637: }
                   7638: 
1.1039    www      7639: sub start_togglebox {
                   7640:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7641:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7642:     unless ($showtext) { $showtext=&mt('show'); }
                   7643:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   7644:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   7645:     return &start_data_table().
                   7646:            &start_data_table_header_row().
                   7647:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   7648:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   7649:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   7650:            &end_data_table_header_row().
                   7651:            '<tr id="'.$id.'" style="display:none""><td>';
                   7652: }
                   7653: 
                   7654: sub end_togglebox {
                   7655:     return '</td></tr>'.&end_data_table();
                   7656: }
                   7657: 
1.1041    www      7658: sub LCprogressbar_script {
1.1045    www      7659:    my ($id)=@_;
1.1041    www      7660:    return(<<ENDPROGRESS);
                   7661: <script type="text/javascript">
                   7662: // <![CDATA[
1.1045    www      7663: \$('#progressbar$id').progressbar({
1.1041    www      7664:   value: 0,
                   7665:   change: function(event, ui) {
                   7666:     var newVal = \$(this).progressbar('option', 'value');
                   7667:     \$('.pblabel', this).text(LCprogressTxt);
                   7668:   }
                   7669: });
                   7670: // ]]>
                   7671: </script>
                   7672: ENDPROGRESS
                   7673: }
                   7674: 
                   7675: sub LCprogressbarUpdate_script {
                   7676:    return(<<ENDPROGRESSUPDATE);
                   7677: <style type="text/css">
                   7678: .ui-progressbar { position:relative; }
                   7679: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   7680: </style>
                   7681: <script type="text/javascript">
                   7682: // <![CDATA[
1.1045    www      7683: var LCprogressTxt='---';
                   7684: 
                   7685: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      7686:    LCprogressTxt=progresstext;
1.1045    www      7687:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      7688: }
                   7689: // ]]>
                   7690: </script>
                   7691: ENDPROGRESSUPDATE
                   7692: }
                   7693: 
1.1042    www      7694: my $LClastpercent;
1.1045    www      7695: my $LCidcnt;
                   7696: my $LCcurrentid;
1.1042    www      7697: 
1.1041    www      7698: sub LCprogressbar {
1.1042    www      7699:     my ($r)=(@_);
                   7700:     $LClastpercent=0;
1.1045    www      7701:     $LCidcnt++;
                   7702:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      7703:     my $starting=&mt('Starting');
                   7704:     my $content=(<<ENDPROGBAR);
                   7705: <p>
1.1045    www      7706:   <div id="progressbar$LCcurrentid">
1.1041    www      7707:     <span class="pblabel">$starting</span>
                   7708:   </div>
                   7709: </p>
                   7710: ENDPROGBAR
1.1045    www      7711:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      7712: }
                   7713: 
                   7714: sub LCprogressbarUpdate {
1.1042    www      7715:     my ($r,$val,$text)=@_;
                   7716:     unless ($val) { 
                   7717:        if ($LClastpercent) {
                   7718:            $val=$LClastpercent;
                   7719:        } else {
                   7720:            $val=0;
                   7721:        }
                   7722:     }
1.1041    www      7723:     if ($val<0) { $val=0; }
                   7724:     if ($val>100) { $val=0; }
1.1042    www      7725:     $LClastpercent=$val;
1.1041    www      7726:     unless ($text) { $text=$val.'%'; }
                   7727:     $text=&js_ready($text);
1.1044    www      7728:     &r_print($r,<<ENDUPDATE);
1.1041    www      7729: <script type="text/javascript">
                   7730: // <![CDATA[
1.1045    www      7731: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      7732: // ]]>
                   7733: </script>
                   7734: ENDUPDATE
1.1035    www      7735: }
                   7736: 
1.1042    www      7737: sub LCprogressbarClose {
                   7738:     my ($r)=@_;
                   7739:     $LClastpercent=0;
1.1044    www      7740:     &r_print($r,<<ENDCLOSE);
1.1042    www      7741: <script type="text/javascript">
                   7742: // <![CDATA[
1.1045    www      7743: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      7744: // ]]>
                   7745: </script>
                   7746: ENDCLOSE
1.1044    www      7747: }
                   7748: 
                   7749: sub r_print {
                   7750:     my ($r,$to_print)=@_;
                   7751:     if ($r) {
                   7752:       $r->print($to_print);
                   7753:       $r->rflush();
                   7754:     } else {
                   7755:       print($to_print);
                   7756:     }
1.1042    www      7757: }
                   7758: 
1.320     albertel 7759: sub html_encode {
                   7760:     my ($result) = @_;
                   7761: 
1.322     albertel 7762:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 7763:     
                   7764:     return $result;
                   7765: }
1.1044    www      7766: 
1.317     albertel 7767: sub js_ready {
                   7768:     my ($result) = @_;
                   7769: 
1.323     albertel 7770:     $result =~ s/[\n\r]/ /xmsg;
                   7771:     $result =~ s/\\/\\\\/xmsg;
                   7772:     $result =~ s/'/\\'/xmsg;
1.372     albertel 7773:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 7774:     
                   7775:     return $result;
                   7776: }
                   7777: 
1.315     albertel 7778: sub validate_page {
                   7779:     if (  exists($env{'internal.start_page'})
1.316     albertel 7780: 	  &&     $env{'internal.start_page'} > 1) {
                   7781: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 7782: 				 $env{'internal.start_page'}.' '.
1.316     albertel 7783: 				 $ENV{'request.filename'});
1.315     albertel 7784:     }
                   7785:     if (  exists($env{'internal.end_page'})
1.316     albertel 7786: 	  &&     $env{'internal.end_page'} > 1) {
                   7787: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 7788: 				 $env{'internal.end_page'}.' '.
1.316     albertel 7789: 				 $env{'request.filename'});
1.315     albertel 7790:     }
                   7791:     if (     exists($env{'internal.start_page'})
                   7792: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 7793: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   7794: 				 $env{'request.filename'});
1.315     albertel 7795:     }
                   7796:     if (   ! exists($env{'internal.start_page'})
                   7797: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 7798: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   7799: 				 $env{'request.filename'});
1.315     albertel 7800:     }
1.306     albertel 7801: }
1.315     albertel 7802: 
1.996     www      7803: 
                   7804: sub start_scrollbox {
1.1075    raeburn  7805:     my ($outerwidth,$width,$height,$id,$bgcolor)=@_;
1.998     raeburn  7806:     unless ($outerwidth) { $outerwidth='520px'; }
                   7807:     unless ($width) { $width='500px'; }
                   7808:     unless ($height) { $height='200px'; }
1.1075    raeburn  7809:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  7810:     if ($id ne '') {
1.1020    raeburn  7811:         $table_id = " id='table_$id'";
                   7812:         $div_id = " id='div_$id'";
1.1018    raeburn  7813:     }
1.1075    raeburn  7814:     if ($bgcolor ne '') {
                   7815:         $tdcol = "background-color: $bgcolor;";
                   7816:     }
                   7817:     return <<"END";
                   7818: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol"><div style="overflow:auto; width:$width; height: $height;"$div_id>
                   7819: END
1.996     www      7820: }
                   7821: 
                   7822: sub end_scrollbox {
1.1036    www      7823:     return '</div></td></tr></table>';
1.996     www      7824: }
                   7825: 
1.318     albertel 7826: sub simple_error_page {
                   7827:     my ($r,$title,$msg) = @_;
                   7828:     my $page =
                   7829: 	&Apache::loncommon::start_page($title).
                   7830: 	&mt($msg).
                   7831: 	&Apache::loncommon::end_page();
                   7832:     if (ref($r)) {
                   7833: 	$r->print($page);
1.327     albertel 7834: 	return;
1.318     albertel 7835:     }
                   7836:     return $page;
                   7837: }
1.347     albertel 7838: 
                   7839: {
1.610     albertel 7840:     my @row_count;
1.961     onken    7841: 
                   7842:     sub start_data_table_count {
                   7843:         unshift(@row_count, 0);
                   7844:         return;
                   7845:     }
                   7846: 
                   7847:     sub end_data_table_count {
                   7848:         shift(@row_count);
                   7849:         return;
                   7850:     }
                   7851: 
1.347     albertel 7852:     sub start_data_table {
1.1018    raeburn  7853: 	my ($add_class,$id) = @_;
1.422     albertel 7854: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  7855:         my $table_id;
                   7856:         if (defined($id)) {
                   7857:             $table_id = ' id="'.$id.'"';
                   7858:         }
1.961     onken    7859: 	&start_data_table_count();
1.1018    raeburn  7860: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 7861:     }
                   7862: 
                   7863:     sub end_data_table {
1.961     onken    7864: 	&end_data_table_count();
1.389     albertel 7865: 	return '</table>'."\n";;
1.347     albertel 7866:     }
                   7867: 
                   7868:     sub start_data_table_row {
1.974     wenzelju 7869: 	my ($add_class, $id) = @_;
1.610     albertel 7870: 	$row_count[0]++;
                   7871: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   7872: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 7873:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7874:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 7875:     }
1.471     banghart 7876:     
                   7877:     sub continue_data_table_row {
1.974     wenzelju 7878: 	my ($add_class, $id) = @_;
1.610     albertel 7879: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 7880: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   7881:         $id = (' id="'.$id.'"') unless ($id eq '');
                   7882:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 7883:     }
1.347     albertel 7884: 
                   7885:     sub end_data_table_row {
1.389     albertel 7886: 	return '</tr>'."\n";;
1.347     albertel 7887:     }
1.367     www      7888: 
1.421     albertel 7889:     sub start_data_table_empty_row {
1.707     bisitz   7890: #	$row_count[0]++;
1.421     albertel 7891: 	return  '<tr class="LC_empty_row" >'."\n";;
                   7892:     }
                   7893: 
                   7894:     sub end_data_table_empty_row {
                   7895: 	return '</tr>'."\n";;
                   7896:     }
                   7897: 
1.367     www      7898:     sub start_data_table_header_row {
1.389     albertel 7899: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      7900:     }
                   7901: 
                   7902:     sub end_data_table_header_row {
1.389     albertel 7903: 	return '</tr>'."\n";;
1.367     www      7904:     }
1.890     droeschl 7905: 
                   7906:     sub data_table_caption {
                   7907:         my $caption = shift;
                   7908:         return "<caption class=\"LC_caption\">$caption</caption>";
                   7909:     }
1.347     albertel 7910: }
                   7911: 
1.548     albertel 7912: =pod
                   7913: 
                   7914: =item * &inhibit_menu_check($arg)
                   7915: 
                   7916: Checks for a inhibitmenu state and generates output to preserve it
                   7917: 
                   7918: Inputs:         $arg - can be any of
                   7919:                      - undef - in which case the return value is a string 
                   7920:                                to add  into arguments list of a uri
                   7921:                      - 'input' - in which case the return value is a HTML
                   7922:                                  <form> <input> field of type hidden to
                   7923:                                  preserve the value
                   7924:                      - a url - in which case the return value is the url with
                   7925:                                the neccesary cgi args added to preserve the
                   7926:                                inhibitmenu state
                   7927:                      - a ref to a url - no return value, but the string is
                   7928:                                         updated to include the neccessary cgi
                   7929:                                         args to preserve the inhibitmenu state
                   7930: 
                   7931: =cut
                   7932: 
                   7933: sub inhibit_menu_check {
                   7934:     my ($arg) = @_;
                   7935:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   7936:     if ($arg eq 'input') {
                   7937: 	if ($env{'form.inhibitmenu'}) {
                   7938: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   7939: 	} else {
                   7940: 	    return
                   7941: 	}
                   7942:     }
                   7943:     if ($env{'form.inhibitmenu'}) {
                   7944: 	if (ref($arg)) {
                   7945: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   7946: 	} elsif ($arg eq '') {
                   7947: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   7948: 	} else {
                   7949: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   7950: 	}
                   7951:     }
                   7952:     if (!ref($arg)) {
                   7953: 	return $arg;
                   7954:     }
                   7955: }
                   7956: 
1.251     albertel 7957: ###############################################
1.182     matthew  7958: 
                   7959: =pod
                   7960: 
1.549     albertel 7961: =back
                   7962: 
                   7963: =head1 User Information Routines
                   7964: 
                   7965: =over 4
                   7966: 
1.405     albertel 7967: =item * &get_users_function()
1.182     matthew  7968: 
                   7969: Used by &bodytag to determine the current users primary role.
                   7970: Returns either 'student','coordinator','admin', or 'author'.
                   7971: 
                   7972: =cut
                   7973: 
                   7974: ###############################################
                   7975: sub get_users_function {
1.815     tempelho 7976:     my $function = 'norole';
1.818     tempelho 7977:     if ($env{'request.role'}=~/^(st)/) {
                   7978:         $function='student';
                   7979:     }
1.907     raeburn  7980:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  7981:         $function='coordinator';
                   7982:     }
1.258     albertel 7983:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  7984:         $function='admin';
                   7985:     }
1.826     bisitz   7986:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  7987:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  7988:         $function='author';
                   7989:     }
                   7990:     return $function;
1.54      www      7991: }
1.99      www      7992: 
                   7993: ###############################################
                   7994: 
1.233     raeburn  7995: =pod
                   7996: 
1.821     raeburn  7997: =item * &show_course()
                   7998: 
                   7999: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8000: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8001: 
                   8002: Inputs:
                   8003: None
                   8004: 
                   8005: Outputs:
                   8006: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8007: 
                   8008: =cut
                   8009: 
                   8010: ###############################################
                   8011: sub show_course {
                   8012:     my $course = !$env{'user.adv'};
                   8013:     if (!$env{'user.adv'}) {
                   8014:         foreach my $env (keys(%env)) {
                   8015:             next if ($env !~ m/^user\.priv\./);
                   8016:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8017:                 $course = 0;
                   8018:                 last;
                   8019:             }
                   8020:         }
                   8021:     }
                   8022:     return $course;
                   8023: }
                   8024: 
                   8025: ###############################################
                   8026: 
                   8027: =pod
                   8028: 
1.542     raeburn  8029: =item * &check_user_status()
1.274     raeburn  8030: 
                   8031: Determines current status of supplied role for a
                   8032: specific user. Roles can be active, previous or future.
                   8033: 
                   8034: Inputs: 
                   8035: user's domain, user's username, course's domain,
1.375     raeburn  8036: course's number, optional section ID.
1.274     raeburn  8037: 
                   8038: Outputs:
                   8039: role status: active, previous or future. 
                   8040: 
                   8041: =cut
                   8042: 
                   8043: sub check_user_status {
1.412     raeburn  8044:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8045:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.274     raeburn  8046:     my @uroles = keys %userinfo;
                   8047:     my $srchstr;
                   8048:     my $active_chk = 'none';
1.412     raeburn  8049:     my $now = time;
1.274     raeburn  8050:     if (@uroles > 0) {
1.908     raeburn  8051:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8052:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8053:         } else {
1.412     raeburn  8054:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8055:         }
                   8056:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8057:             my $role_end = 0;
                   8058:             my $role_start = 0;
                   8059:             $active_chk = 'active';
1.412     raeburn  8060:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8061:                 $role_end = $1;
                   8062:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8063:                     $role_start = $1;
1.274     raeburn  8064:                 }
                   8065:             }
                   8066:             if ($role_start > 0) {
1.412     raeburn  8067:                 if ($now < $role_start) {
1.274     raeburn  8068:                     $active_chk = 'future';
                   8069:                 }
                   8070:             }
                   8071:             if ($role_end > 0) {
1.412     raeburn  8072:                 if ($now > $role_end) {
1.274     raeburn  8073:                     $active_chk = 'previous';
                   8074:                 }
                   8075:             }
                   8076:         }
                   8077:     }
                   8078:     return $active_chk;
                   8079: }
                   8080: 
                   8081: ###############################################
                   8082: 
                   8083: =pod
                   8084: 
1.405     albertel 8085: =item * &get_sections()
1.233     raeburn  8086: 
                   8087: Determines all the sections for a course including
                   8088: sections with students and sections containing other roles.
1.419     raeburn  8089: Incoming parameters: 
                   8090: 
                   8091: 1. domain
                   8092: 2. course number 
                   8093: 3. reference to array containing roles for which sections should 
                   8094: be gathered (optional).
                   8095: 4. reference to array containing status types for which sections 
                   8096: should be gathered (optional).
                   8097: 
                   8098: If the third argument is undefined, sections are gathered for any role. 
                   8099: If the fourth argument is undefined, sections are gathered for any status.
                   8100: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8101:  
1.374     raeburn  8102: Returns section hash (keys are section IDs, values are
                   8103: number of users in each section), subject to the
1.419     raeburn  8104: optional roles filter, optional status filter 
1.233     raeburn  8105: 
                   8106: =cut
                   8107: 
                   8108: ###############################################
                   8109: sub get_sections {
1.419     raeburn  8110:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8111:     if (!defined($cdom) || !defined($cnum)) {
                   8112:         my $cid =  $env{'request.course.id'};
                   8113: 
                   8114: 	return if (!defined($cid));
                   8115: 
                   8116:         $cdom = $env{'course.'.$cid.'.domain'};
                   8117:         $cnum = $env{'course.'.$cid.'.num'};
                   8118:     }
                   8119: 
                   8120:     my %sectioncount;
1.419     raeburn  8121:     my $now = time;
1.240     albertel 8122: 
1.366     albertel 8123:     if (!defined($possible_roles) || (grep(/^st$/,@$possible_roles))) {
1.276     albertel 8124: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8125: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8126: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8127:         my $start_index = &Apache::loncoursedata::CL_START();
                   8128:         my $end_index = &Apache::loncoursedata::CL_END();
                   8129:         my $status;
1.366     albertel 8130: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8131: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8132: 				                     $data->[$status_index],
                   8133:                                                      $data->[$start_index],
                   8134:                                                      $data->[$end_index]);
                   8135:             if ($stu_status eq 'Active') {
                   8136:                 $status = 'active';
                   8137:             } elsif ($end < $now) {
                   8138:                 $status = 'previous';
                   8139:             } elsif ($start > $now) {
                   8140:                 $status = 'future';
                   8141:             } 
                   8142: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8143:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8144:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8145: 		    $sectioncount{$section}++;
                   8146:                 }
1.240     albertel 8147: 	    }
                   8148: 	}
                   8149:     }
                   8150:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8151:     foreach my $user (sort(keys(%courseroles))) {
                   8152: 	if ($user !~ /^(\w{2})/) { next; }
                   8153: 	my ($role) = ($user =~ /^(\w{2})/);
                   8154: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8155: 	my ($section,$status);
1.240     albertel 8156: 	if ($role eq 'cr' &&
                   8157: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8158: 	    $section=$1;
                   8159: 	}
                   8160: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8161: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8162:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8163:         if ($end == -1 && $start == -1) {
                   8164:             next; #deleted role
                   8165:         }
                   8166:         if (!defined($possible_status)) { 
                   8167:             $sectioncount{$section}++;
                   8168:         } else {
                   8169:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8170:                 $status = 'active';
                   8171:             } elsif ($end < $now) {
                   8172:                 $status = 'future';
                   8173:             } elsif ($start > $now) {
                   8174:                 $status = 'previous';
                   8175:             }
                   8176:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8177:                 $sectioncount{$section}++;
                   8178:             }
                   8179:         }
1.233     raeburn  8180:     }
1.366     albertel 8181:     return %sectioncount;
1.233     raeburn  8182: }
                   8183: 
1.274     raeburn  8184: ###############################################
1.294     raeburn  8185: 
                   8186: =pod
1.405     albertel 8187: 
                   8188: =item * &get_course_users()
                   8189: 
1.275     raeburn  8190: Retrieves usernames:domains for users in the specified course
                   8191: with specific role(s), and access status. 
                   8192: 
                   8193: Incoming parameters:
1.277     albertel 8194: 1. course domain
                   8195: 2. course number
                   8196: 3. access status: users must have - either active, 
1.275     raeburn  8197: previous, future, or all.
1.277     albertel 8198: 4. reference to array of permissible roles
1.288     raeburn  8199: 5. reference to array of section restrictions (optional)
                   8200: 6. reference to results object (hash of hashes).
                   8201: 7. reference to optional userdata hash
1.609     raeburn  8202: 8. reference to optional statushash
1.630     raeburn  8203: 9. flag if privileged users (except those set to unhide in
                   8204:    course settings) should be excluded    
1.609     raeburn  8205: Keys of top level results hash are roles.
1.275     raeburn  8206: Keys of inner hashes are username:domain, with 
                   8207: values set to access type.
1.288     raeburn  8208: Optional userdata hash returns an array with arguments in the 
                   8209: same order as loncoursedata::get_classlist() for student data.
                   8210: 
1.609     raeburn  8211: Optional statushash returns
                   8212: 
1.288     raeburn  8213: Entries for end, start, section and status are blank because
                   8214: of the possibility of multiple values for non-student roles.
                   8215: 
1.275     raeburn  8216: =cut
1.405     albertel 8217: 
1.275     raeburn  8218: ###############################################
1.405     albertel 8219: 
1.275     raeburn  8220: sub get_course_users {
1.630     raeburn  8221:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8222:     my %idx = ();
1.419     raeburn  8223:     my %seclists;
1.288     raeburn  8224: 
                   8225:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8226:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8227:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8228:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8229:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8230:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8231:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8232:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8233: 
1.290     albertel 8234:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8235:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8236:         my $now = time;
1.277     albertel 8237:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8238:             my $match = 0;
1.412     raeburn  8239:             my $secmatch = 0;
1.419     raeburn  8240:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8241:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8242:             if ($section eq '') {
                   8243:                 $section = 'none';
                   8244:             }
1.291     albertel 8245:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8246:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8247:                     $secmatch = 1;
                   8248:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8249:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8250:                         $secmatch = 1;
                   8251:                     }
                   8252:                 } else {  
1.419     raeburn  8253: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8254: 		        $secmatch = 1;
                   8255:                     }
1.290     albertel 8256: 		}
1.412     raeburn  8257:                 if (!$secmatch) {
                   8258:                     next;
                   8259:                 }
1.419     raeburn  8260:             }
1.275     raeburn  8261:             if (defined($$types{'active'})) {
1.288     raeburn  8262:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8263:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8264:                     $match = 1;
1.275     raeburn  8265:                 }
                   8266:             }
                   8267:             if (defined($$types{'previous'})) {
1.609     raeburn  8268:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8269:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8270:                     $match = 1;
1.275     raeburn  8271:                 }
                   8272:             }
                   8273:             if (defined($$types{'future'})) {
1.609     raeburn  8274:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8275:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8276:                     $match = 1;
1.275     raeburn  8277:                 }
                   8278:             }
1.609     raeburn  8279:             if ($match) {
                   8280:                 push(@{$seclists{$student}},$section);
                   8281:                 if (ref($userdata) eq 'HASH') {
                   8282:                     $$userdata{$student} = $$classlist{$student};
                   8283:                 }
                   8284:                 if (ref($statushash) eq 'HASH') {
                   8285:                     $statushash->{$student}{'st'}{$section} = $status;
                   8286:                 }
1.288     raeburn  8287:             }
1.275     raeburn  8288:         }
                   8289:     }
1.412     raeburn  8290:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8291:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8292:         my $now = time;
1.609     raeburn  8293:         my %displaystatus = ( previous => 'Expired',
                   8294:                               active   => 'Active',
                   8295:                               future   => 'Future',
                   8296:                             );
1.630     raeburn  8297:         my %nothide;
                   8298:         if ($hidepriv) {
                   8299:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8300:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8301:                 if ($user !~ /:/) {
                   8302:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8303:                 } else {
                   8304:                     $nothide{$user} = 1;
                   8305:                 }
                   8306:             }
                   8307:         }
1.439     raeburn  8308:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8309:             my $match = 0;
1.412     raeburn  8310:             my $secmatch = 0;
1.439     raeburn  8311:             my $status;
1.412     raeburn  8312:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8313:             $user =~ s/:$//;
1.439     raeburn  8314:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8315:             if ($end == -1 || $start == -1) {
                   8316:                 next;
                   8317:             }
                   8318:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8319:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8320:                 my ($uname,$udom) = split(/:/,$user);
                   8321:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8322:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8323:                         $secmatch = 1;
                   8324:                     } elsif ($usec eq '') {
1.420     albertel 8325:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8326:                             $secmatch = 1;
                   8327:                         }
                   8328:                     } else {
                   8329:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8330:                             $secmatch = 1;
                   8331:                         }
                   8332:                     }
                   8333:                     if (!$secmatch) {
                   8334:                         next;
                   8335:                     }
1.288     raeburn  8336:                 }
1.419     raeburn  8337:                 if ($usec eq '') {
                   8338:                     $usec = 'none';
                   8339:                 }
1.275     raeburn  8340:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8341:                     if ($hidepriv) {
                   8342:                         if ((&Apache::lonnet::privileged($uname,$udom)) &&
                   8343:                             (!$nothide{$uname.':'.$udom})) {
                   8344:                             next;
                   8345:                         }
                   8346:                     }
1.503     raeburn  8347:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8348:                         $status = 'previous';
                   8349:                     } elsif ($start > $now) {
                   8350:                         $status = 'future';
                   8351:                     } else {
                   8352:                         $status = 'active';
                   8353:                     }
1.277     albertel 8354:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8355:                         if ($status eq $type) {
1.420     albertel 8356:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8357:                                 push(@{$$users{$role}{$user}},$type);
                   8358:                             }
1.288     raeburn  8359:                             $match = 1;
                   8360:                         }
                   8361:                     }
1.419     raeburn  8362:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8363:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8364: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8365:                         }
1.420     albertel 8366:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8367:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8368:                         }
1.609     raeburn  8369:                         if (ref($statushash) eq 'HASH') {
                   8370:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8371:                         }
1.275     raeburn  8372:                     }
                   8373:                 }
                   8374:             }
                   8375:         }
1.290     albertel 8376:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8377:             if ((defined($cdom)) && (defined($cnum))) {
                   8378:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8379:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8380:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8381:                     next if ($owner eq '');
                   8382:                     my ($ownername,$ownerdom);
                   8383:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8384:                         $ownername = $1;
                   8385:                         $ownerdom = $2;
                   8386:                     } else {
                   8387:                         $ownername = $owner;
                   8388:                         $ownerdom = $cdom;
                   8389:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8390:                     }
                   8391:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8392:                     if (defined($userdata) && 
1.609     raeburn  8393: 			!exists($$userdata{$owner})) {
                   8394: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8395:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8396:                             push(@{$seclists{$owner}},'none');
                   8397:                         }
                   8398:                         if (ref($statushash) eq 'HASH') {
                   8399:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8400:                         }
1.290     albertel 8401: 		    }
1.279     raeburn  8402:                 }
                   8403:             }
                   8404:         }
1.419     raeburn  8405:         foreach my $user (keys(%seclists)) {
                   8406:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8407:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8408:         }
1.275     raeburn  8409:     }
                   8410:     return;
                   8411: }
                   8412: 
1.288     raeburn  8413: sub get_user_info {
                   8414:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8415:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8416: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8417:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8418:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8419:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8420:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8421:     return;
                   8422: }
1.275     raeburn  8423: 
1.472     raeburn  8424: ###############################################
                   8425: 
                   8426: =pod
                   8427: 
                   8428: =item * &get_user_quota()
                   8429: 
                   8430: Retrieves quota assigned for storage of portfolio files for a user  
                   8431: 
                   8432: Incoming parameters:
                   8433: 1. user's username
                   8434: 2. user's domain
                   8435: 
                   8436: Returns:
1.536     raeburn  8437: 1. Disk quota (in Mb) assigned to student.
                   8438: 2. (Optional) Type of setting: custom or default
                   8439:    (individually assigned or default for user's 
                   8440:    institutional status).
                   8441: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8442:    or student - types as defined in localenroll::inst_usertypes 
                   8443:    for user's domain, which determines default quota for user.
                   8444: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8445: 
                   8446: If a value has been stored in the user's environment, 
1.536     raeburn  8447: it will return that, otherwise it returns the maximal default
                   8448: defined for the user's instituional status(es) in the domain.
1.472     raeburn  8449: 
                   8450: =cut
                   8451: 
                   8452: ###############################################
                   8453: 
                   8454: 
                   8455: sub get_user_quota {
                   8456:     my ($uname,$udom) = @_;
1.536     raeburn  8457:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8458:     if (!defined($udom)) {
                   8459:         $udom = $env{'user.domain'};
                   8460:     }
                   8461:     if (!defined($uname)) {
                   8462:         $uname = $env{'user.name'};
                   8463:     }
                   8464:     if (($udom eq '' || $uname eq '') ||
                   8465:         ($udom eq 'public') && ($uname eq 'public')) {
                   8466:         $quota = 0;
1.536     raeburn  8467:         $quotatype = 'default';
                   8468:         $defquota = 0; 
1.472     raeburn  8469:     } else {
1.536     raeburn  8470:         my $inststatus;
1.472     raeburn  8471:         if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8472:             $quota = $env{'environment.portfolioquota'};
1.536     raeburn  8473:             $inststatus = $env{'environment.inststatus'};
1.472     raeburn  8474:         } else {
1.536     raeburn  8475:             my %userenv = 
                   8476:                 &Apache::lonnet::get('environment',['portfolioquota',
                   8477:                                      'inststatus'],$udom,$uname);
1.472     raeburn  8478:             my ($tmp) = keys(%userenv);
                   8479:             if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8480:                 $quota = $userenv{'portfolioquota'};
1.536     raeburn  8481:                 $inststatus = $userenv{'inststatus'};
1.472     raeburn  8482:             } else {
                   8483:                 undef(%userenv);
                   8484:             }
                   8485:         }
1.536     raeburn  8486:         ($defquota,$settingstatus) = &default_quota($udom,$inststatus);
1.472     raeburn  8487:         if ($quota eq '') {
1.536     raeburn  8488:             $quota = $defquota;
                   8489:             $quotatype = 'default';
                   8490:         } else {
                   8491:             $quotatype = 'custom';
1.472     raeburn  8492:         }
                   8493:     }
1.536     raeburn  8494:     if (wantarray) {
                   8495:         return ($quota,$quotatype,$settingstatus,$defquota);
                   8496:     } else {
                   8497:         return $quota;
                   8498:     }
1.472     raeburn  8499: }
                   8500: 
                   8501: ###############################################
                   8502: 
                   8503: =pod
                   8504: 
                   8505: =item * &default_quota()
                   8506: 
1.536     raeburn  8507: Retrieves default quota assigned for storage of user portfolio files,
                   8508: given an (optional) user's institutional status.
1.472     raeburn  8509: 
                   8510: Incoming parameters:
                   8511: 1. domain
1.536     raeburn  8512: 2. (Optional) institutional status(es).  This is a : separated list of 
                   8513:    status types (e.g., faculty, staff, student etc.)
                   8514:    which apply to the user for whom the default is being retrieved.
                   8515:    If the institutional status string in undefined, the domain
                   8516:    default quota will be returned. 
1.472     raeburn  8517: 
                   8518: Returns:
                   8519: 1. Default disk quota (in Mb) for user portfolios in the domain.
1.536     raeburn  8520: 2. (Optional) institutional type which determined the value of the
                   8521:    default quota.
1.472     raeburn  8522: 
                   8523: If a value has been stored in the domain's configuration db,
                   8524: it will return that, otherwise it returns 20 (for backwards 
                   8525: compatibility with domains which have not set up a configuration
                   8526: db file; the original statically defined portfolio quota was 20 Mb). 
                   8527: 
1.536     raeburn  8528: If the user's status includes multiple types (e.g., staff and student),
                   8529: the largest default quota which applies to the user determines the
                   8530: default quota returned.
                   8531: 
1.780     raeburn  8532: =back
                   8533: 
1.472     raeburn  8534: =cut
                   8535: 
                   8536: ###############################################
                   8537: 
                   8538: 
                   8539: sub default_quota {
1.536     raeburn  8540:     my ($udom,$inststatus) = @_;
                   8541:     my ($defquota,$settingstatus);
                   8542:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  8543:                                             ['quotas'],$udom);
                   8544:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  8545:         if ($inststatus ne '') {
1.765     raeburn  8546:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  8547:             foreach my $item (@statuses) {
1.711     raeburn  8548:                 if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8549:                     if ($quotahash{'quotas'}{'defaultquota'}{$item} ne '') {
                   8550:                         if ($defquota eq '') {
                   8551:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8552:                             $settingstatus = $item;
                   8553:                         } elsif ($quotahash{'quotas'}{'defaultquota'}{$item} > $defquota) {
                   8554:                             $defquota = $quotahash{'quotas'}{'defaultquota'}{$item};
                   8555:                             $settingstatus = $item;
                   8556:                         }
                   8557:                     }
                   8558:                 } else {
                   8559:                     if ($quotahash{'quotas'}{$item} ne '') {
                   8560:                         if ($defquota eq '') {
                   8561:                             $defquota = $quotahash{'quotas'}{$item};
                   8562:                             $settingstatus = $item;
                   8563:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   8564:                             $defquota = $quotahash{'quotas'}{$item};
                   8565:                             $settingstatus = $item;
                   8566:                         }
1.536     raeburn  8567:                     }
                   8568:                 }
                   8569:             }
                   8570:         }
                   8571:         if ($defquota eq '') {
1.711     raeburn  8572:             if (ref($quotahash{'quotas'}{'defaultquota'}) eq 'HASH') {
                   8573:                 $defquota = $quotahash{'quotas'}{'defaultquota'}{'default'};
                   8574:             } else {
                   8575:                 $defquota = $quotahash{'quotas'}{'default'};
                   8576:             }
1.536     raeburn  8577:             $settingstatus = 'default';
                   8578:         }
                   8579:     } else {
                   8580:         $settingstatus = 'default';
                   8581:         $defquota = 20;
                   8582:     }
                   8583:     if (wantarray) {
                   8584:         return ($defquota,$settingstatus);
1.472     raeburn  8585:     } else {
1.536     raeburn  8586:         return $defquota;
1.472     raeburn  8587:     }
                   8588: }
                   8589: 
1.384     raeburn  8590: sub get_secgrprole_info {
                   8591:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   8592:     my %sections_count = &get_sections($cdom,$cnum);
                   8593:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   8594:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   8595:     my @groups = sort(keys(%curr_groups));
                   8596:     my $allroles = [];
                   8597:     my $rolehash;
                   8598:     my $accesshash = {
                   8599:                      active => 'Currently has access',
                   8600:                      future => 'Will have future access',
                   8601:                      previous => 'Previously had access',
                   8602:                   };
                   8603:     if ($needroles) {
                   8604:         $rolehash = {'all' => 'all'};
1.385     albertel 8605:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8606: 	if (&Apache::lonnet::error(%user_roles)) {
                   8607: 	    undef(%user_roles);
                   8608: 	}
                   8609:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  8610:             my ($role)=split(/\:/,$item,2);
                   8611:             if ($role eq 'cr') { next; }
                   8612:             if ($role =~ /^cr/) {
                   8613:                 $$rolehash{$role} = (split('/',$role))[3];
                   8614:             } else {
                   8615:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   8616:             }
                   8617:         }
                   8618:         foreach my $key (sort(keys(%{$rolehash}))) {
                   8619:             push(@{$allroles},$key);
                   8620:         }
                   8621:         push (@{$allroles},'st');
                   8622:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   8623:     }
                   8624:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   8625: }
                   8626: 
1.555     raeburn  8627: sub user_picker {
1.994     raeburn  8628:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  8629:     my $currdom = $dom;
                   8630:     my %curr_selected = (
                   8631:                         srchin => 'dom',
1.580     raeburn  8632:                         srchby => 'lastname',
1.555     raeburn  8633:                       );
                   8634:     my $srchterm;
1.625     raeburn  8635:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  8636:         if ($srch->{'srchby'} ne '') {
                   8637:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   8638:         }
                   8639:         if ($srch->{'srchin'} ne '') {
                   8640:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   8641:         }
                   8642:         if ($srch->{'srchtype'} ne '') {
                   8643:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   8644:         }
                   8645:         if ($srch->{'srchdomain'} ne '') {
                   8646:             $currdom = $srch->{'srchdomain'};
                   8647:         }
                   8648:         $srchterm = $srch->{'srchterm'};
                   8649:     }
                   8650:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  8651:                     'usr'       => 'Search criteria',
1.563     raeburn  8652:                     'doma'      => 'Domain/institution to search',
1.558     albertel 8653:                     'uname'     => 'username',
                   8654:                     'lastname'  => 'last name',
1.555     raeburn  8655:                     'lastfirst' => 'last name, first name',
1.558     albertel 8656:                     'crs'       => 'in this course',
1.576     raeburn  8657:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 8658:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  8659:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 8660:                     'exact'     => 'is',
                   8661:                     'contains'  => 'contains',
1.569     raeburn  8662:                     'begins'    => 'begins with',
1.571     raeburn  8663:                     'youm'      => "You must include some text to search for.",
                   8664:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   8665:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   8666:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   8667:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   8668:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   8669:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   8670:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  8671:                                        );
1.563     raeburn  8672:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   8673:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  8674: 
                   8675:     my @srchins = ('crs','dom','alc','instd');
                   8676: 
                   8677:     foreach my $option (@srchins) {
                   8678:         # FIXME 'alc' option unavailable until 
                   8679:         #       loncreateuser::print_user_query_page()
                   8680:         #       has been completed.
                   8681:         next if ($option eq 'alc');
1.880     raeburn  8682:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  8683:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  8684:         if ($curr_selected{'srchin'} eq $option) {
                   8685:             $srchinsel .= ' 
                   8686:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8687:         } else {
                   8688:             $srchinsel .= '
                   8689:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8690:         }
1.555     raeburn  8691:     }
1.563     raeburn  8692:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  8693: 
                   8694:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  8695:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  8696:         if ($curr_selected{'srchby'} eq $option) {
                   8697:             $srchbysel .= '
                   8698:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8699:         } else {
                   8700:             $srchbysel .= '
                   8701:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8702:          }
                   8703:     }
                   8704:     $srchbysel .= "\n  </select>\n";
                   8705: 
                   8706:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  8707:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  8708:         if ($curr_selected{'srchtype'} eq $option) {
                   8709:             $srchtypesel .= '
                   8710:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   8711:         } else {
                   8712:             $srchtypesel .= '
                   8713:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   8714:         }
                   8715:     }
                   8716:     $srchtypesel .= "\n  </select>\n";
                   8717: 
1.558     albertel 8718:     my ($newuserscript,$new_user_create);
1.994     raeburn  8719:     my $context_dom = $env{'request.role.domain'};
                   8720:     if ($context eq 'requestcrs') {
                   8721:         if ($env{'form.coursedom'} ne '') { 
                   8722:             $context_dom = $env{'form.coursedom'};
                   8723:         }
                   8724:     }
1.556     raeburn  8725:     if ($forcenewuser) {
1.576     raeburn  8726:         if (ref($srch) eq 'HASH') {
1.994     raeburn  8727:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  8728:                 if ($cancreate) {
                   8729:                     $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>';
                   8730:                 } else {
1.799     bisitz   8731:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  8732:                     my %usertypetext = (
                   8733:                         official   => 'institutional',
                   8734:                         unofficial => 'non-institutional',
                   8735:                     );
1.799     bisitz   8736:                     $new_user_create = '<p class="LC_warning">'
                   8737:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   8738:                                       .' '
                   8739:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   8740:                                           ,'<a href="'.$helplink.'">','</a>')
                   8741:                                       .'</p><br />';
1.627     raeburn  8742:                 }
1.576     raeburn  8743:             }
                   8744:         }
                   8745: 
1.556     raeburn  8746:         $newuserscript = <<"ENDSCRIPT";
                   8747: 
1.570     raeburn  8748: function setSearch(createnew,callingForm) {
1.556     raeburn  8749:     if (createnew == 1) {
1.570     raeburn  8750:         for (var i=0; i<callingForm.srchby.length; i++) {
                   8751:             if (callingForm.srchby.options[i].value == 'uname') {
                   8752:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  8753:             }
                   8754:         }
1.570     raeburn  8755:         for (var i=0; i<callingForm.srchin.length; i++) {
                   8756:             if ( callingForm.srchin.options[i].value == 'dom') {
                   8757: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  8758:             }
                   8759:         }
1.570     raeburn  8760:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   8761:             if (callingForm.srchtype.options[i].value == 'exact') {
                   8762:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  8763:             }
                   8764:         }
1.570     raeburn  8765:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  8766:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  8767:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  8768:             }
                   8769:         }
                   8770:     }
                   8771: }
                   8772: ENDSCRIPT
1.558     albertel 8773: 
1.556     raeburn  8774:     }
                   8775: 
1.555     raeburn  8776:     my $output = <<"END_BLOCK";
1.556     raeburn  8777: <script type="text/javascript">
1.824     bisitz   8778: // <![CDATA[
1.570     raeburn  8779: function validateEntry(callingForm) {
1.558     albertel 8780: 
1.556     raeburn  8781:     var checkok = 1;
1.558     albertel 8782:     var srchin;
1.570     raeburn  8783:     for (var i=0; i<callingForm.srchin.length; i++) {
                   8784: 	if ( callingForm.srchin[i].checked ) {
                   8785: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 8786: 	}
                   8787:     }
                   8788: 
1.570     raeburn  8789:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   8790:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   8791:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   8792:     var srchterm =  callingForm.srchterm.value;
                   8793:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  8794:     var msg = "";
                   8795: 
                   8796:     if (srchterm == "") {
                   8797:         checkok = 0;
1.571     raeburn  8798:         msg += "$lt{'youm'}\\n";
1.556     raeburn  8799:     }
                   8800: 
1.569     raeburn  8801:     if (srchtype== 'begins') {
                   8802:         if (srchterm.length < 2) {
                   8803:             checkok = 0;
1.571     raeburn  8804:             msg += "$lt{'thte'}\\n";
1.569     raeburn  8805:         }
                   8806:     }
                   8807: 
1.556     raeburn  8808:     if (srchtype== 'contains') {
                   8809:         if (srchterm.length < 3) {
                   8810:             checkok = 0;
1.571     raeburn  8811:             msg += "$lt{'thet'}\\n";
1.556     raeburn  8812:         }
                   8813:     }
                   8814:     if (srchin == 'instd') {
                   8815:         if (srchdomain == '') {
                   8816:             checkok = 0;
1.571     raeburn  8817:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  8818:         }
                   8819:     }
                   8820:     if (srchin == 'dom') {
                   8821:         if (srchdomain == '') {
                   8822:             checkok = 0;
1.571     raeburn  8823:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  8824:         }
                   8825:     }
                   8826:     if (srchby == 'lastfirst') {
                   8827:         if (srchterm.indexOf(",") == -1) {
                   8828:             checkok = 0;
1.571     raeburn  8829:             msg += "$lt{'whus'}\\n";
1.556     raeburn  8830:         }
                   8831:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   8832:             checkok = 0;
1.571     raeburn  8833:             msg += "$lt{'whse'}\\n";
1.556     raeburn  8834:         }
                   8835:     }
                   8836:     if (checkok == 0) {
1.571     raeburn  8837:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  8838:         return;
                   8839:     }
                   8840:     if (checkok == 1) {
1.570     raeburn  8841:         callingForm.submit();
1.556     raeburn  8842:     }
                   8843: }
                   8844: 
                   8845: $newuserscript
                   8846: 
1.824     bisitz   8847: // ]]>
1.556     raeburn  8848: </script>
1.558     albertel 8849: 
                   8850: $new_user_create
                   8851: 
1.555     raeburn  8852: END_BLOCK
1.558     albertel 8853: 
1.876     raeburn  8854:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   8855:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   8856:                $domform.
                   8857:                &Apache::lonhtmlcommon::row_closure().
                   8858:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   8859:                $srchbysel.
                   8860:                $srchtypesel. 
                   8861:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   8862:                $srchinsel.
                   8863:                &Apache::lonhtmlcommon::row_closure(1). 
                   8864:                &Apache::lonhtmlcommon::end_pick_box().
                   8865:                '<br />';
1.555     raeburn  8866:     return $output;
                   8867: }
                   8868: 
1.612     raeburn  8869: sub user_rule_check {
1.615     raeburn  8870:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  8871:     my $response;
                   8872:     if (ref($usershash) eq 'HASH') {
                   8873:         foreach my $user (keys(%{$usershash})) {
                   8874:             my ($uname,$udom) = split(/:/,$user);
                   8875:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  8876:             my ($id,$newuser);
1.612     raeburn  8877:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  8878:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  8879:                 $id = $usershash->{$user}->{'id'};
                   8880:             }
                   8881:             my $inst_response;
                   8882:             if (ref($checks) eq 'HASH') {
                   8883:                 if (defined($checks->{'username'})) {
1.615     raeburn  8884:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  8885:                         &Apache::lonnet::get_instuser($udom,$uname);
                   8886:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  8887:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  8888:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   8889:                 }
1.615     raeburn  8890:             } else {
                   8891:                 ($inst_response,%{$inst_results->{$user}}) =
                   8892:                     &Apache::lonnet::get_instuser($udom,$uname);
                   8893:                 return;
1.612     raeburn  8894:             }
1.615     raeburn  8895:             if (!$got_rules->{$udom}) {
1.612     raeburn  8896:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   8897:                                                   ['usercreation'],$udom);
                   8898:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  8899:                     foreach my $item ('username','id') {
1.612     raeburn  8900:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   8901:                             $$curr_rules{$udom}{$item} = 
                   8902:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  8903:                         }
                   8904:                     }
                   8905:                 }
1.615     raeburn  8906:                 $got_rules->{$udom} = 1;  
1.585     raeburn  8907:             }
1.612     raeburn  8908:             foreach my $item (keys(%{$checks})) {
                   8909:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   8910:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   8911:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   8912:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   8913:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   8914:                                 if ($rule_check{$rule}) {
                   8915:                                     $$rulematch{$user}{$item} = $rule;
                   8916:                                     if ($inst_response eq 'ok') {
1.615     raeburn  8917:                                         if (ref($inst_results) eq 'HASH') {
                   8918:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   8919:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   8920:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   8921:                                                 }
1.612     raeburn  8922:                                             }
                   8923:                                         }
1.615     raeburn  8924:                                     }
                   8925:                                     last;
1.585     raeburn  8926:                                 }
                   8927:                             }
                   8928:                         }
                   8929:                     }
                   8930:                 }
                   8931:             }
                   8932:         }
                   8933:     }
1.612     raeburn  8934:     return;
                   8935: }
                   8936: 
                   8937: sub user_rule_formats {
                   8938:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   8939:     my %text = ( 
                   8940:                  'username' => 'Usernames',
                   8941:                  'id'       => 'IDs',
                   8942:                );
                   8943:     my $output;
                   8944:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   8945:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   8946:         if (@{$ruleorder} > 0) {
                   8947:             $output = '<br />'.&mt("$text{$check} with the following format(s) may <span class=\"LC_cusr_emph\">only</span> be used for verified users at [_1]:",$domdesc).' <ul>';
                   8948:             foreach my $rule (@{$ruleorder}) {
                   8949:                 if (ref($curr_rules) eq 'ARRAY') {
                   8950:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   8951:                         if (ref($rules->{$rule}) eq 'HASH') {
                   8952:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   8953:                                         $rules->{$rule}{'desc'}.'</li>';
                   8954:                         }
                   8955:                     }
                   8956:                 }
                   8957:             }
                   8958:             $output .= '</ul>';
                   8959:         }
                   8960:     }
                   8961:     return $output;
                   8962: }
                   8963: 
                   8964: sub instrule_disallow_msg {
1.615     raeburn  8965:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  8966:     my $response;
                   8967:     my %text = (
                   8968:                   item   => 'username',
                   8969:                   items  => 'usernames',
                   8970:                   match  => 'matches',
                   8971:                   do     => 'does',
                   8972:                   action => 'a username',
                   8973:                   one    => 'one',
                   8974:                );
                   8975:     if ($count > 1) {
                   8976:         $text{'item'} = 'usernames';
                   8977:         $text{'match'} ='match';
                   8978:         $text{'do'} = 'do';
                   8979:         $text{'action'} = 'usernames',
                   8980:         $text{'one'} = 'ones';
                   8981:     }
                   8982:     if ($checkitem eq 'id') {
                   8983:         $text{'items'} = 'IDs';
                   8984:         $text{'item'} = 'ID';
                   8985:         $text{'action'} = 'an ID';
1.615     raeburn  8986:         if ($count > 1) {
                   8987:             $text{'item'} = 'IDs';
                   8988:             $text{'action'} = 'IDs';
                   8989:         }
1.612     raeburn  8990:     }
1.674     bisitz   8991:     $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  8992:     if ($mode eq 'upload') {
                   8993:         if ($checkitem eq 'username') {
                   8994:             $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'}.");
                   8995:         } elsif ($checkitem eq 'id') {
1.674     bisitz   8996:             $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  8997:         }
1.669     raeburn  8998:     } elsif ($mode eq 'selfcreate') {
                   8999:         if ($checkitem eq 'id') {
                   9000:             $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.");
                   9001:         }
1.615     raeburn  9002:     } else {
                   9003:         if ($checkitem eq 'username') {
                   9004:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9005:         } elsif ($checkitem eq 'id') {
                   9006:             $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.");
                   9007:         }
1.612     raeburn  9008:     }
                   9009:     return $response;
1.585     raeburn  9010: }
                   9011: 
1.624     raeburn  9012: sub personal_data_fieldtitles {
                   9013:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9014:                         id => 'Student/Employee ID',
                   9015:                         permanentemail => 'E-mail address',
                   9016:                         lastname => 'Last Name',
                   9017:                         firstname => 'First Name',
                   9018:                         middlename => 'Middle Name',
                   9019:                         generation => 'Generation',
                   9020:                         gen => 'Generation',
1.765     raeburn  9021:                         inststatus => 'Affiliation',
1.624     raeburn  9022:                    );
                   9023:     return %fieldtitles;
                   9024: }
                   9025: 
1.642     raeburn  9026: sub sorted_inst_types {
                   9027:     my ($dom) = @_;
                   9028:     my ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9029:     my $othertitle = &mt('All users');
                   9030:     if ($env{'request.course.id'}) {
1.668     raeburn  9031:         $othertitle  = &mt('Any users');
1.642     raeburn  9032:     }
                   9033:     my @types;
                   9034:     if (ref($order) eq 'ARRAY') {
                   9035:         @types = @{$order};
                   9036:     }
                   9037:     if (@types == 0) {
                   9038:         if (ref($usertypes) eq 'HASH') {
                   9039:             @types = sort(keys(%{$usertypes}));
                   9040:         }
                   9041:     }
                   9042:     if (keys(%{$usertypes}) > 0) {
                   9043:         $othertitle = &mt('Other users');
                   9044:     }
                   9045:     return ($othertitle,$usertypes,\@types);
                   9046: }
                   9047: 
1.645     raeburn  9048: sub get_institutional_codes {
                   9049:     my ($settings,$allcourses,$LC_code) = @_;
                   9050: # Get complete list of course sections to update
                   9051:     my @currsections = ();
                   9052:     my @currxlists = ();
                   9053:     my $coursecode = $$settings{'internal.coursecode'};
                   9054: 
                   9055:     if ($$settings{'internal.sectionnums'} ne '') {
                   9056:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9057:     }
                   9058: 
                   9059:     if ($$settings{'internal.crosslistings'} ne '') {
                   9060:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9061:     }
                   9062: 
                   9063:     if (@currxlists > 0) {
                   9064:         foreach (@currxlists) {
                   9065:             if (m/^([^:]+):(\w*)$/) {
                   9066:                 unless (grep/^$1$/,@{$allcourses}) {
                   9067:                     push @{$allcourses},$1;
                   9068:                     $$LC_code{$1} = $2;
                   9069:                 }
                   9070:             }
                   9071:         }
                   9072:     }
                   9073:  
                   9074:     if (@currsections > 0) {
                   9075:         foreach (@currsections) {
                   9076:             if (m/^(\w+):(\w*)$/) {
                   9077:                 my $sec = $coursecode.$1;
                   9078:                 my $lc_sec = $2;
                   9079:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9080:                     push @{$allcourses},$sec;
                   9081:                     $$LC_code{$sec} = $lc_sec;
                   9082:                 }
                   9083:             }
                   9084:         }
                   9085:     }
                   9086:     return;
                   9087: }
                   9088: 
1.971     raeburn  9089: sub get_standard_codeitems {
                   9090:     return ('Year','Semester','Department','Number','Section');
                   9091: }
                   9092: 
1.112     bowersj2 9093: =pod
                   9094: 
1.780     raeburn  9095: =head1 Slot Helpers
                   9096: 
                   9097: =over 4
                   9098: 
                   9099: =item * sorted_slots()
                   9100: 
1.1040    raeburn  9101: Sorts an array of slot names in order of an optional sort key,
                   9102: default sort is by slot start time (earliest first). 
1.780     raeburn  9103: 
                   9104: Inputs:
                   9105: 
                   9106: =over 4
                   9107: 
                   9108: slotsarr  - Reference to array of unsorted slot names.
                   9109: 
                   9110: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9111: 
1.1040    raeburn  9112: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9113: 
1.549     albertel 9114: =back
                   9115: 
1.780     raeburn  9116: Returns:
                   9117: 
                   9118: =over 4
                   9119: 
1.1040    raeburn  9120: sorted   - An array of slot names sorted by a specified sort key 
                   9121:            (default sort key is start time of the slot).
1.780     raeburn  9122: 
                   9123: =back
                   9124: 
                   9125: =cut
                   9126: 
                   9127: 
                   9128: sub sorted_slots {
1.1040    raeburn  9129:     my ($slotsarr,$slots,$sortkey) = @_;
                   9130:     if ($sortkey eq '') {
                   9131:         $sortkey = 'starttime';
                   9132:     }
1.780     raeburn  9133:     my @sorted;
                   9134:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9135:         @sorted =
                   9136:             sort {
                   9137:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9138:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9139:                      }
                   9140:                      if (ref($slots->{$a})) { return -1;}
                   9141:                      if (ref($slots->{$b})) { return 1;}
                   9142:                      return 0;
                   9143:                  } @{$slotsarr};
                   9144:     }
                   9145:     return @sorted;
                   9146: }
                   9147: 
1.1040    raeburn  9148: =pod
                   9149: 
                   9150: =item * get_future_slots()
                   9151: 
                   9152: Inputs:
                   9153: 
                   9154: =over 4
                   9155: 
                   9156: cnum - course number
                   9157: 
                   9158: cdom - course domain
                   9159: 
                   9160: now - current UNIX time
                   9161: 
                   9162: symb - optional symb
                   9163: 
                   9164: =back
                   9165: 
                   9166: Returns:
                   9167: 
                   9168: =over 4
                   9169: 
                   9170: sorted_reservable - ref to array of student_schedulable slots currently 
                   9171:                     reservable, ordered by end date of reservation period.
                   9172: 
                   9173: reservable_now - ref to hash of student_schedulable slots currently
                   9174:                  reservable.
                   9175: 
                   9176:     Keys in inner hash are:
                   9177:     (a) symb: either blank or symb to which slot use is restricted.
                   9178:     (b) endreserve: end date of reservation period. 
                   9179: 
                   9180: sorted_future - ref to array of student_schedulable slots reservable in
                   9181:                 the future, ordered by start date of reservation period.
                   9182: 
                   9183: future_reservable - ref to hash of student_schedulable slots reservable
                   9184:                     in the future.
                   9185: 
                   9186:     Keys in inner hash are:
                   9187:     (a) symb: either blank or symb to which slot use is restricted.
                   9188:     (b) startreserve:  start date of reservation period.
                   9189: 
                   9190: =back
                   9191: 
                   9192: =cut
                   9193: 
                   9194: sub get_future_slots {
                   9195:     my ($cnum,$cdom,$now,$symb) = @_;
                   9196:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9197:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9198:     foreach my $slot (keys(%slots)) {
                   9199:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9200:         if ($symb) {
                   9201:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9202:                      ($slots{$slot}->{'symb'} ne $symb));
                   9203:         }
                   9204:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9205:             ($slots{$slot}->{'endtime'} > $now)) {
                   9206:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9207:                 my $userallowed = 0;
                   9208:                 if ($slots{$slot}->{'allowedsections'}) {
                   9209:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9210:                     if (!defined($env{'request.role.sec'})
                   9211:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9212:                         $userallowed=1;
                   9213:                     } else {
                   9214:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9215:                             $userallowed=1;
                   9216:                         }
                   9217:                     }
                   9218:                     unless ($userallowed) {
                   9219:                         if (defined($env{'request.course.groups'})) {
                   9220:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9221:                             foreach my $group (@groups) {
                   9222:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9223:                                     $userallowed=1;
                   9224:                                     last;
                   9225:                                 }
                   9226:                             }
                   9227:                         }
                   9228:                     }
                   9229:                 }
                   9230:                 if ($slots{$slot}->{'allowedusers'}) {
                   9231:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9232:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9233:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9234:                         $userallowed = 1;
                   9235:                     }
                   9236:                 }
                   9237:                 next unless($userallowed);
                   9238:             }
                   9239:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9240:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9241:             my $symb = $slots{$slot}->{'symb'};
                   9242:             if (($startreserve < $now) &&
                   9243:                 (!$endreserve || $endreserve > $now)) {
                   9244:                 my $lastres = $endreserve;
                   9245:                 if (!$lastres) {
                   9246:                     $lastres = $slots{$slot}->{'starttime'};
                   9247:                 }
                   9248:                 $reservable_now{$slot} = {
                   9249:                                            symb       => $symb,
                   9250:                                            endreserve => $lastres
                   9251:                                          };
                   9252:             } elsif (($startreserve > $now) &&
                   9253:                      (!$endreserve || $endreserve > $startreserve)) {
                   9254:                 $future_reservable{$slot} = {
                   9255:                                               symb         => $symb,
                   9256:                                               startreserve => $startreserve
                   9257:                                             };
                   9258:             }
                   9259:         }
                   9260:     }
                   9261:     my @unsorted_reservable = keys(%reservable_now);
                   9262:     if (@unsorted_reservable > 0) {
                   9263:         @sorted_reservable = 
                   9264:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9265:     }
                   9266:     my @unsorted_future = keys(%future_reservable);
                   9267:     if (@unsorted_future > 0) {
                   9268:         @sorted_future =
                   9269:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9270:     }
                   9271:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9272: }
1.780     raeburn  9273: 
                   9274: =pod
                   9275: 
1.1057    foxr     9276: =back
                   9277: 
1.549     albertel 9278: =head1 HTTP Helpers
                   9279: 
                   9280: =over 4
                   9281: 
1.648     raeburn  9282: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9283: 
1.258     albertel 9284: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9285: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9286: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9287: 
                   9288: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9289: $possible_names is an ref to an array of form element names.  As an example:
                   9290: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9291: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9292: 
                   9293: =cut
1.1       albertel 9294: 
1.6       albertel 9295: sub get_unprocessed_cgi {
1.25      albertel 9296:   my ($query,$possible_names)= @_;
1.26      matthew  9297:   # $Apache::lonxml::debug=1;
1.356     albertel 9298:   foreach my $pair (split(/&/,$query)) {
                   9299:     my ($name, $value) = split(/=/,$pair);
1.369     www      9300:     $name = &unescape($name);
1.25      albertel 9301:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9302:       $value =~ tr/+/ /;
                   9303:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9304:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9305:     }
1.16      harris41 9306:   }
1.6       albertel 9307: }
                   9308: 
1.112     bowersj2 9309: =pod
                   9310: 
1.648     raeburn  9311: =item * &cacheheader() 
1.112     bowersj2 9312: 
                   9313: returns cache-controlling header code
                   9314: 
                   9315: =cut
                   9316: 
1.7       albertel 9317: sub cacheheader {
1.258     albertel 9318:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 9319:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   9320:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 9321:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   9322:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 9323:     return $output;
1.7       albertel 9324: }
                   9325: 
1.112     bowersj2 9326: =pod
                   9327: 
1.648     raeburn  9328: =item * &no_cache($r) 
1.112     bowersj2 9329: 
                   9330: specifies header code to not have cache
                   9331: 
                   9332: =cut
                   9333: 
1.9       albertel 9334: sub no_cache {
1.216     albertel 9335:     my ($r) = @_;
                   9336:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 9337: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 9338:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   9339:     $r->no_cache(1);
                   9340:     $r->header_out("Expires" => $date);
                   9341:     $r->header_out("Pragma" => "no-cache");
1.123     www      9342: }
                   9343: 
                   9344: sub content_type {
1.181     albertel 9345:     my ($r,$type,$charset) = @_;
1.299     foxr     9346:     if ($r) {
                   9347: 	#  Note that printout.pl calls this with undef for $r.
                   9348: 	&no_cache($r);
                   9349:     }
1.258     albertel 9350:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 9351:     unless ($charset) {
                   9352: 	$charset=&Apache::lonlocal::current_encoding;
                   9353:     }
                   9354:     if ($charset) { $type.='; charset='.$charset; }
                   9355:     if ($r) {
                   9356: 	$r->content_type($type);
                   9357:     } else {
                   9358: 	print("Content-type: $type\n\n");
                   9359:     }
1.9       albertel 9360: }
1.25      albertel 9361: 
1.112     bowersj2 9362: =pod
                   9363: 
1.648     raeburn  9364: =item * &add_to_env($name,$value) 
1.112     bowersj2 9365: 
1.258     albertel 9366: adds $name to the %env hash with value
1.112     bowersj2 9367: $value, if $name already exists, the entry is converted to an array
                   9368: reference and $value is added to the array.
                   9369: 
                   9370: =cut
                   9371: 
1.25      albertel 9372: sub add_to_env {
                   9373:   my ($name,$value)=@_;
1.258     albertel 9374:   if (defined($env{$name})) {
                   9375:     if (ref($env{$name})) {
1.25      albertel 9376:       #already have multiple values
1.258     albertel 9377:       push(@{ $env{$name} },$value);
1.25      albertel 9378:     } else {
                   9379:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 9380:       my $first=$env{$name};
                   9381:       undef($env{$name});
                   9382:       push(@{ $env{$name} },$first,$value);
1.25      albertel 9383:     }
                   9384:   } else {
1.258     albertel 9385:     $env{$name}=$value;
1.25      albertel 9386:   }
1.31      albertel 9387: }
1.149     albertel 9388: 
                   9389: =pod
                   9390: 
1.648     raeburn  9391: =item * &get_env_multiple($name) 
1.149     albertel 9392: 
1.258     albertel 9393: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 9394: values may be defined and end up as an array ref.
                   9395: 
                   9396: returns an array of values
                   9397: 
                   9398: =cut
                   9399: 
                   9400: sub get_env_multiple {
                   9401:     my ($name) = @_;
                   9402:     my @values;
1.258     albertel 9403:     if (defined($env{$name})) {
1.149     albertel 9404:         # exists is it an array
1.258     albertel 9405:         if (ref($env{$name})) {
                   9406:             @values=@{ $env{$name} };
1.149     albertel 9407:         } else {
1.258     albertel 9408:             $values[0]=$env{$name};
1.149     albertel 9409:         }
                   9410:     }
                   9411:     return(@values);
                   9412: }
                   9413: 
1.660     raeburn  9414: sub ask_for_embedded_content {
                   9415:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  9416:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  9417:         %currsubfile,%unused,$rem);
1.1071    raeburn  9418:     my $counter = 0;
                   9419:     my $numnew = 0;
1.987     raeburn  9420:     my $numremref = 0;
                   9421:     my $numinvalid = 0;
                   9422:     my $numpathchg = 0;
                   9423:     my $numexisting = 0;
1.1071    raeburn  9424:     my $numunused = 0;
                   9425:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
                   9426:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path);
                   9427:     my $heading = &mt('Upload embedded files');
                   9428:     my $buttontext = &mt('Upload');
                   9429: 
1.1085    raeburn  9430:     my $navmap;
                   9431:     if ($env{'request.course.id'}) {
                   9432:         $navmap = Apache::lonnavmaps::navmap->new();
                   9433:     }
1.984     raeburn  9434:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9435:         my $current_path='/';
                   9436:         if ($env{'form.currentpath'}) {
                   9437:             $current_path = $env{'form.currentpath'};
                   9438:         }
                   9439:         if ($actionurl eq '/adm/coursegrp_portfolio') {
                   9440:             $udom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9441:             $uname = $env{'course.'.$env{'request.course.id'}.'.num'};
                   9442:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   9443:         } else {
                   9444:             $udom = $env{'user.domain'};
                   9445:             $uname = $env{'user.name'};
                   9446:             $url = '/userfiles/portfolio';
                   9447:         }
1.987     raeburn  9448:         $toplevel = $url.'/';
1.984     raeburn  9449:         $url .= $current_path;
                   9450:         $getpropath = 1;
1.987     raeburn  9451:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   9452:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      9453:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  9454:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  9455:         $toplevel = $url;
1.984     raeburn  9456:         if ($rest ne '') {
1.987     raeburn  9457:             $url .= $rest;
                   9458:         }
                   9459:     } elsif ($actionurl eq '/adm/coursedocs') {
                   9460:         if (ref($args) eq 'HASH') {
1.1071    raeburn  9461:             $url = $args->{'docs_url'};
                   9462:             $toplevel = $url;
1.1084    raeburn  9463:             if ($args->{'context'} eq 'paste') {
                   9464:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   9465:                 ($path) = 
                   9466:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9467:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9468:                 $fileloc =~ s{^/}{};
                   9469:             }
1.1071    raeburn  9470:         }
1.1084    raeburn  9471:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  9472:         if ($env{'request.course.id'} ne '') {
                   9473:             $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   9474:             $cnum =  $env{'course.'.$env{'request.course.id'}.'.num'};
                   9475:             if (ref($args) eq 'HASH') {
                   9476:                 $url = $args->{'docs_url'};
                   9477:                 $title = $args->{'docs_title'};
                   9478:                 $toplevel = "/$url";
1.1085    raeburn  9479:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1071    raeburn  9480:                 ($path) =  
                   9481:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   9482:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   9483:                 $fileloc =~ s{^/}{};
                   9484:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   9485:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   9486:             }
1.987     raeburn  9487:         }
                   9488:     }
                   9489:     my $now = time();
                   9490:     foreach my $embed_file (keys(%{$allfiles})) {
                   9491:         my $absolutepath;
                   9492:         if ($embed_file =~ m{^\w+://}) {
                   9493:             $newfiles{$embed_file} = 1;
                   9494:             $mapping{$embed_file} = $embed_file;
                   9495:         } else {
                   9496:             if ($embed_file =~ m{^/}) {
                   9497:                 $absolutepath = $embed_file;
                   9498:                 $embed_file =~ s{^(/+)}{};
                   9499:             }
                   9500:             if ($embed_file =~ m{/}) {
                   9501:                 my ($path,$fname) = ($embed_file =~ m{^(.+)/([^/]*)$});
                   9502:                 $path = &check_for_traversal($path,$url,$toplevel);
                   9503:                 my $item = $fname;
                   9504:                 if ($path ne '') {
                   9505:                     $item = $path.'/'.$fname;
                   9506:                     $subdependencies{$path}{$fname} = 1;
                   9507:                 } else {
                   9508:                     $dependencies{$item} = 1;
                   9509:                 }
                   9510:                 if ($absolutepath) {
                   9511:                     $mapping{$item} = $absolutepath;
                   9512:                 } else {
                   9513:                     $mapping{$item} = $embed_file;
                   9514:                 }
                   9515:             } else {
                   9516:                 $dependencies{$embed_file} = 1;
                   9517:                 if ($absolutepath) {
                   9518:                     $mapping{$embed_file} = $absolutepath;
                   9519:                 } else {
                   9520:                     $mapping{$embed_file} = $embed_file;
                   9521:                 }
                   9522:             }
1.984     raeburn  9523:         }
                   9524:     }
1.1071    raeburn  9525:     my $dirptr = 16384;
1.984     raeburn  9526:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  9527:         $currsubfile{$path} = {};
1.984     raeburn  9528:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  9529:             my ($sublistref,$listerror) =
                   9530:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   9531:             if (ref($sublistref) eq 'ARRAY') {
                   9532:                 foreach my $line (@{$sublistref}) {
                   9533:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  9534:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  9535:                 }
1.984     raeburn  9536:             }
1.987     raeburn  9537:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9538:             if (opendir(my $dir,$url.'/'.$path)) {
                   9539:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  9540:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   9541:             }
1.1084    raeburn  9542:         } elsif (($actionurl eq '/adm/dependencies') ||
                   9543:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9544:                   ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9545:             if ($env{'request.course.id'} ne '') {
                   9546:                 my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9547:                 if ($dir ne '') {
                   9548:                     my ($sublistref,$listerror) =
                   9549:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   9550:                     if (ref($sublistref) eq 'ARRAY') {
                   9551:                         foreach my $line (@{$sublistref}) {
                   9552:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   9553:                                 undef,$mtime)=split(/\&/,$line,12);
                   9554:                             unless (($testdir&$dirptr) ||
                   9555:                                     ($file_name =~ /^\.\.?$/)) {
                   9556:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   9557:                             }
                   9558:                         }
                   9559:                     }
                   9560:                 }
1.984     raeburn  9561:             }
                   9562:         }
                   9563:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  9564:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  9565:                 my $item = $path.'/'.$file;
                   9566:                 unless ($mapping{$item} eq $item) {
                   9567:                     $pathchanges{$item} = 1;
                   9568:                 }
                   9569:                 $existing{$item} = 1;
                   9570:                 $numexisting ++;
                   9571:             } else {
                   9572:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  9573:             }
                   9574:         }
1.1071    raeburn  9575:         if ($actionurl eq '/adm/dependencies') {
                   9576:             foreach my $path (keys(%currsubfile)) {
                   9577:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   9578:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   9579:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  9580:                              next if (($rem ne '') &&
                   9581:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   9582:                                        (ref($navmap) &&
                   9583:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   9584:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9585:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  9586:                              $unused{$path.'/'.$file} = 1; 
                   9587:                          }
                   9588:                     }
                   9589:                 }
                   9590:             }
                   9591:         }
1.984     raeburn  9592:     }
1.987     raeburn  9593:     my %currfile;
1.984     raeburn  9594:     if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  9595:         my ($dirlistref,$listerror) =
                   9596:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   9597:         if (ref($dirlistref) eq 'ARRAY') {
                   9598:             foreach my $line (@{$dirlistref}) {
                   9599:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   9600:                 $currfile{$file_name} = 1;
                   9601:             }
1.984     raeburn  9602:         }
1.987     raeburn  9603:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  9604:         if (opendir(my $dir,$url)) {
1.987     raeburn  9605:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  9606:             map {$currfile{$_} = 1;} @dir_list;
                   9607:         }
1.1084    raeburn  9608:     } elsif (($actionurl eq '/adm/dependencies') ||
                   9609:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9610:               ($args->{'context'} eq 'paste'))) {
1.1071    raeburn  9611:         if ($env{'request.course.id'} ne '') {
                   9612:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   9613:             if ($dir ne '') {
                   9614:                 my ($dirlistref,$listerror) =
                   9615:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   9616:                 if (ref($dirlistref) eq 'ARRAY') {
                   9617:                     foreach my $line (@{$dirlistref}) {
                   9618:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   9619:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   9620:                         unless (($testdir&$dirptr) ||
                   9621:                                 ($file_name =~ /^\.\.?$/)) {
                   9622:                             $currfile{$file_name} = [$size,$mtime];
                   9623:                         }
                   9624:                     }
                   9625:                 }
                   9626:             }
                   9627:         }
1.984     raeburn  9628:     }
                   9629:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  9630:         if (exists($currfile{$file})) {
1.987     raeburn  9631:             unless ($mapping{$file} eq $file) {
                   9632:                 $pathchanges{$file} = 1;
                   9633:             }
                   9634:             $existing{$file} = 1;
                   9635:             $numexisting ++;
                   9636:         } else {
1.984     raeburn  9637:             $newfiles{$file} = 1;
                   9638:         }
                   9639:     }
1.1071    raeburn  9640:     foreach my $file (keys(%currfile)) {
                   9641:         unless (($file eq $filename) ||
                   9642:                 ($file eq $filename.'.bak') ||
                   9643:                 ($dependencies{$file})) {
1.1085    raeburn  9644:             if ($actionurl eq '/adm/dependencies') {
                   9645:                 next if (($rem ne '') &&
                   9646:                          (($env{"httpref.$rem".$file} ne '') ||
                   9647:                           (ref($navmap) &&
                   9648:                           (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   9649:                            (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   9650:                             ($navmap->getResourceByUrl($rem.$1)))))));
                   9651:             }
1.1071    raeburn  9652:             $unused{$file} = 1;
                   9653:         }
                   9654:     }
1.1084    raeburn  9655:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   9656:         ($args->{'context'} eq 'paste')) {
                   9657:         $counter = scalar(keys(%existing));
                   9658:         $numpathchg = scalar(keys(%pathchanges));
                   9659:         return ($output,$counter,$numpathchg,\%existing); 
                   9660:     }
1.984     raeburn  9661:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  9662:         if ($actionurl eq '/adm/dependencies') {
                   9663:             next if ($embed_file =~ m{^\w+://});
                   9664:         }
1.660     raeburn  9665:         $upload_output .= &start_data_table_row().
1.1071    raeburn  9666:                           '<td><img src="'.&icon($embed_file).'" />&nbsp;'.
                   9667:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  9668:         unless ($mapping{$embed_file} eq $embed_file) {
                   9669:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.&mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
                   9670:         }
                   9671:         $upload_output .= '</td><td>';
1.1071    raeburn  9672:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.660     raeburn  9673:             $upload_output.='<span class="LC_warning">'.&mt("URL points to other server.").'</span>';
1.987     raeburn  9674:             $numremref++;
1.660     raeburn  9675:         } elsif ($args->{'error_on_invalid_names'}
                   9676:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.987     raeburn  9677:             $upload_output.='<span class="LC_warning">'.&mt('Invalid characters').'</span>';
                   9678:             $numinvalid++;
1.660     raeburn  9679:         } else {
1.1071    raeburn  9680:             $upload_output .= &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  9681:                                                      $embed_file,\%mapping,
1.1071    raeburn  9682:                                                      $allfiles,$codebase,'upload');
                   9683:             $counter ++;
                   9684:             $numnew ++;
1.987     raeburn  9685:         }
                   9686:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   9687:     }
                   9688:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  9689:         if ($actionurl eq '/adm/dependencies') {
                   9690:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   9691:             $modify_output .= &start_data_table_row().
                   9692:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   9693:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   9694:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   9695:                               '<td>'.$size.'</td>'.
                   9696:                               '<td>'.$mtime.'</td>'.
                   9697:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   9698:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   9699:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   9700:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   9701:                               &embedded_file_element('upload_embedded',$counter,
                   9702:                                                      $embed_file,\%mapping,
                   9703:                                                      $allfiles,$codebase,'modify').
                   9704:                               '</div></td>'.
                   9705:                               &end_data_table_row()."\n";
                   9706:             $counter ++;
                   9707:         } else {
                   9708:             $upload_output .= &start_data_table_row().
                   9709:                               '<td><span class="LC_filename">'.$embed_file.'</span></td>';
                   9710:                               '<td><span class="LC_warning">'.&mt('Already exists').'</span></td>'.
                   9711:                               &Apache::loncommon::end_data_table_row()."\n";
                   9712:         }
                   9713:     }
                   9714:     my $delidx = $counter;
                   9715:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   9716:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   9717:         $delete_output .= &start_data_table_row().
                   9718:                           '<td><img src="'.&icon($oldfile).'" />'.
                   9719:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   9720:                           '<td>'.$size.'</td>'.
                   9721:                           '<td>'.$mtime.'</td>'.
                   9722:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   9723:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   9724:                           &embedded_file_element('upload_embedded',$delidx,
                   9725:                                                  $oldfile,\%mapping,$allfiles,
                   9726:                                                  $codebase,'delete').'</td>'.
                   9727:                           &end_data_table_row()."\n"; 
                   9728:         $numunused ++;
                   9729:         $delidx ++;
1.987     raeburn  9730:     }
                   9731:     if ($upload_output) {
                   9732:         $upload_output = &start_data_table().
                   9733:                          $upload_output.
                   9734:                          &end_data_table()."\n";
                   9735:     }
1.1071    raeburn  9736:     if ($modify_output) {
                   9737:         $modify_output = &start_data_table().
                   9738:                          &start_data_table_header_row().
                   9739:                          '<th>'.&mt('File').'</th>'.
                   9740:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9741:                          '<th>'.&mt('Modified').'</th>'.
                   9742:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   9743:                          &end_data_table_header_row().
                   9744:                          $modify_output.
                   9745:                          &end_data_table()."\n";
                   9746:     }
                   9747:     if ($delete_output) {
                   9748:         $delete_output = &start_data_table().
                   9749:                          &start_data_table_header_row().
                   9750:                          '<th>'.&mt('File').'</th>'.
                   9751:                          '<th>'.&mt('Size (KB)').'</th>'.
                   9752:                          '<th>'.&mt('Modified').'</th>'.
                   9753:                          '<th>'.&mt('Delete?').'</th>'.
                   9754:                          &end_data_table_header_row().
                   9755:                          $delete_output.
                   9756:                          &end_data_table()."\n";
                   9757:     }
1.987     raeburn  9758:     my $applies = 0;
                   9759:     if ($numremref) {
                   9760:         $applies ++;
                   9761:     }
                   9762:     if ($numinvalid) {
                   9763:         $applies ++;
                   9764:     }
                   9765:     if ($numexisting) {
                   9766:         $applies ++;
                   9767:     }
1.1071    raeburn  9768:     if ($counter || $numunused) {
1.987     raeburn  9769:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   9770:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  9771:                   $state.'<h3>'.$heading.'</h3>'; 
                   9772:         if ($actionurl eq '/adm/dependencies') {
                   9773:             if ($numnew) {
                   9774:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   9775:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   9776:                            $upload_output.'<br />'."\n";
                   9777:             }
                   9778:             if ($numexisting) {
                   9779:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   9780:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   9781:                            $modify_output.'<br />'."\n";
                   9782:                            $buttontext = &mt('Save changes');
                   9783:             }
                   9784:             if ($numunused) {
                   9785:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   9786:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   9787:                            $delete_output.'<br />'."\n";
                   9788:                            $buttontext = &mt('Save changes');
                   9789:             }
                   9790:         } else {
                   9791:             $output .= $upload_output.'<br />'."\n";
                   9792:         }
                   9793:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   9794:                    $counter.'" />'."\n";
                   9795:         if ($actionurl eq '/adm/dependencies') { 
                   9796:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   9797:                        $numnew.'" />'."\n";
                   9798:         } elsif ($actionurl eq '') {
1.987     raeburn  9799:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   9800:         }
                   9801:     } elsif ($applies) {
                   9802:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   9803:         if ($applies > 1) {
                   9804:             $output .=  
                   9805:                 &mt('No files need to be uploaded, as one of the following applies to each reference:').'<ul>';
                   9806:             if ($numremref) {
                   9807:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   9808:             }
                   9809:             if ($numinvalid) {
                   9810:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   9811:             }
                   9812:             if ($numexisting) {
                   9813:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   9814:             }
                   9815:             $output .= '</ul><br />';
                   9816:         } elsif ($numremref) {
                   9817:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   9818:         } elsif ($numinvalid) {
                   9819:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   9820:         } elsif ($numexisting) {
                   9821:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   9822:         }
                   9823:         $output .= $upload_output.'<br />';
                   9824:     }
                   9825:     my ($pathchange_output,$chgcount);
1.1071    raeburn  9826:     $chgcount = $counter;
1.987     raeburn  9827:     if (keys(%pathchanges) > 0) {
                   9828:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  9829:             if ($counter) {
1.987     raeburn  9830:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   9831:                                                   $embed_file,\%mapping,
1.1071    raeburn  9832:                                                   $allfiles,$codebase,'change');
1.987     raeburn  9833:             } else {
                   9834:                 $pathchange_output .= 
                   9835:                     &start_data_table_row().
                   9836:                     '<td><input type ="checkbox" name="namechange" value="'.
                   9837:                     $chgcount.'" checked="checked" /></td>'.
                   9838:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   9839:                     '<td>'.$embed_file.
                   9840:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  9841:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  9842:                     '</td>'.&end_data_table_row();
1.660     raeburn  9843:             }
1.987     raeburn  9844:             $numpathchg ++;
                   9845:             $chgcount ++;
1.660     raeburn  9846:         }
                   9847:     }
1.1071    raeburn  9848:     if ($counter) {
1.987     raeburn  9849:         if ($numpathchg) {
                   9850:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   9851:                        $numpathchg.'" />'."\n";
                   9852:         }
                   9853:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   9854:             ($actionurl eq '/adm/imsimport')) {
                   9855:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   9856:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   9857:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  9858:         } elsif ($actionurl eq '/adm/dependencies') {
                   9859:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  9860:         }
1.1071    raeburn  9861:         $output .=  '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  9862:     } elsif ($numpathchg) {
                   9863:         my %pathchange = ();
                   9864:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   9865:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   9866:             $output .= '<p>'.&mt('or').'</p>'; 
                   9867:         } 
                   9868:     }
1.1071    raeburn  9869:     return ($output,$counter,$numpathchg);
1.987     raeburn  9870: }
                   9871: 
                   9872: sub embedded_file_element {
1.1071    raeburn  9873:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  9874:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   9875:                    (ref($codebase) eq 'HASH'));
                   9876:     my $output;
1.1071    raeburn  9877:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  9878:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   9879:     }
                   9880:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   9881:                &escape($embed_file).'" />';
                   9882:     unless (($context eq 'upload_embedded') && 
                   9883:             ($mapping->{$embed_file} eq $embed_file)) {
                   9884:         $output .='
                   9885:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   9886:     }
                   9887:     my $attrib;
                   9888:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   9889:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   9890:     }
                   9891:     $output .=
                   9892:         "\n\t\t".
                   9893:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   9894:         $attrib.'" />';
                   9895:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   9896:         $output .=
                   9897:             "\n\t\t".
                   9898:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   9899:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  9900:     }
1.987     raeburn  9901:     return $output;
1.660     raeburn  9902: }
                   9903: 
1.1071    raeburn  9904: sub get_dependency_details {
                   9905:     my ($currfile,$currsubfile,$embed_file) = @_;
                   9906:     my ($size,$mtime,$showsize,$showmtime);
                   9907:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   9908:         if ($embed_file =~ m{/}) {
                   9909:             my ($path,$fname) = split(/\//,$embed_file);
                   9910:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   9911:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   9912:             }
                   9913:         } else {
                   9914:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   9915:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   9916:             }
                   9917:         }
                   9918:         $showsize = $size/1024.0;
                   9919:         $showsize = sprintf("%.1f",$showsize);
                   9920:         if ($mtime > 0) {
                   9921:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   9922:         }
                   9923:     }
                   9924:     return ($showsize,$showmtime);
                   9925: }
                   9926: 
                   9927: sub ask_embedded_js {
                   9928:     return <<"END";
                   9929: <script type="text/javascript"">
                   9930: // <![CDATA[
                   9931: function toggleBrowse(counter) {
                   9932:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   9933:     var fileid = document.getElementById('embedded_item_'+counter);
                   9934:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   9935:     if (chkboxid.checked == true) {
                   9936:         uploaddivid.style.display='block';
                   9937:     } else {
                   9938:         uploaddivid.style.display='none';
                   9939:         fileid.value = '';
                   9940:     }
                   9941: }
                   9942: // ]]>
                   9943: </script>
                   9944: 
                   9945: END
                   9946: }
                   9947: 
1.661     raeburn  9948: sub upload_embedded {
                   9949:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  9950:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   9951:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  9952:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   9953:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   9954:         my $orig_uploaded_filename =
                   9955:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  9956:         foreach my $type ('orig','ref','attrib','codebase') {
                   9957:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   9958:                 $env{'form.embedded_'.$type.'_'.$i} =
                   9959:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   9960:             }
                   9961:         }
1.661     raeburn  9962:         my ($path,$fname) =
                   9963:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   9964:         # no path, whole string is fname
                   9965:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   9966:         $fname = &Apache::lonnet::clean_filename($fname);
                   9967:         # See if there is anything left
                   9968:         next if ($fname eq '');
                   9969: 
                   9970:         # Check if file already exists as a file or directory.
                   9971:         my ($state,$msg);
                   9972:         if ($context eq 'portfolio') {
                   9973:             my $port_path = $dirpath;
                   9974:             if ($group ne '') {
                   9975:                 $port_path = "groups/$group/$port_path";
                   9976:             }
1.987     raeburn  9977:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   9978:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  9979:                                               $dir_root,$port_path,$disk_quota,
                   9980:                                               $current_disk_usage,$uname,$udom);
                   9981:             if ($state eq 'will_exceed_quota'
1.984     raeburn  9982:                 || $state eq 'file_locked') {
1.661     raeburn  9983:                 $output .= $msg;
                   9984:                 next;
                   9985:             }
                   9986:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   9987:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   9988:             if ($state eq 'exists') {
                   9989:                 $output .= $msg;
                   9990:                 next;
                   9991:             }
                   9992:         }
                   9993:         # Check if extension is valid
                   9994:         if (($fname =~ /\.(\w+)$/) &&
                   9995:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.987     raeburn  9996:             $output .= &mt('Invalid file extension ([_1]) - reserved for LONCAPA use - rename the file with a different extension and re-upload. ',$1).'<br />';
1.661     raeburn  9997:             next;
                   9998:         } elsif (($fname =~ /\.(\w+)$/) &&
                   9999:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10000:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10001:             next;
                   10002:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.987     raeburn  10003:             $output .= &mt('File name not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10004:             next;
                   10005:         }
                   10006:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
                   10007:         if ($context eq 'portfolio') {
1.984     raeburn  10008:             my $result;
                   10009:             if ($state eq 'existingfile') {
                   10010:                 $result=
                   10011:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.987     raeburn  10012:                                                     $dirpath.$env{'form.currentpath'}.$path);
1.661     raeburn  10013:             } else {
1.984     raeburn  10014:                 $result=
                   10015:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10016:                                                     $dirpath.
                   10017:                                                     $env{'form.currentpath'}.$path);
1.984     raeburn  10018:                 if ($result !~ m|^/uploaded/|) {
                   10019:                     $output .= '<span class="LC_error">'
                   10020:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10021:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10022:                                .'</span><br />';
                   10023:                     next;
                   10024:                 } else {
1.987     raeburn  10025:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10026:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10027:                 }
1.661     raeburn  10028:             }
1.987     raeburn  10029:         } elsif ($context eq 'coursedoc') {
                   10030:             my $result =
                   10031:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,'coursedoc',
                   10032:                                                 $dirpath.'/'.$path);
                   10033:             if ($result !~ m|^/uploaded/|) {
                   10034:                 $output .= '<span class="LC_error">'
                   10035:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10036:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10037:                            .'</span><br />';
                   10038:                     next;
                   10039:             } else {
                   10040:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10041:                            $path.$fname.'</span>').'<br />';
                   10042:             }
1.661     raeburn  10043:         } else {
                   10044: # Save the file
                   10045:             my $target = $env{'form.embedded_item_'.$i};
                   10046:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10047:             my $dest = $fullpath.$fname;
                   10048:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10049:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10050:             my $count;
                   10051:             my $filepath = $dir_root;
1.1027    raeburn  10052:             foreach my $subdir (@parts) {
                   10053:                 $filepath .= "/$subdir";
                   10054:                 if (!-e $filepath) {
1.661     raeburn  10055:                     mkdir($filepath,0770);
                   10056:                 }
                   10057:             }
                   10058:             my $fh;
                   10059:             if (!open($fh,'>'.$dest)) {
                   10060:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10061:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10062:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10063:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10064:                            '</span><br />';
                   10065:             } else {
                   10066:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10067:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10068:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10069:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10070:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10071:                               '</span><br />';
                   10072:                 } else {
1.987     raeburn  10073:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10074:                                $url.'</span>').'<br />';
                   10075:                     unless ($context eq 'testbank') {
                   10076:                         $footer .= &mt('View embedded file: [_1]',
                   10077:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10078:                     }
                   10079:                 }
                   10080:                 close($fh);
                   10081:             }
                   10082:         }
                   10083:         if ($env{'form.embedded_ref_'.$i}) {
                   10084:             $pathchange{$i} = 1;
                   10085:         }
                   10086:     }
                   10087:     if ($output) {
                   10088:         $output = '<p>'.$output.'</p>';
                   10089:     }
                   10090:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10091:     $returnflag = 'ok';
1.1071    raeburn  10092:     my $numpathchgs = scalar(keys(%pathchange));
                   10093:     if ($numpathchgs > 0) {
1.987     raeburn  10094:         if ($context eq 'portfolio') {
                   10095:             $output .= '<p>'.&mt('or').'</p>';
                   10096:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10097:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10098:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10099:             $returnflag = 'modify_orightml';
                   10100:         }
                   10101:     }
1.1071    raeburn  10102:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10103: }
                   10104: 
                   10105: sub modify_html_form {
                   10106:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10107:     my $end = 0;
                   10108:     my $modifyform;
                   10109:     if ($context eq 'upload_embedded') {
                   10110:         return unless (ref($pathchange) eq 'HASH');
                   10111:         if ($env{'form.number_embedded_items'}) {
                   10112:             $end += $env{'form.number_embedded_items'};
                   10113:         }
                   10114:         if ($env{'form.number_pathchange_items'}) {
                   10115:             $end += $env{'form.number_pathchange_items'};
                   10116:         }
                   10117:         if ($end) {
                   10118:             for (my $i=0; $i<$end; $i++) {
                   10119:                 if ($i < $env{'form.number_embedded_items'}) {
                   10120:                     next unless($pathchange->{$i});
                   10121:                 }
                   10122:                 $modifyform .=
                   10123:                     &start_data_table_row().
                   10124:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10125:                     'checked="checked" /></td>'.
                   10126:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10127:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10128:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10129:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10130:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10131:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10132:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10133:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10134:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10135:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10136:                     &end_data_table_row();
1.1071    raeburn  10137:             }
1.987     raeburn  10138:         }
                   10139:     } else {
                   10140:         $modifyform = $pathchgtable;
                   10141:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10142:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10143:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10144:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10145:         }
                   10146:     }
                   10147:     if ($modifyform) {
1.1071    raeburn  10148:         if ($actionurl eq '/adm/dependencies') {
                   10149:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10150:         }
1.987     raeburn  10151:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10152:                '<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".
                   10153:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10154:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10155:                '</ol></p>'."\n".'<p>'.
                   10156:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10157:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10158:                &start_data_table()."\n".
                   10159:                &start_data_table_header_row().
                   10160:                '<th>'.&mt('Change?').'</th>'.
                   10161:                '<th>'.&mt('Current reference').'</th>'.
                   10162:                '<th>'.&mt('Required reference').'</th>'.
                   10163:                &end_data_table_header_row()."\n".
                   10164:                $modifyform.
                   10165:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10166:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10167:                '</form>'."\n";
                   10168:     }
                   10169:     return;
                   10170: }
                   10171: 
                   10172: sub modify_html_refs {
                   10173:     my ($context,$dirpath,$uname,$udom,$dir_root) = @_;
                   10174:     my $container;
                   10175:     if ($context eq 'portfolio') {
                   10176:         $container = $env{'form.container'};
                   10177:     } elsif ($context eq 'coursedoc') {
                   10178:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10179:     } elsif ($context eq 'manage_dependencies') {
                   10180:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10181:         $container = "/$container";
1.987     raeburn  10182:     } else {
1.1027    raeburn  10183:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10184:     }
                   10185:     my (%allfiles,%codebase,$output,$content);
                   10186:     my @changes = &get_env_multiple('form.namechange');
1.1071    raeburn  10187:     unless (@changes > 0) {
                   10188:         if (wantarray) {
                   10189:             return ('',0,0); 
                   10190:         } else {
                   10191:             return;
                   10192:         }
                   10193:     }
                   10194:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10195:         ($context eq 'manage_dependencies')) {
                   10196:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10197:             if (wantarray) {
                   10198:                 return ('',0,0);
                   10199:             } else {
                   10200:                 return;
                   10201:             }
                   10202:         } 
1.987     raeburn  10203:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10204:         if ($content eq '-1') {
                   10205:             if (wantarray) {
                   10206:                 return ('',0,0);
                   10207:             } else {
                   10208:                 return;
                   10209:             }
                   10210:         }
1.987     raeburn  10211:     } else {
1.1071    raeburn  10212:         unless ($container =~ /^\Q$dir_root\E/) {
                   10213:             if (wantarray) {
                   10214:                 return ('',0,0);
                   10215:             } else {
                   10216:                 return;
                   10217:             }
                   10218:         } 
1.987     raeburn  10219:         if (open(my $fh,"<$container")) {
                   10220:             $content = join('', <$fh>);
                   10221:             close($fh);
                   10222:         } else {
1.1071    raeburn  10223:             if (wantarray) {
                   10224:                 return ('',0,0);
                   10225:             } else {
                   10226:                 return;
                   10227:             }
1.987     raeburn  10228:         }
                   10229:     }
                   10230:     my ($count,$codebasecount) = (0,0);
                   10231:     my $mm = new File::MMagic;
                   10232:     my $mime_type = $mm->checktype_contents($content);
                   10233:     if ($mime_type eq 'text/html') {
                   10234:         my $parse_result = 
                   10235:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   10236:                                                     \%codebase,\$content);
                   10237:         if ($parse_result eq 'ok') {
                   10238:             foreach my $i (@changes) {
                   10239:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   10240:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   10241:                 if ($allfiles{$ref}) {
                   10242:                     my $newname =  $orig;
                   10243:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  10244:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  10245:                     if ($attrib_regexp =~ /:/) {
                   10246:                         $attrib_regexp =~ s/\:/|/g;
                   10247:                     }
                   10248:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   10249:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   10250:                         $count += $numchg;
                   10251:                     }
                   10252:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  10253:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  10254:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   10255:                         $codebasecount ++;
                   10256:                     }
                   10257:                 }
                   10258:             }
                   10259:             if ($count || $codebasecount) {
                   10260:                 my $saveresult;
1.1071    raeburn  10261:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
                   10262:                     ($context eq 'manage_dependencies')) {
1.987     raeburn  10263:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   10264:                     if ($url eq $container) {
                   10265:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   10266:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10267:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  10268:                                             $fname.'</span>').'</p>';
1.987     raeburn  10269:                     } else {
                   10270:                          $output = '<p class="LC_error">'.
                   10271:                                    &mt('Error: update failed for: [_1].',
                   10272:                                    '<span class="LC_filename">'.
                   10273:                                    $container.'</span>').'</p>';
                   10274:                     }
                   10275:                 } else {
                   10276:                     if (open(my $fh,">$container")) {
                   10277:                         print $fh $content;
                   10278:                         close($fh);
                   10279:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   10280:                                   $count,'<span class="LC_filename">'.
                   10281:                                   $container.'</span>').'</p>';
1.661     raeburn  10282:                     } else {
1.987     raeburn  10283:                          $output = '<p class="LC_error">'.
                   10284:                                    &mt('Error: could not update [_1].',
                   10285:                                    '<span class="LC_filename">'.
                   10286:                                    $container.'</span>').'</p>';
1.661     raeburn  10287:                     }
                   10288:                 }
                   10289:             }
1.987     raeburn  10290:         } else {
                   10291:             &logthis('Failed to parse '.$container.
                   10292:                      ' to modify references: '.$parse_result);
1.661     raeburn  10293:         }
                   10294:     }
1.1071    raeburn  10295:     if (wantarray) {
                   10296:         return ($output,$count,$codebasecount);
                   10297:     } else {
                   10298:         return $output;
                   10299:     }
1.661     raeburn  10300: }
                   10301: 
                   10302: sub check_for_existing {
                   10303:     my ($path,$fname,$element) = @_;
                   10304:     my ($state,$msg);
                   10305:     if (-d $path.'/'.$fname) {
                   10306:         $state = 'exists';
                   10307:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10308:     } elsif (-e $path.'/'.$fname) {
                   10309:         $state = 'exists';
                   10310:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   10311:     }
                   10312:     if ($state eq 'exists') {
                   10313:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   10314:     }
                   10315:     return ($state,$msg);
                   10316: }
                   10317: 
                   10318: sub check_for_upload {
                   10319:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   10320:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  10321:     my $filesize = length($env{'form.'.$element});
                   10322:     if (!$filesize) {
                   10323:         my $msg = '<span class="LC_error">'.
                   10324:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   10325:                       '<span class="LC_filename">'.$fname.'</span>',
                   10326:                       $filesize).'<br />'.
1.1007    raeburn  10327:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  10328:                   '</span>';
                   10329:         return ('zero_bytes',$msg);
                   10330:     }
                   10331:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  10332:     my $getpropath = 1;
1.1021    raeburn  10333:     my ($dirlistref,$listerror) =
                   10334:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  10335:     my $found_file = 0;
                   10336:     my $locked_file = 0;
1.991     raeburn  10337:     my @lockers;
                   10338:     my $navmap;
                   10339:     if ($env{'request.course.id'}) {
                   10340:         $navmap = Apache::lonnavmaps::navmap->new();
                   10341:     }
1.1021    raeburn  10342:     if (ref($dirlistref) eq 'ARRAY') {
                   10343:         foreach my $line (@{$dirlistref}) {
                   10344:             my ($file_name,$rest)=split(/\&/,$line,2);
                   10345:             if ($file_name eq $fname){
                   10346:                 $file_name = $path.$file_name;
                   10347:                 if ($group ne '') {
                   10348:                     $file_name = $group.$file_name;
                   10349:                 }
                   10350:                 $found_file = 1;
                   10351:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   10352:                     foreach my $lock (@lockers) {
                   10353:                         if (ref($lock) eq 'ARRAY') {
                   10354:                             my ($symb,$crsid) = @{$lock};
                   10355:                             if ($crsid eq $env{'request.course.id'}) {
                   10356:                                 if (ref($navmap)) {
                   10357:                                     my $res = $navmap->getBySymb($symb);
                   10358:                                     foreach my $part (@{$res->parts()}) { 
                   10359:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   10360:                                         unless (($slot_status == $res->RESERVED) ||
                   10361:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   10362:                                             $locked_file = 1;
                   10363:                                         }
1.991     raeburn  10364:                                     }
1.1021    raeburn  10365:                                 } else {
                   10366:                                     $locked_file = 1;
1.991     raeburn  10367:                                 }
                   10368:                             } else {
                   10369:                                 $locked_file = 1;
                   10370:                             }
                   10371:                         }
1.1021    raeburn  10372:                    }
                   10373:                 } else {
                   10374:                     my @info = split(/\&/,$rest);
                   10375:                     my $currsize = $info[6]/1000;
                   10376:                     if ($currsize < $filesize) {
                   10377:                         my $extra = $filesize - $currsize;
                   10378:                         if (($current_disk_usage + $extra) > $disk_quota) {
                   10379:                             my $msg = '<span class="LC_error">'.
                   10380:                                       &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.',
                   10381:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</span>'.
                   10382:                                       '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   10383:                                                    $disk_quota,$current_disk_usage);
                   10384:                             return ('will_exceed_quota',$msg);
                   10385:                         }
1.984     raeburn  10386:                     }
                   10387:                 }
1.661     raeburn  10388:             }
                   10389:         }
                   10390:     }
                   10391:     if (($current_disk_usage + $filesize) > $disk_quota){
                   10392:         my $msg = '<span class="LC_error">'.
                   10393:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</span>'.
                   10394:                   '<br />'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage);
                   10395:         return ('will_exceed_quota',$msg);
                   10396:     } elsif ($found_file) {
                   10397:         if ($locked_file) {
                   10398:             my $msg = '<span class="LC_error">';
                   10399:             $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>');
                   10400:             $msg .= '</span><br />';
                   10401:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   10402:             return ('file_locked',$msg);
                   10403:         } else {
                   10404:             my $msg = '<span class="LC_error">';
1.984     raeburn  10405:             $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  10406:             $msg .= '</span>';
1.984     raeburn  10407:             return ('existingfile',$msg);
1.661     raeburn  10408:         }
                   10409:     }
                   10410: }
                   10411: 
1.987     raeburn  10412: sub check_for_traversal {
                   10413:     my ($path,$url,$toplevel) = @_;
                   10414:     my @parts=split(/\//,$path);
                   10415:     my $cleanpath;
                   10416:     my $fullpath = $url;
                   10417:     for (my $i=0;$i<@parts;$i++) {
                   10418:         next if ($parts[$i] eq '.');
                   10419:         if ($parts[$i] eq '..') {
                   10420:             $fullpath =~ s{([^/]+/)$}{};
                   10421:         } else {
                   10422:             $fullpath .= $parts[$i].'/';
                   10423:         }
                   10424:     }
                   10425:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   10426:         $cleanpath = $1;
                   10427:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   10428:         my $curr_toprel = $1;
                   10429:         my @parts = split(/\//,$curr_toprel);
                   10430:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   10431:         my @urlparts = split(/\//,$url_toprel);
                   10432:         my $doubledots;
                   10433:         my $startdiff = -1;
                   10434:         for (my $i=0; $i<@urlparts; $i++) {
                   10435:             if ($startdiff == -1) {
                   10436:                 unless ($urlparts[$i] eq $parts[$i]) {
                   10437:                     $startdiff = $i;
                   10438:                     $doubledots .= '../';
                   10439:                 }
                   10440:             } else {
                   10441:                 $doubledots .= '../';
                   10442:             }
                   10443:         }
                   10444:         if ($startdiff > -1) {
                   10445:             $cleanpath = $doubledots;
                   10446:             for (my $i=$startdiff; $i<@parts; $i++) {
                   10447:                 $cleanpath .= $parts[$i].'/';
                   10448:             }
                   10449:         }
                   10450:     }
                   10451:     $cleanpath =~ s{(/)$}{};
                   10452:     return $cleanpath;
                   10453: }
1.31      albertel 10454: 
1.1053    raeburn  10455: sub is_archive_file {
                   10456:     my ($mimetype) = @_;
                   10457:     if (($mimetype eq 'application/octet-stream') ||
                   10458:         ($mimetype eq 'application/x-stuffit') ||
                   10459:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   10460:         return 1;
                   10461:     }
                   10462:     return;
                   10463: }
                   10464: 
                   10465: sub decompress_form {
1.1065    raeburn  10466:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  10467:     my %lt = &Apache::lonlocal::texthash (
                   10468:         this => 'This file is an archive file.',
1.1067    raeburn  10469:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  10470:         itsc => 'Its contents are as follows:',
1.1053    raeburn  10471:         youm => 'You may wish to extract its contents.',
                   10472:         extr => 'Extract contents',
1.1067    raeburn  10473:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   10474:         proa => 'Process automatically?',
1.1053    raeburn  10475:         yes  => 'Yes',
                   10476:         no   => 'No',
1.1067    raeburn  10477:         fold => 'Title for folder containing movie',
                   10478:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  10479:     );
1.1065    raeburn  10480:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  10481:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  10482:     my $info = &list_archive_contents($fileloc,\@paths);
                   10483:     if (@paths) {
                   10484:         foreach my $path (@paths) {
                   10485:             $path =~ s{^/}{};
1.1067    raeburn  10486:             if ($path =~ m{^([^/]+)/$}) {
                   10487:                 $topdir = $1;
                   10488:             }
1.1065    raeburn  10489:             if ($path =~ m{^([^/]+)/}) {
                   10490:                 $toplevel{$1} = $path;
                   10491:             } else {
                   10492:                 $toplevel{$path} = $path;
                   10493:             }
                   10494:         }
                   10495:     }
1.1067    raeburn  10496:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
                   10497:         my @camtasia = ("$topdir/","$topdir/index.html",
                   10498:                         "$topdir/media/",
                   10499:                         "$topdir/media/$topdir.mp4",
                   10500:                         "$topdir/media/FirstFrame.png",
                   10501:                         "$topdir/media/player.swf",
                   10502:                         "$topdir/media/swfobject.js",
                   10503:                         "$topdir/media/expressInstall.swf");
                   10504:         my @diffs = &compare_arrays(\@paths,\@camtasia);
                   10505:         if (@diffs == 0) {
                   10506:             $is_camtasia = 1;
                   10507:         }
                   10508:     }
                   10509:     my $output;
                   10510:     if ($is_camtasia) {
                   10511:         $output = <<"ENDCAM";
                   10512: <script type="text/javascript" language="Javascript">
                   10513: // <![CDATA[
                   10514: 
                   10515: function camtasiaToggle() {
                   10516:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   10517:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
                   10518:             if (document.uploaded_decompress.autoextract_camtasia[i].value == 1) {
                   10519: 
                   10520:                 document.getElementById('camtasia_titles').style.display='block';
                   10521:             } else {
                   10522:                 document.getElementById('camtasia_titles').style.display='none';
                   10523:             }
                   10524:         }
                   10525:     }
                   10526:     return;
                   10527: }
                   10528: 
                   10529: // ]]>
                   10530: </script>
                   10531: <p>$lt{'camt'}</p>
                   10532: ENDCAM
1.1065    raeburn  10533:     } else {
1.1067    raeburn  10534:         $output = '<p>'.$lt{'this'};
                   10535:         if ($info eq '') {
                   10536:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   10537:         } else {
                   10538:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   10539:                        '<div><pre>'.$info.'</pre></div>';
                   10540:         }
1.1065    raeburn  10541:     }
1.1067    raeburn  10542:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  10543:     my $duplicates;
                   10544:     my $num = 0;
                   10545:     if (ref($dirlist) eq 'ARRAY') {
                   10546:         foreach my $item (@{$dirlist}) {
                   10547:             if (ref($item) eq 'ARRAY') {
                   10548:                 if (exists($toplevel{$item->[0]})) {
                   10549:                     $duplicates .= 
                   10550:                         &start_data_table_row().
                   10551:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10552:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   10553:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   10554:                         'value="1" />'.&mt('Yes').'</label>'.
                   10555:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   10556:                         '<td>'.$item->[0].'</td>';
                   10557:                     if ($item->[2]) {
                   10558:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   10559:                     } else {
                   10560:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   10561:                     }
                   10562:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   10563:                                    '<td>'.
                   10564:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   10565:                                    '</td>'.
                   10566:                                    &end_data_table_row();
                   10567:                     $num ++;
                   10568:                 }
                   10569:             }
                   10570:         }
                   10571:     }
                   10572:     my $itemcount;
                   10573:     if (@paths > 0) {
                   10574:         $itemcount = scalar(@paths);
                   10575:     } else {
                   10576:         $itemcount = 1;
                   10577:     }
1.1067    raeburn  10578:     if ($is_camtasia) {
                   10579:         $output .= $lt{'auto'}.'<br />'.
                   10580:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
                   10581:                    '<input type="radio" name="autoextract_camtasia" value="1" onclick="javascript:camtasiaToggle();" checked="checked" />'.
                   10582:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   10583:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   10584:                    $lt{'no'}.'</label></span><br />'.
                   10585:                    '<div id="camtasia_titles" style="display:block">'.
                   10586:                    &Apache::lonhtmlcommon::start_pick_box().
                   10587:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   10588:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   10589:                    &Apache::lonhtmlcommon::row_closure().
                   10590:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   10591:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   10592:                    &Apache::lonhtmlcommon::row_closure(1).
                   10593:                    &Apache::lonhtmlcommon::end_pick_box().
                   10594:                    '</div>';
                   10595:     }
1.1065    raeburn  10596:     $output .= 
                   10597:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  10598:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   10599:         "\n";
1.1065    raeburn  10600:     if ($duplicates ne '') {
                   10601:         $output .= '<p><span class="LC_warning">'.
                   10602:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   10603:                    &start_data_table().
                   10604:                    &start_data_table_header_row().
                   10605:                    '<th>'.&mt('Overwrite?').'</th>'.
                   10606:                    '<th>'.&mt('Name').'</th>'.
                   10607:                    '<th>'.&mt('Type').'</th>'.
                   10608:                    '<th>'.&mt('Size').'</th>'.
                   10609:                    '<th>'.&mt('Last modified').'</th>'.
                   10610:                    &end_data_table_header_row().
                   10611:                    $duplicates.
                   10612:                    &end_data_table().
                   10613:                    '</p>';
                   10614:     }
1.1067    raeburn  10615:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  10616:     if (ref($hiddenelements) eq 'HASH') {
                   10617:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   10618:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   10619:         }
                   10620:     }
                   10621:     $output .= <<"END";
1.1067    raeburn  10622: <br />
1.1053    raeburn  10623: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   10624: </form>
                   10625: $noextract
                   10626: END
                   10627:     return $output;
                   10628: }
                   10629: 
1.1065    raeburn  10630: sub decompression_utility {
                   10631:     my ($program) = @_;
                   10632:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   10633:     my $location;
                   10634:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   10635:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   10636:                          '/usr/sbin/') {
                   10637:             if (-x $dir.$program) {
                   10638:                 $location = $dir.$program;
                   10639:                 last;
                   10640:             }
                   10641:         }
                   10642:     }
                   10643:     return $location;
                   10644: }
                   10645: 
                   10646: sub list_archive_contents {
                   10647:     my ($file,$pathsref) = @_;
                   10648:     my (@cmd,$output);
                   10649:     my $needsregexp;
                   10650:     if ($file =~ /\.zip$/) {
                   10651:         @cmd = (&decompression_utility('unzip'),"-l");
                   10652:         $needsregexp = 1;
                   10653:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   10654:              ($file =~ /\.tgz$/)) {
                   10655:         @cmd = (&decompression_utility('tar'),"-ztf");
                   10656:     } elsif ($file =~ /\.tar\.bz2$/) {
                   10657:         @cmd = (&decompression_utility('tar'),"-jtf");
                   10658:     } elsif ($file =~ m|\.tar$|) {
                   10659:         @cmd = (&decompression_utility('tar'),"-tf");
                   10660:     }
                   10661:     if (@cmd) {
                   10662:         undef($!);
                   10663:         undef($@);
                   10664:         if (open(my $fh,"-|", @cmd, $file)) {
                   10665:             while (my $line = <$fh>) {
                   10666:                 $output .= $line;
                   10667:                 chomp($line);
                   10668:                 my $item;
                   10669:                 if ($needsregexp) {
                   10670:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   10671:                 } else {
                   10672:                     $item = $line;
                   10673:                 }
                   10674:                 if ($item ne '') {
                   10675:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   10676:                         push(@{$pathsref},$item);
                   10677:                     } 
                   10678:                 }
                   10679:             }
                   10680:             close($fh);
                   10681:         }
                   10682:     }
                   10683:     return $output;
                   10684: }
                   10685: 
1.1053    raeburn  10686: sub decompress_uploaded_file {
                   10687:     my ($file,$dir) = @_;
                   10688:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   10689:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   10690:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   10691:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   10692:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   10693:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   10694:     my $decompressed = $env{'cgi.decompressed'};
                   10695:     &Apache::lonnet::delenv('cgi.file');
                   10696:     &Apache::lonnet::delenv('cgi.dir');
                   10697:     &Apache::lonnet::delenv('cgi.decompressed');
                   10698:     return ($decompressed,$result);
                   10699: }
                   10700: 
1.1055    raeburn  10701: sub process_decompression {
                   10702:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   10703:     my ($dir,$error,$warning,$output);
                   10704:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/) {
                   10705:         $error = &mt('File name not a supported archive file type.').
                   10706:                  '<br />'.&mt('File name should end with one of: [_1].',
                   10707:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   10708:     } else {
                   10709:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   10710:         if ($docuhome eq 'no_host') {
                   10711:             $error = &mt('Could not determine home server for course.');
                   10712:         } else {
                   10713:             my @ids=&Apache::lonnet::current_machine_ids();
                   10714:             my $currdir = "$dir_root/$destination";
                   10715:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   10716:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   10717:                        "$dir_root/$destination";
                   10718:             } else {
                   10719:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   10720:                        "$dir_root/$docudom/$docuname/$destination";
                   10721:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   10722:                     $error = &mt('Archive file not found.');
                   10723:                 }
                   10724:             }
1.1065    raeburn  10725:             my (@to_overwrite,@to_skip);
                   10726:             if ($env{'form.archive_overwrite_total'} > 0) {
                   10727:                 my $total = $env{'form.archive_overwrite_total'};
                   10728:                 for (my $i=0; $i<$total; $i++) {
                   10729:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   10730:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   10731:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   10732:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   10733:                     }
                   10734:                 }
                   10735:             }
                   10736:             my $numskip = scalar(@to_skip);
                   10737:             if (($numskip > 0) && 
                   10738:                 ($numskip == $env{'form.archive_itemcount'})) {
                   10739:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   10740:             } elsif ($dir eq '') {
1.1055    raeburn  10741:                 $error = &mt('Directory containing archive file unavailable.');
                   10742:             } elsif (!$error) {
1.1065    raeburn  10743:                 my ($decompressed,$display);
                   10744:                 if ($numskip > 0) {
                   10745:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   10746:                     mkdir("$dir/$tempdir",0755);
                   10747:                     system("mv $dir/$file $dir/$tempdir/$file");
                   10748:                     ($decompressed,$display) = 
                   10749:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   10750:                     foreach my $item (@to_skip) {
                   10751:                         if (($item ne '') && ($item !~ /\.\./)) {
                   10752:                             if (-f "$dir/$tempdir/$item") { 
                   10753:                                 unlink("$dir/$tempdir/$item");
                   10754:                             } elsif (-d "$dir/$tempdir/$item") {
                   10755:                                 system("rm -rf $dir/$tempdir/$item");
                   10756:                             }
                   10757:                         }
                   10758:                     }
                   10759:                     system("mv $dir/$tempdir/* $dir");
                   10760:                     rmdir("$dir/$tempdir");   
                   10761:                 } else {
                   10762:                     ($decompressed,$display) = 
                   10763:                         &decompress_uploaded_file($file,$dir);
                   10764:                 }
1.1055    raeburn  10765:                 if ($decompressed eq 'ok') {
1.1065    raeburn  10766:                     $output = '<p class="LC_info">'.
                   10767:                               &mt('Files extracted successfully from archive.').
                   10768:                               '</p>'."\n";
1.1055    raeburn  10769:                     my ($warning,$result,@contents);
                   10770:                     my ($newdirlistref,$newlisterror) =
                   10771:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   10772:                                                  $docuname,1);
                   10773:                     my (%is_dir,%changes,@newitems);
                   10774:                     my $dirptr = 16384;
1.1065    raeburn  10775:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  10776:                         foreach my $dir_line (@{$newdirlistref}) {
                   10777:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  10778:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   10779:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  10780:                                 push(@newitems,$item);
                   10781:                                 if ($dirptr&$testdir) {
                   10782:                                     $is_dir{$item} = 1;
                   10783:                                 }
                   10784:                                 $changes{$item} = 1;
                   10785:                             }
                   10786:                         }
                   10787:                     }
                   10788:                     if (keys(%changes) > 0) {
                   10789:                         foreach my $item (sort(@newitems)) {
                   10790:                             if ($changes{$item}) {
                   10791:                                 push(@contents,$item);
                   10792:                             }
                   10793:                         }
                   10794:                     }
                   10795:                     if (@contents > 0) {
1.1067    raeburn  10796:                         my $wantform;
                   10797:                         unless ($env{'form.autoextract_camtasia'}) {
                   10798:                             $wantform = 1;
                   10799:                         }
1.1056    raeburn  10800:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  10801:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   10802:                                                                 $currdir,\%is_dir,
                   10803:                                                                 \%children,\%parent,
1.1056    raeburn  10804:                                                                 \@contents,\%dirorder,
                   10805:                                                                 \%titles,$wantform);
1.1055    raeburn  10806:                         if ($datatable ne '') {
                   10807:                             $output .= &archive_options_form('decompressed',$datatable,
                   10808:                                                              $count,$hiddenelem);
1.1065    raeburn  10809:                             my $startcount = 6;
1.1055    raeburn  10810:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  10811:                                                            \%titles,\%children);
1.1055    raeburn  10812:                         }
1.1067    raeburn  10813:                         if ($env{'form.autoextract_camtasia'}) {
                   10814:                             my %displayed;
                   10815:                             my $total = 1;
                   10816:                             $env{'form.archive_directory'} = [];
                   10817:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   10818:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   10819:                                 $path =~ s{/$}{};
                   10820:                                 my $item;
                   10821:                                 if ($path ne '') {
                   10822:                                     $item = "$path/$titles{$i}";
                   10823:                                 } else {
                   10824:                                     $item = $titles{$i};
                   10825:                                 }
                   10826:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   10827:                                 if ($item eq $contents[0]) {
                   10828:                                     push(@{$env{'form.archive_directory'}},$i);
                   10829:                                     $env{'form.archive_'.$i} = 'display';
                   10830:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   10831:                                     $displayed{'folder'} = $i;
                   10832:                                 } elsif ($item eq "$contents[0]/index.html") {
                   10833:                                     $env{'form.archive_'.$i} = 'display';
                   10834:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   10835:                                     $displayed{'web'} = $i;
                   10836:                                 } else {
                   10837:                                     if ($item eq "$contents[0]/media") {
                   10838:                                         push(@{$env{'form.archive_directory'}},$i);
                   10839:                                     }
                   10840:                                     $env{'form.archive_'.$i} = 'dependency';
                   10841:                                 }
                   10842:                                 $total ++;
                   10843:                             }
                   10844:                             for (my $i=1; $i<$total; $i++) {
                   10845:                                 next if ($i == $displayed{'web'});
                   10846:                                 next if ($i == $displayed{'folder'});
                   10847:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   10848:                             }
                   10849:                             $env{'form.phase'} = 'decompress_cleanup';
                   10850:                             $env{'form.archivedelete'} = 1;
                   10851:                             $env{'form.archive_count'} = $total-1;
                   10852:                             $output .=
                   10853:                                 &process_extracted_files('coursedocs',$docudom,
                   10854:                                                          $docuname,$destination,
                   10855:                                                          $dir_root,$hiddenelem);
                   10856:                         }
1.1055    raeburn  10857:                     } else {
                   10858:                         $warning = &mt('No new items extracted from archive file.');
                   10859:                     }
                   10860:                 } else {
                   10861:                     $output = $display;
                   10862:                     $error = &mt('An error occurred during extraction from the archive file.');
                   10863:                 }
                   10864:             }
                   10865:         }
                   10866:     }
                   10867:     if ($error) {
                   10868:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   10869:                    $error.'</p>'."\n";
                   10870:     }
                   10871:     if ($warning) {
                   10872:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   10873:     }
                   10874:     return $output;
                   10875: }
                   10876: 
                   10877: sub get_extracted {
1.1056    raeburn  10878:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   10879:         $titles,$wantform) = @_;
1.1055    raeburn  10880:     my $count = 0;
                   10881:     my $depth = 0;
                   10882:     my $datatable;
1.1056    raeburn  10883:     my @hierarchy;
1.1055    raeburn  10884:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  10885:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   10886:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  10887:     foreach my $item (@{$contents}) {
                   10888:         $count ++;
1.1056    raeburn  10889:         @{$dirorder->{$count}} = @hierarchy;
                   10890:         $titles->{$count} = $item;
1.1055    raeburn  10891:         &archive_hierarchy($depth,$count,$parent,$children);
                   10892:         if ($wantform) {
                   10893:             $datatable .= &archive_row($is_dir->{$item},$item,
                   10894:                                        $currdir,$depth,$count);
                   10895:         }
                   10896:         if ($is_dir->{$item}) {
                   10897:             $depth ++;
1.1056    raeburn  10898:             push(@hierarchy,$count);
                   10899:             $parent->{$depth} = $count;
1.1055    raeburn  10900:             $datatable .=
                   10901:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  10902:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   10903:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  10904:             $depth --;
1.1056    raeburn  10905:             pop(@hierarchy);
1.1055    raeburn  10906:         }
                   10907:     }
                   10908:     return ($count,$datatable);
                   10909: }
                   10910: 
                   10911: sub recurse_extracted_archive {
1.1056    raeburn  10912:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   10913:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  10914:     my $result='';
1.1056    raeburn  10915:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   10916:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   10917:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  10918:         return $result;
                   10919:     }
                   10920:     my $dirptr = 16384;
                   10921:     my ($newdirlistref,$newlisterror) =
                   10922:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   10923:     if (ref($newdirlistref) eq 'ARRAY') {
                   10924:         foreach my $dir_line (@{$newdirlistref}) {
                   10925:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   10926:             unless ($item =~ /^\.+$/) {
                   10927:                 $$count ++;
1.1056    raeburn  10928:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   10929:                 $titles->{$$count} = $item;
1.1055    raeburn  10930:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  10931: 
1.1055    raeburn  10932:                 my $is_dir;
                   10933:                 if ($dirptr&$testdir) {
                   10934:                     $is_dir = 1;
                   10935:                 }
                   10936:                 if ($wantform) {
                   10937:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   10938:                 }
                   10939:                 if ($is_dir) {
                   10940:                     $$depth ++;
1.1056    raeburn  10941:                     push(@{$hierarchy},$$count);
                   10942:                     $parent->{$$depth} = $$count;
1.1055    raeburn  10943:                     $result .=
                   10944:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   10945:                                                    $docuname,$depth,$count,
1.1056    raeburn  10946:                                                    $hierarchy,$dirorder,$children,
                   10947:                                                    $parent,$titles,$wantform);
1.1055    raeburn  10948:                     $$depth --;
1.1056    raeburn  10949:                     pop(@{$hierarchy});
1.1055    raeburn  10950:                 }
                   10951:             }
                   10952:         }
                   10953:     }
                   10954:     return $result;
                   10955: }
                   10956: 
                   10957: sub archive_hierarchy {
                   10958:     my ($depth,$count,$parent,$children) =@_;
                   10959:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   10960:         if (exists($parent->{$depth})) {
                   10961:              $children->{$parent->{$depth}} .= $count.':';
                   10962:         }
                   10963:     }
                   10964:     return;
                   10965: }
                   10966: 
                   10967: sub archive_row {
                   10968:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   10969:     my ($name) = ($item =~ m{([^/]+)$});
                   10970:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  10971:                                        'display'    => 'Add as file',
1.1055    raeburn  10972:                                        'dependency' => 'Include as dependency',
                   10973:                                        'discard'    => 'Discard',
                   10974:                                       );
                   10975:     if ($is_dir) {
1.1059    raeburn  10976:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  10977:     }
1.1056    raeburn  10978:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   10979:     my $offset = 0;
1.1055    raeburn  10980:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  10981:         $offset ++;
1.1065    raeburn  10982:         if ($action ne 'display') {
                   10983:             $offset ++;
                   10984:         }  
1.1055    raeburn  10985:         $output .= '<td><span class="LC_nobreak">'.
                   10986:                    '<label><input type="radio" name="archive_'.$count.
                   10987:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   10988:         my $text = $choices{$action};
                   10989:         if ($is_dir) {
                   10990:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   10991:             if ($action eq 'display') {
1.1059    raeburn  10992:                 $text = &mt('Add as folder');
1.1055    raeburn  10993:             }
1.1056    raeburn  10994:         } else {
                   10995:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   10996: 
                   10997:         }
                   10998:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   10999:         if ($action eq 'dependency') {
                   11000:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11001:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11002:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11003:                        '<option value=""></option>'."\n".
                   11004:                        '</select>'."\n".
                   11005:                        '</div>';
1.1059    raeburn  11006:         } elsif ($action eq 'display') {
                   11007:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11008:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11009:                        '</div>';
1.1055    raeburn  11010:         }
1.1056    raeburn  11011:         $output .= '</td>';
1.1055    raeburn  11012:     }
                   11013:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11014:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11015:     for (my $i=0; $i<$depth; $i++) {
                   11016:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11017:     }
                   11018:     if ($is_dir) {
                   11019:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11020:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11021:     } else {
                   11022:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11023:     }
                   11024:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11025:                &end_data_table_row();
                   11026:     return $output;
                   11027: }
                   11028: 
                   11029: sub archive_options_form {
1.1065    raeburn  11030:     my ($form,$display,$count,$hiddenelem) = @_;
                   11031:     my %lt = &Apache::lonlocal::texthash(
                   11032:                perm => 'Permanently remove archive file?',
                   11033:                hows => 'How should each extracted item be incorporated in the course?',
                   11034:                cont => 'Content actions for all',
                   11035:                addf => 'Add as folder/file',
                   11036:                incd => 'Include as dependency for a displayed file',
                   11037:                disc => 'Discard',
                   11038:                no   => 'No',
                   11039:                yes  => 'Yes',
                   11040:                save => 'Save',
                   11041:     );
                   11042:     my $output = <<"END";
                   11043: <form name="$form" method="post" action="">
                   11044: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11045: <label>
                   11046:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11047: </label>
                   11048: &nbsp;
                   11049: <label>
                   11050:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11051: </span>
                   11052: </p>
                   11053: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11054: <br />$lt{'hows'}
                   11055: <div class="LC_columnSection">
                   11056:   <fieldset>
                   11057:     <legend>$lt{'cont'}</legend>
                   11058:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11059:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11060:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11061:   </fieldset>
                   11062: </div>
                   11063: END
                   11064:     return $output.
1.1055    raeburn  11065:            &start_data_table()."\n".
1.1065    raeburn  11066:            $display."\n".
1.1055    raeburn  11067:            &end_data_table()."\n".
                   11068:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11069:            $hiddenelem.
1.1065    raeburn  11070:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11071:            '</form>';
                   11072: }
                   11073: 
                   11074: sub archive_javascript {
1.1056    raeburn  11075:     my ($startcount,$numitems,$titles,$children) = @_;
                   11076:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11077:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11078:     my $scripttag = <<START;
                   11079: <script type="text/javascript">
                   11080: // <![CDATA[
                   11081: 
                   11082: function checkAll(form,prefix) {
                   11083:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11084:     for (var i=0; i < form.elements.length; i++) {
                   11085:         var id = form.elements[i].id;
                   11086:         if ((id != '') && (id != undefined)) {
                   11087:             if (idstr.test(id)) {
                   11088:                 if (form.elements[i].type == 'radio') {
                   11089:                     form.elements[i].checked = true;
1.1056    raeburn  11090:                     var nostart = i-$startcount;
1.1059    raeburn  11091:                     var offset = nostart%7;
                   11092:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11093:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11094:                 }
                   11095:             }
                   11096:         }
                   11097:     }
                   11098: }
                   11099: 
                   11100: function propagateCheck(form,count) {
                   11101:     if (count > 0) {
1.1059    raeburn  11102:         var startelement = $startcount + ((count-1) * 7);
                   11103:         for (var j=1; j<6; j++) {
                   11104:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  11105:                 var item = startelement + j; 
                   11106:                 if (form.elements[item].type == 'radio') {
                   11107:                     if (form.elements[item].checked) {
                   11108:                         containerCheck(form,count,j);
                   11109:                         break;
                   11110:                     }
1.1055    raeburn  11111:                 }
                   11112:             }
                   11113:         }
                   11114:     }
                   11115: }
                   11116: 
                   11117: numitems = $numitems
1.1056    raeburn  11118: var titles = new Array(numitems);
                   11119: var parents = new Array(numitems);
1.1055    raeburn  11120: for (var i=0; i<numitems; i++) {
1.1056    raeburn  11121:     parents[i] = new Array;
1.1055    raeburn  11122: }
1.1059    raeburn  11123: var maintitle = '$maintitle';
1.1055    raeburn  11124: 
                   11125: START
                   11126: 
1.1056    raeburn  11127:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   11128:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  11129:         for (my $i=0; $i<@contents; $i ++) {
                   11130:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   11131:         }
                   11132:     }
                   11133: 
1.1056    raeburn  11134:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   11135:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   11136:     }
                   11137: 
1.1055    raeburn  11138:     $scripttag .= <<END;
                   11139: 
                   11140: function containerCheck(form,count,offset) {
                   11141:     if (count > 0) {
1.1056    raeburn  11142:         dependencyCheck(form,count,offset);
1.1059    raeburn  11143:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  11144:         form.elements[item].checked = true;
                   11145:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11146:             if (parents[count].length > 0) {
                   11147:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  11148:                     containerCheck(form,parents[count][j],offset);
                   11149:                 }
                   11150:             }
                   11151:         }
                   11152:     }
                   11153: }
                   11154: 
                   11155: function dependencyCheck(form,count,offset) {
                   11156:     if (count > 0) {
1.1059    raeburn  11157:         var chosen = (offset+$startcount)+7*(count-1);
                   11158:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  11159:         var currtype = form.elements[depitem].type;
                   11160:         if (form.elements[chosen].value == 'dependency') {
                   11161:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   11162:             form.elements[depitem].options.length = 0;
                   11163:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  11164:             for (var i=1; i<=numitems; i++) {
                   11165:                 if (i == count) {
                   11166:                     continue;
                   11167:                 }
1.1059    raeburn  11168:                 var startelement = $startcount + (i-1) * 7;
                   11169:                 for (var j=1; j<6; j++) {
                   11170:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  11171:                         var item = startelement + j;
                   11172:                         if (form.elements[item].type == 'radio') {
                   11173:                             if (form.elements[item].checked) {
                   11174:                                 if (form.elements[item].value == 'display') {
                   11175:                                     var n = form.elements[depitem].options.length;
                   11176:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   11177:                                 }
                   11178:                             }
                   11179:                         }
                   11180:                     }
                   11181:                 }
                   11182:             }
                   11183:         } else {
                   11184:             document.getElementById('arc_depon_'+count).style.display='none';
                   11185:             form.elements[depitem].options.length = 0;
                   11186:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   11187:         }
1.1059    raeburn  11188:         titleCheck(form,count,offset);
1.1056    raeburn  11189:     }
                   11190: }
                   11191: 
                   11192: function propagateSelect(form,count,offset) {
                   11193:     if (count > 0) {
1.1065    raeburn  11194:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  11195:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   11196:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11197:             if (parents[count].length > 0) {
                   11198:                 for (var j=0; j<parents[count].length; j++) {
                   11199:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  11200:                 }
                   11201:             }
                   11202:         }
                   11203:     }
                   11204: }
1.1056    raeburn  11205: 
                   11206: function containerSelect(form,count,offset,picked) {
                   11207:     if (count > 0) {
1.1065    raeburn  11208:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  11209:         if (form.elements[item].type == 'radio') {
                   11210:             if (form.elements[item].value == 'dependency') {
                   11211:                 if (form.elements[item+1].type == 'select-one') {
                   11212:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   11213:                         if (form.elements[item+1].options[i].value == picked) {
                   11214:                             form.elements[item+1].selectedIndex = i;
                   11215:                             break;
                   11216:                         }
                   11217:                     }
                   11218:                 }
                   11219:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   11220:                     if (parents[count].length > 0) {
                   11221:                         for (var j=0; j<parents[count].length; j++) {
                   11222:                             containerSelect(form,parents[count][j],offset,picked);
                   11223:                         }
                   11224:                     }
                   11225:                 }
                   11226:             }
                   11227:         }
                   11228:     }
                   11229: }
                   11230: 
1.1059    raeburn  11231: function titleCheck(form,count,offset) {
                   11232:     if (count > 0) {
                   11233:         var chosen = (offset+$startcount)+7*(count-1);
                   11234:         var depitem = $startcount + ((count-1) * 7) + 2;
                   11235:         var currtype = form.elements[depitem].type;
                   11236:         if (form.elements[chosen].value == 'display') {
                   11237:             document.getElementById('arc_title_'+count).style.display='block';
                   11238:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   11239:                 document.getElementById('archive_title_'+count).value=maintitle;
                   11240:             }
                   11241:         } else {
                   11242:             document.getElementById('arc_title_'+count).style.display='none';
                   11243:             if (currtype == 'text') { 
                   11244:                 document.getElementById('archive_title_'+count).value='';
                   11245:             }
                   11246:         }
                   11247:     }
                   11248:     return;
                   11249: }
                   11250: 
1.1055    raeburn  11251: // ]]>
                   11252: </script>
                   11253: END
                   11254:     return $scripttag;
                   11255: }
                   11256: 
                   11257: sub process_extracted_files {
1.1067    raeburn  11258:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  11259:     my $numitems = $env{'form.archive_count'};
                   11260:     return unless ($numitems);
                   11261:     my @ids=&Apache::lonnet::current_machine_ids();
                   11262:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  11263:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  11264:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11265:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11266:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   11267:         $pathtocheck = "$dir_root/$destination";
                   11268:         $dir = $dir_root;
                   11269:         $ishome = 1;
                   11270:     } else {
                   11271:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   11272:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   11273:         $dir = "$dir_root/$docudom/$docuname";    
                   11274:     }
                   11275:     my $currdir = "$dir_root/$destination";
                   11276:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   11277:     if ($env{'form.folderpath'}) {
                   11278:         my @items = split('&',$env{'form.folderpath'});
                   11279:         $folders{'0'} = $items[-2];
                   11280:         $containers{'0'}='sequence';
                   11281:     } elsif ($env{'form.pagepath'}) {
                   11282:         my @items = split('&',$env{'form.pagepath'});
                   11283:         $folders{'0'} = $items[-2];
                   11284:         $containers{'0'}='page';
                   11285:     }
                   11286:     my @archdirs = &get_env_multiple('form.archive_directory');
                   11287:     if ($numitems) {
                   11288:         for (my $i=1; $i<=$numitems; $i++) {
                   11289:             my $path = $env{'form.archive_content_'.$i};
                   11290:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   11291:                 my $item = $1;
                   11292:                 $toplevelitems{$item} = $i;
                   11293:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   11294:                     $is_dir{$item} = 1;
                   11295:                 }
                   11296:             }
                   11297:         }
                   11298:     }
1.1067    raeburn  11299:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  11300:     if (keys(%toplevelitems) > 0) {
                   11301:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  11302:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   11303:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  11304:     }
1.1066    raeburn  11305:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  11306:     if ($numitems) {
                   11307:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  11308:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  11309:             my $path = $env{'form.archive_content_'.$i};
                   11310:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11311:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   11312:                     if ($prefix ne '' && $path ne '') {
                   11313:                         if (-e $prefix.$path) {
1.1066    raeburn  11314:                             if ((@archdirs > 0) && 
                   11315:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   11316:                                 $todeletedir{$prefix.$path} = 1;
                   11317:                             } else {
                   11318:                                 $todelete{$prefix.$path} = 1;
                   11319:                             }
1.1055    raeburn  11320:                         }
                   11321:                     }
                   11322:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  11323:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  11324:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  11325:                     $docstitle = $env{'form.archive_title_'.$i};
                   11326:                     if ($docstitle eq '') {
                   11327:                         $docstitle = $title;
                   11328:                     }
1.1055    raeburn  11329:                     $outer = 0;
1.1056    raeburn  11330:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11331:                         if (@{$dirorder{$i}} > 0) {
                   11332:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  11333:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   11334:                                     $outer = $item;
                   11335:                                     last;
                   11336:                                 }
                   11337:                             }
                   11338:                         }
                   11339:                     }
                   11340:                     my ($errtext,$fatal) = 
                   11341:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   11342:                                                '/'.$folders{$outer}.'.'.
                   11343:                                                $containers{$outer});
                   11344:                     next if ($fatal);
                   11345:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   11346:                         if ($context eq 'coursedocs') {
1.1056    raeburn  11347:                             $mapinner{$i} = time;
1.1055    raeburn  11348:                             $folders{$i} = 'default_'.$mapinner{$i};
                   11349:                             $containers{$i} = 'sequence';
                   11350:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11351:                                       $folders{$i}.'.'.$containers{$i};
                   11352:                             my $newidx = &LONCAPA::map::getresidx();
                   11353:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11354:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11355:                             push(@LONCAPA::map::order,$newidx);
                   11356:                             my ($outtext,$errtext) =
                   11357:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11358:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11359:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  11360:                             $newseqid{$i} = $newidx;
1.1067    raeburn  11361:                             unless ($errtext) {
                   11362:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   11363:                             }
1.1055    raeburn  11364:                         }
                   11365:                     } else {
                   11366:                         if ($context eq 'coursedocs') {
                   11367:                             my $newidx=&LONCAPA::map::getresidx();
                   11368:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   11369:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   11370:                                       $title;
                   11371:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   11372:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   11373:                             }
                   11374:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11375:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   11376:                             }
                   11377:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   11378:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  11379:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  11380:                                 unless ($ishome) {
                   11381:                                     my $fetch = "$newdest{$i}/$title";
                   11382:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   11383:                                     $prompttofetch{$fetch} = 1;
                   11384:                                 }
1.1055    raeburn  11385:                             }
                   11386:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  11387:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  11388:                             push(@LONCAPA::map::order, $newidx);
                   11389:                             my ($outtext,$errtext)=
                   11390:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   11391:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  11392:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  11393:                             unless ($errtext) {
                   11394:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   11395:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   11396:                                 }
                   11397:                             }
1.1055    raeburn  11398:                         }
                   11399:                     }
1.1086    raeburn  11400:                 }
                   11401:             } else {
                   11402:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11403:             }
                   11404:         }
                   11405:         for (my $i=1; $i<=$numitems; $i++) {
                   11406:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   11407:             my $path = $env{'form.archive_content_'.$i};
                   11408:             if ($path =~ /^\Q$pathtocheck\E/) {
                   11409:                 my ($title) = ($path =~ m{/([^/]+)$});
                   11410:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   11411:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   11412:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   11413:                         my ($itemidx,$fullpath,$relpath);
                   11414:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   11415:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  11416:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  11417:                                 if ($dirorder{$i}->[$j] eq $container) {
                   11418:                                     $itemidx = $j;
1.1056    raeburn  11419:                                 }
                   11420:                             }
1.1086    raeburn  11421:                         }
                   11422:                         if ($itemidx eq '') {
                   11423:                             $itemidx =  0;
                   11424:                         } 
                   11425:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   11426:                             if ($mapinner{$referrer{$i}}) {
                   11427:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   11428:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11429:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11430:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11431:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11432:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11433:                                             if (!-e $fullpath) {
                   11434:                                                 mkdir($fullpath,0755);
1.1056    raeburn  11435:                                             }
                   11436:                                         }
1.1086    raeburn  11437:                                     } else {
                   11438:                                         last;
1.1056    raeburn  11439:                                     }
1.1086    raeburn  11440:                                 }
                   11441:                             }
                   11442:                         } elsif ($newdest{$referrer{$i}}) {
                   11443:                             $fullpath = $newdest{$referrer{$i}};
                   11444:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   11445:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   11446:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   11447:                                     last;
                   11448:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   11449:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   11450:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11451:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   11452:                                         if (!-e $fullpath) {
                   11453:                                             mkdir($fullpath,0755);
1.1056    raeburn  11454:                                         }
                   11455:                                     }
1.1086    raeburn  11456:                                 } else {
                   11457:                                     last;
1.1056    raeburn  11458:                                 }
1.1055    raeburn  11459:                             }
                   11460:                         }
1.1086    raeburn  11461:                         if ($fullpath ne '') {
                   11462:                             if (-e "$prefix$path") {
                   11463:                                 system("mv $prefix$path $fullpath/$title");
                   11464:                             }
                   11465:                             if (-e "$fullpath/$title") {
                   11466:                                 my $showpath;
                   11467:                                 if ($relpath ne '') {
                   11468:                                     $showpath = "$relpath/$title";
                   11469:                                 } else {
                   11470:                                     $showpath = "/$title";
                   11471:                                 } 
                   11472:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   11473:                             } 
                   11474:                             unless ($ishome) {
                   11475:                                 my $fetch = "$fullpath/$title";
                   11476:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   11477:                                 $prompttofetch{$fetch} = 1;
                   11478:                             }
                   11479:                         }
1.1055    raeburn  11480:                     }
1.1086    raeburn  11481:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   11482:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   11483:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  11484:                 }
                   11485:             } else {
                   11486:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   11487:             }
                   11488:         }
                   11489:         if (keys(%todelete)) {
                   11490:             foreach my $key (keys(%todelete)) {
                   11491:                 unlink($key);
1.1066    raeburn  11492:             }
                   11493:         }
                   11494:         if (keys(%todeletedir)) {
                   11495:             foreach my $key (keys(%todeletedir)) {
                   11496:                 rmdir($key);
                   11497:             }
                   11498:         }
                   11499:         foreach my $dir (sort(keys(%is_dir))) {
                   11500:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   11501:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  11502:             }
                   11503:         }
1.1067    raeburn  11504:         if ($result ne '') {
                   11505:             $output .= '<ul>'."\n".
                   11506:                        $result."\n".
                   11507:                        '</ul>';
                   11508:         }
                   11509:         unless ($ishome) {
                   11510:             my $replicationfail;
                   11511:             foreach my $item (keys(%prompttofetch)) {
                   11512:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   11513:                 unless ($fetchresult eq 'ok') {
                   11514:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   11515:                 }
                   11516:             }
                   11517:             if ($replicationfail) {
                   11518:                 $output .= '<p class="LC_error">'.
                   11519:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   11520:                            $replicationfail.
                   11521:                            '</ul></p>';
                   11522:             }
                   11523:         }
1.1055    raeburn  11524:     } else {
                   11525:         $warning = &mt('No items found in archive.');
                   11526:     }
                   11527:     if ($error) {
                   11528:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11529:                    $error.'</p>'."\n";
                   11530:     }
                   11531:     if ($warning) {
                   11532:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11533:     }
                   11534:     return $output;
                   11535: }
                   11536: 
1.1066    raeburn  11537: sub cleanup_empty_dirs {
                   11538:     my ($path) = @_;
                   11539:     if (($path ne '') && (-d $path)) {
                   11540:         if (opendir(my $dirh,$path)) {
                   11541:             my @dircontents = grep(!/^\./,readdir($dirh));
                   11542:             my $numitems = 0;
                   11543:             foreach my $item (@dircontents) {
                   11544:                 if (-d "$path/$item") {
                   11545:                     &recurse_dirs("$path/$item");
                   11546:                     if (-e "$path/$item") {
                   11547:                         $numitems ++;
                   11548:                     }
                   11549:                 } else {
                   11550:                     $numitems ++;
                   11551:                 }
                   11552:             }
                   11553:             if ($numitems == 0) {
                   11554:                 rmdir($path);
                   11555:             }
                   11556:             closedir($dirh);
                   11557:         }
                   11558:     }
                   11559:     return;
                   11560: }
                   11561: 
1.41      ng       11562: =pod
1.45      matthew  11563: 
1.1068    raeburn  11564: =item &get_folder_hierarchy()
                   11565: 
                   11566: Provides hierarchy of names of folders/sub-folders containing the current
                   11567: item,
                   11568: 
                   11569: Inputs: 3
                   11570:      - $navmap - navmaps object
                   11571: 
                   11572:      - $map - url for map (either the trigger itself, or map containing
                   11573:                            the resource, which is the trigger).
                   11574: 
                   11575:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   11576: 
                   11577: Outputs: 1 @pathitems - array of folder/subfolder names.
                   11578: 
                   11579: =cut
                   11580: 
                   11581: sub get_folder_hierarchy {
                   11582:     my ($navmap,$map,$showitem) = @_;
                   11583:     my @pathitems;
                   11584:     if (ref($navmap)) {
                   11585:         my $mapres = $navmap->getResourceByUrl($map);
                   11586:         if (ref($mapres)) {
                   11587:             my $pcslist = $mapres->map_hierarchy();
                   11588:             if ($pcslist ne '') {
                   11589:                 my @pcs = split(/,/,$pcslist);
                   11590:                 foreach my $pc (@pcs) {
                   11591:                     if ($pc == 1) {
                   11592:                         push(@pathitems,&mt('Main Course Documents'));
                   11593:                     } else {
                   11594:                         my $res = $navmap->getByMapPc($pc);
                   11595:                         if (ref($res)) {
                   11596:                             my $title = $res->compTitle();
                   11597:                             $title =~ s/\W+/_/g;
                   11598:                             if ($title ne '') {
                   11599:                                 push(@pathitems,$title);
                   11600:                             }
                   11601:                         }
                   11602:                     }
                   11603:                 }
                   11604:             }
1.1071    raeburn  11605:             if ($showitem) {
                   11606:                 if ($mapres->{ID} eq '0.0') {
                   11607:                     push(@pathitems,&mt('Main Course Documents'));
                   11608:                 } else {
                   11609:                     my $maptitle = $mapres->compTitle();
                   11610:                     $maptitle =~ s/\W+/_/g;
                   11611:                     if ($maptitle ne '') {
                   11612:                         push(@pathitems,$maptitle);
                   11613:                     }
1.1068    raeburn  11614:                 }
                   11615:             }
                   11616:         }
                   11617:     }
                   11618:     return @pathitems;
                   11619: }
                   11620: 
                   11621: =pod
                   11622: 
1.1015    raeburn  11623: =item * &get_turnedin_filepath()
                   11624: 
                   11625: Determines path in a user's portfolio file for storage of files uploaded
                   11626: to a specific essayresponse or dropbox item.
                   11627: 
                   11628: Inputs: 3 required + 1 optional.
                   11629: $symb is symb for resource, $uname and $udom are for current user (required).
                   11630: $caller is optional (can be "submission", if routine is called when storing
                   11631: an upoaded file when "Submit Answer" button was pressed).
                   11632: 
                   11633: Returns array containing $path and $multiresp. 
                   11634: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   11635: than one file upload item.  Callers of routine should append partid as a 
                   11636: subdirectory to $path in cases where $multiresp is 1.
                   11637: 
                   11638: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   11639: 
                   11640: =cut
                   11641: 
                   11642: sub get_turnedin_filepath {
                   11643:     my ($symb,$uname,$udom,$caller) = @_;
                   11644:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   11645:     my $turnindir;
                   11646:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   11647:     $turnindir = $userhash{'turnindir'};
                   11648:     my ($path,$multiresp);
                   11649:     if ($turnindir eq '') {
                   11650:         if ($caller eq 'submission') {
                   11651:             $turnindir = &mt('turned in');
                   11652:             $turnindir =~ s/\W+/_/g;
                   11653:             my %newhash = (
                   11654:                             'turnindir' => $turnindir,
                   11655:                           );
                   11656:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   11657:         }
                   11658:     }
                   11659:     if ($turnindir ne '') {
                   11660:         $path = '/'.$turnindir.'/';
                   11661:         my ($multipart,$turnin,@pathitems);
                   11662:         my $navmap = Apache::lonnavmaps::navmap->new();
                   11663:         if (defined($navmap)) {
                   11664:             my $mapres = $navmap->getResourceByUrl($map);
                   11665:             if (ref($mapres)) {
                   11666:                 my $pcslist = $mapres->map_hierarchy();
                   11667:                 if ($pcslist ne '') {
                   11668:                     foreach my $pc (split(/,/,$pcslist)) {
                   11669:                         my $res = $navmap->getByMapPc($pc);
                   11670:                         if (ref($res)) {
                   11671:                             my $title = $res->compTitle();
                   11672:                             $title =~ s/\W+/_/g;
                   11673:                             if ($title ne '') {
                   11674:                                 push(@pathitems,$title);
                   11675:                             }
                   11676:                         }
                   11677:                     }
                   11678:                 }
                   11679:                 my $maptitle = $mapres->compTitle();
                   11680:                 $maptitle =~ s/\W+/_/g;
                   11681:                 if ($maptitle ne '') {
                   11682:                     push(@pathitems,$maptitle);
                   11683:                 }
                   11684:                 unless ($env{'request.state'} eq 'construct') {
                   11685:                     my $res = $navmap->getBySymb($symb);
                   11686:                     if (ref($res)) {
                   11687:                         my $partlist = $res->parts();
                   11688:                         my $totaluploads = 0;
                   11689:                         if (ref($partlist) eq 'ARRAY') {
                   11690:                             foreach my $part (@{$partlist}) {
                   11691:                                 my @types = $res->responseType($part);
                   11692:                                 my @ids = $res->responseIds($part);
                   11693:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   11694:                                     if ($types[$i] eq 'essay') {
                   11695:                                         my $partid = $part.'_'.$ids[$i];
                   11696:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   11697:                                             $totaluploads ++;
                   11698:                                         }
                   11699:                                     }
                   11700:                                 }
                   11701:                             }
                   11702:                             if ($totaluploads > 1) {
                   11703:                                 $multiresp = 1;
                   11704:                             }
                   11705:                         }
                   11706:                     }
                   11707:                 }
                   11708:             } else {
                   11709:                 return;
                   11710:             }
                   11711:         } else {
                   11712:             return;
                   11713:         }
                   11714:         my $restitle=&Apache::lonnet::gettitle($symb);
                   11715:         $restitle =~ s/\W+/_/g;
                   11716:         if ($restitle eq '') {
                   11717:             $restitle = ($resurl =~ m{/[^/]+$});
                   11718:             if ($restitle eq '') {
                   11719:                 $restitle = time;
                   11720:             }
                   11721:         }
                   11722:         push(@pathitems,$restitle);
                   11723:         $path .= join('/',@pathitems);
                   11724:     }
                   11725:     return ($path,$multiresp);
                   11726: }
                   11727: 
                   11728: =pod
                   11729: 
1.464     albertel 11730: =back
1.41      ng       11731: 
1.112     bowersj2 11732: =head1 CSV Upload/Handling functions
1.38      albertel 11733: 
1.41      ng       11734: =over 4
                   11735: 
1.648     raeburn  11736: =item * &upfile_store($r)
1.41      ng       11737: 
                   11738: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 11739: needs $env{'form.upfile'}
1.41      ng       11740: returns $datatoken to be put into hidden field
                   11741: 
                   11742: =cut
1.31      albertel 11743: 
                   11744: sub upfile_store {
                   11745:     my $r=shift;
1.258     albertel 11746:     $env{'form.upfile'}=~s/\r/\n/gs;
                   11747:     $env{'form.upfile'}=~s/\f/\n/gs;
                   11748:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   11749:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 11750: 
1.258     albertel 11751:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   11752: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 11753:     {
1.158     raeburn  11754:         my $datafile = $r->dir_config('lonDaemons').
                   11755:                            '/tmp/'.$datatoken.'.tmp';
                   11756:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 11757:             print $fh $env{'form.upfile'};
1.158     raeburn  11758:             close($fh);
                   11759:         }
1.31      albertel 11760:     }
                   11761:     return $datatoken;
                   11762: }
                   11763: 
1.56      matthew  11764: =pod
                   11765: 
1.648     raeburn  11766: =item * &load_tmp_file($r)
1.41      ng       11767: 
                   11768: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 11769: needs $env{'form.datatoken'},
                   11770: sets $env{'form.upfile'} to the contents of the file
1.41      ng       11771: 
                   11772: =cut
1.31      albertel 11773: 
                   11774: sub load_tmp_file {
                   11775:     my $r=shift;
                   11776:     my @studentdata=();
                   11777:     {
1.158     raeburn  11778:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 11779:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  11780:         if ( open(my $fh,"<$studentfile") ) {
                   11781:             @studentdata=<$fh>;
                   11782:             close($fh);
                   11783:         }
1.31      albertel 11784:     }
1.258     albertel 11785:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 11786: }
                   11787: 
1.56      matthew  11788: =pod
                   11789: 
1.648     raeburn  11790: =item * &upfile_record_sep()
1.41      ng       11791: 
                   11792: Separate uploaded file into records
                   11793: returns array of records,
1.258     albertel 11794: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       11795: 
                   11796: =cut
1.31      albertel 11797: 
                   11798: sub upfile_record_sep {
1.258     albertel 11799:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 11800:     } else {
1.248     albertel 11801: 	my @records;
1.258     albertel 11802: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 11803: 	    if ($line=~/^\s*$/) { next; }
                   11804: 	    push(@records,$line);
                   11805: 	}
                   11806: 	return @records;
1.31      albertel 11807:     }
                   11808: }
                   11809: 
1.56      matthew  11810: =pod
                   11811: 
1.648     raeburn  11812: =item * &record_sep($record)
1.41      ng       11813: 
1.258     albertel 11814: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       11815: 
                   11816: =cut
                   11817: 
1.263     www      11818: sub takeleft {
                   11819:     my $index=shift;
                   11820:     return substr('0000'.$index,-4,4);
                   11821: }
                   11822: 
1.31      albertel 11823: sub record_sep {
                   11824:     my $record=shift;
                   11825:     my %components=();
1.258     albertel 11826:     if ($env{'form.upfiletype'} eq 'xml') {
                   11827:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 11828:         my $i=0;
1.356     albertel 11829:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 11830:             $field=~s/^(\"|\')//;
                   11831:             $field=~s/(\"|\')$//;
1.263     www      11832:             $components{&takeleft($i)}=$field;
1.31      albertel 11833:             $i++;
                   11834:         }
1.258     albertel 11835:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 11836:         my $i=0;
1.356     albertel 11837:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 11838:             $field=~s/^(\"|\')//;
                   11839:             $field=~s/(\"|\')$//;
1.263     www      11840:             $components{&takeleft($i)}=$field;
1.31      albertel 11841:             $i++;
                   11842:         }
                   11843:     } else {
1.561     www      11844:         my $separator=',';
1.480     banghart 11845:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      11846:             $separator=';';
1.480     banghart 11847:         }
1.31      albertel 11848:         my $i=0;
1.561     www      11849: # the character we are looking for to indicate the end of a quote or a record 
                   11850:         my $looking_for=$separator;
                   11851: # do not add the characters to the fields
                   11852:         my $ignore=0;
                   11853: # we just encountered a separator (or the beginning of the record)
                   11854:         my $just_found_separator=1;
                   11855: # store the field we are working on here
                   11856:         my $field='';
                   11857: # work our way through all characters in record
                   11858:         foreach my $character ($record=~/(.)/g) {
                   11859:             if ($character eq $looking_for) {
                   11860:                if ($character ne $separator) {
                   11861: # Found the end of a quote, again looking for separator
                   11862:                   $looking_for=$separator;
                   11863:                   $ignore=1;
                   11864:                } else {
                   11865: # Found a separator, store away what we got
                   11866:                   $components{&takeleft($i)}=$field;
                   11867: 	          $i++;
                   11868:                   $just_found_separator=1;
                   11869:                   $ignore=0;
                   11870:                   $field='';
                   11871:                }
                   11872:                next;
                   11873:             }
                   11874: # single or double quotation marks after a separator indicate beginning of a quote
                   11875: # we are now looking for the end of the quote and need to ignore separators
                   11876:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   11877:                $looking_for=$character;
                   11878:                next;
                   11879:             }
                   11880: # ignore would be true after we reached the end of a quote
                   11881:             if ($ignore) { next; }
                   11882:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   11883:             $field.=$character;
                   11884:             $just_found_separator=0; 
1.31      albertel 11885:         }
1.561     www      11886: # catch the very last entry, since we never encountered the separator
                   11887:         $components{&takeleft($i)}=$field;
1.31      albertel 11888:     }
                   11889:     return %components;
                   11890: }
                   11891: 
1.144     matthew  11892: ######################################################
                   11893: ######################################################
                   11894: 
1.56      matthew  11895: =pod
                   11896: 
1.648     raeburn  11897: =item * &upfile_select_html()
1.41      ng       11898: 
1.144     matthew  11899: Return HTML code to select a file from the users machine and specify 
                   11900: the file type.
1.41      ng       11901: 
                   11902: =cut
                   11903: 
1.144     matthew  11904: ######################################################
                   11905: ######################################################
1.31      albertel 11906: sub upfile_select_html {
1.144     matthew  11907:     my %Types = (
                   11908:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 11909:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  11910:                  space => &mt('Space separated'),
                   11911:                  tab   => &mt('Tabulator separated'),
                   11912: #                 xml   => &mt('HTML/XML'),
                   11913:                  );
                   11914:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  11915:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  11916:     foreach my $type (sort(keys(%Types))) {
                   11917:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   11918:     }
                   11919:     $Str .= "</select>\n";
                   11920:     return $Str;
1.31      albertel 11921: }
                   11922: 
1.301     albertel 11923: sub get_samples {
                   11924:     my ($records,$toget) = @_;
                   11925:     my @samples=({});
                   11926:     my $got=0;
                   11927:     foreach my $rec (@$records) {
                   11928: 	my %temp = &record_sep($rec);
                   11929: 	if (! grep(/\S/, values(%temp))) { next; }
                   11930: 	if (%temp) {
                   11931: 	    $samples[$got]=\%temp;
                   11932: 	    $got++;
                   11933: 	    if ($got == $toget) { last; }
                   11934: 	}
                   11935:     }
                   11936:     return \@samples;
                   11937: }
                   11938: 
1.144     matthew  11939: ######################################################
                   11940: ######################################################
                   11941: 
1.56      matthew  11942: =pod
                   11943: 
1.648     raeburn  11944: =item * &csv_print_samples($r,$records)
1.41      ng       11945: 
                   11946: Prints a table of sample values from each column uploaded $r is an
                   11947: Apache Request ref, $records is an arrayref from
                   11948: &Apache::loncommon::upfile_record_sep
                   11949: 
                   11950: =cut
                   11951: 
1.144     matthew  11952: ######################################################
                   11953: ######################################################
1.31      albertel 11954: sub csv_print_samples {
                   11955:     my ($r,$records) = @_;
1.662     bisitz   11956:     my $samples = &get_samples($records,5);
1.301     albertel 11957: 
1.594     raeburn  11958:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   11959:               &start_data_table_header_row());
1.356     albertel 11960:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   11961:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  11962:     $r->print(&end_data_table_header_row());
1.301     albertel 11963:     foreach my $hash (@$samples) {
1.594     raeburn  11964: 	$r->print(&start_data_table_row());
1.356     albertel 11965: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 11966: 	    $r->print('<td>');
1.356     albertel 11967: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 11968: 	    $r->print('</td>');
                   11969: 	}
1.594     raeburn  11970: 	$r->print(&end_data_table_row());
1.31      albertel 11971:     }
1.594     raeburn  11972:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 11973: }
                   11974: 
1.144     matthew  11975: ######################################################
                   11976: ######################################################
                   11977: 
1.56      matthew  11978: =pod
                   11979: 
1.648     raeburn  11980: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       11981: 
                   11982: Prints a table to create associations between values and table columns.
1.144     matthew  11983: 
1.41      ng       11984: $r is an Apache Request ref,
                   11985: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  11986: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       11987: 
                   11988: =cut
                   11989: 
1.144     matthew  11990: ######################################################
                   11991: ######################################################
1.31      albertel 11992: sub csv_print_select_table {
                   11993:     my ($r,$records,$d) = @_;
1.301     albertel 11994:     my $i=0;
                   11995:     my $samples = &get_samples($records,1);
1.144     matthew  11996:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  11997: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  11998:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  11999:               '<th>'.&mt('Column').'</th>'.
                   12000:               &end_data_table_header_row()."\n");
1.356     albertel 12001:     foreach my $array_ref (@$d) {
                   12002: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12003: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12004: 
1.875     bisitz   12005: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12006: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12007: 	$r->print('<option value="none"></option>');
1.356     albertel 12008: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12009: 	    $r->print('<option value="'.$sample.'"'.
                   12010:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12011:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12012: 	}
1.594     raeburn  12013: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12014: 	$i++;
                   12015:     }
1.594     raeburn  12016:     $r->print(&end_data_table());
1.31      albertel 12017:     $i--;
                   12018:     return $i;
                   12019: }
1.56      matthew  12020: 
1.144     matthew  12021: ######################################################
                   12022: ######################################################
                   12023: 
1.56      matthew  12024: =pod
1.31      albertel 12025: 
1.648     raeburn  12026: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12027: 
                   12028: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12029: 
                   12030: $r is an Apache Request ref,
                   12031: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12032: $d is an array of 2 element arrays (internal name, displayed name)
                   12033: 
                   12034: =cut
                   12035: 
1.144     matthew  12036: ######################################################
                   12037: ######################################################
1.31      albertel 12038: sub csv_samples_select_table {
                   12039:     my ($r,$records,$d) = @_;
                   12040:     my $i=0;
1.144     matthew  12041:     #
1.662     bisitz   12042:     my $max_samples = 5;
                   12043:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12044:     $r->print(&start_data_table().
                   12045:               &start_data_table_header_row().'<th>'.
                   12046:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12047:               &end_data_table_header_row());
1.301     albertel 12048: 
                   12049:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12050: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12051: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12052: 	foreach my $option (@$d) {
                   12053: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12054: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12055:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12056:                       $display.'</option>');
1.31      albertel 12057: 	}
                   12058: 	$r->print('</select></td><td>');
1.662     bisitz   12059: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12060: 	    if (defined($samples->[$line]{$key})) { 
                   12061: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12062: 	    }
                   12063: 	}
1.594     raeburn  12064: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12065: 	$i++;
                   12066:     }
1.594     raeburn  12067:     $r->print(&end_data_table());
1.31      albertel 12068:     $i--;
                   12069:     return($i);
1.115     matthew  12070: }
                   12071: 
1.144     matthew  12072: ######################################################
                   12073: ######################################################
                   12074: 
1.115     matthew  12075: =pod
                   12076: 
1.648     raeburn  12077: =item * &clean_excel_name($name)
1.115     matthew  12078: 
                   12079: Returns a replacement for $name which does not contain any illegal characters.
                   12080: 
                   12081: =cut
                   12082: 
1.144     matthew  12083: ######################################################
                   12084: ######################################################
1.115     matthew  12085: sub clean_excel_name {
                   12086:     my ($name) = @_;
                   12087:     $name =~ s/[:\*\?\/\\]//g;
                   12088:     if (length($name) > 31) {
                   12089:         $name = substr($name,0,31);
                   12090:     }
                   12091:     return $name;
1.25      albertel 12092: }
1.84      albertel 12093: 
1.85      albertel 12094: =pod
                   12095: 
1.648     raeburn  12096: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 12097: 
                   12098: Returns either 1 or undef
                   12099: 
                   12100: 1 if the part is to be hidden, undef if it is to be shown
                   12101: 
                   12102: Arguments are:
                   12103: 
                   12104: $id the id of the part to be checked
                   12105: $symb, optional the symb of the resource to check
                   12106: $udom, optional the domain of the user to check for
                   12107: $uname, optional the username of the user to check for
                   12108: 
                   12109: =cut
1.84      albertel 12110: 
                   12111: sub check_if_partid_hidden {
                   12112:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 12113:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 12114: 					 $symb,$udom,$uname);
1.141     albertel 12115:     my $truth=1;
                   12116:     #if the string starts with !, then the list is the list to show not hide
                   12117:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 12118:     my @hiddenlist=split(/,/,$hiddenparts);
                   12119:     foreach my $checkid (@hiddenlist) {
1.141     albertel 12120: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 12121:     }
1.141     albertel 12122:     return !$truth;
1.84      albertel 12123: }
1.127     matthew  12124: 
1.138     matthew  12125: 
                   12126: ############################################################
                   12127: ############################################################
                   12128: 
                   12129: =pod
                   12130: 
1.157     matthew  12131: =back 
                   12132: 
1.138     matthew  12133: =head1 cgi-bin script and graphing routines
                   12134: 
1.157     matthew  12135: =over 4
                   12136: 
1.648     raeburn  12137: =item * &get_cgi_id()
1.138     matthew  12138: 
                   12139: Inputs: none
                   12140: 
                   12141: Returns an id which can be used to pass environment variables
                   12142: to various cgi-bin scripts.  These environment variables will
                   12143: be removed from the users environment after a given time by
                   12144: the routine &Apache::lonnet::transfer_profile_to_env.
                   12145: 
                   12146: =cut
                   12147: 
                   12148: ############################################################
                   12149: ############################################################
1.152     albertel 12150: my $uniq=0;
1.136     matthew  12151: sub get_cgi_id {
1.154     albertel 12152:     $uniq=($uniq+1)%100000;
1.280     albertel 12153:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  12154: }
                   12155: 
1.127     matthew  12156: ############################################################
                   12157: ############################################################
                   12158: 
                   12159: =pod
                   12160: 
1.648     raeburn  12161: =item * &DrawBarGraph()
1.127     matthew  12162: 
1.138     matthew  12163: Facilitates the plotting of data in a (stacked) bar graph.
                   12164: Puts plot definition data into the users environment in order for 
                   12165: graph.png to plot it.  Returns an <img> tag for the plot.
                   12166: The bars on the plot are labeled '1','2',...,'n'.
                   12167: 
                   12168: Inputs:
                   12169: 
                   12170: =over 4
                   12171: 
                   12172: =item $Title: string, the title of the plot
                   12173: 
                   12174: =item $xlabel: string, text describing the X-axis of the plot
                   12175: 
                   12176: =item $ylabel: string, text describing the Y-axis of the plot
                   12177: 
                   12178: =item $Max: scalar, the maximum Y value to use in the plot
                   12179: If $Max is < any data point, the graph will not be rendered.
                   12180: 
1.140     matthew  12181: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  12182: they are plotted.  If undefined, default values will be used.
                   12183: 
1.178     matthew  12184: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   12185: 
1.138     matthew  12186: =item @Values: An array of array references.  Each array reference holds data
                   12187: to be plotted in a stacked bar chart.
                   12188: 
1.239     matthew  12189: =item If the final element of @Values is a hash reference the key/value
                   12190: pairs will be added to the graph definition.
                   12191: 
1.138     matthew  12192: =back
                   12193: 
                   12194: Returns:
                   12195: 
                   12196: An <img> tag which references graph.png and the appropriate identifying
                   12197: information for the plot.
                   12198: 
1.127     matthew  12199: =cut
                   12200: 
                   12201: ############################################################
                   12202: ############################################################
1.134     matthew  12203: sub DrawBarGraph {
1.178     matthew  12204:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  12205:     #
                   12206:     if (! defined($colors)) {
                   12207:         $colors = ['#33ff00', 
                   12208:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   12209:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   12210:                   ]; 
                   12211:     }
1.228     matthew  12212:     my $extra_settings = {};
                   12213:     if (ref($Values[-1]) eq 'HASH') {
                   12214:         $extra_settings = pop(@Values);
                   12215:     }
1.127     matthew  12216:     #
1.136     matthew  12217:     my $identifier = &get_cgi_id();
                   12218:     my $id = 'cgi.'.$identifier;        
1.129     matthew  12219:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  12220:         return '';
                   12221:     }
1.225     matthew  12222:     #
                   12223:     my @Labels;
                   12224:     if (defined($labels)) {
                   12225:         @Labels = @$labels;
                   12226:     } else {
                   12227:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   12228:             push (@Labels,$i+1);
                   12229:         }
                   12230:     }
                   12231:     #
1.129     matthew  12232:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  12233:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  12234:     my %ValuesHash;
                   12235:     my $NumSets=1;
                   12236:     foreach my $array (@Values) {
                   12237:         next if (! ref($array));
1.136     matthew  12238:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  12239:             join(',',@$array);
1.129     matthew  12240:     }
1.127     matthew  12241:     #
1.136     matthew  12242:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  12243:     if ($NumBars < 3) {
                   12244:         $width = 120+$NumBars*32;
1.220     matthew  12245:         $xskip = 1;
1.225     matthew  12246:         $bar_width = 30;
                   12247:     } elsif ($NumBars < 5) {
                   12248:         $width = 120+$NumBars*20;
                   12249:         $xskip = 1;
                   12250:         $bar_width = 20;
1.220     matthew  12251:     } elsif ($NumBars < 10) {
1.136     matthew  12252:         $width = 120+$NumBars*15;
                   12253:         $xskip = 1;
                   12254:         $bar_width = 15;
                   12255:     } elsif ($NumBars <= 25) {
                   12256:         $width = 120+$NumBars*11;
                   12257:         $xskip = 5;
                   12258:         $bar_width = 8;
                   12259:     } elsif ($NumBars <= 50) {
                   12260:         $width = 120+$NumBars*8;
                   12261:         $xskip = 5;
                   12262:         $bar_width = 4;
                   12263:     } else {
                   12264:         $width = 120+$NumBars*8;
                   12265:         $xskip = 5;
                   12266:         $bar_width = 4;
                   12267:     }
                   12268:     #
1.137     matthew  12269:     $Max = 1 if ($Max < 1);
                   12270:     if ( int($Max) < $Max ) {
                   12271:         $Max++;
                   12272:         $Max = int($Max);
                   12273:     }
1.127     matthew  12274:     $Title  = '' if (! defined($Title));
                   12275:     $xlabel = '' if (! defined($xlabel));
                   12276:     $ylabel = '' if (! defined($ylabel));
1.369     www      12277:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   12278:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   12279:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  12280:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  12281:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   12282:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   12283:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   12284:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12285:     $ValuesHash{$id.'.height'}   = $height;
                   12286:     $ValuesHash{$id.'.width'}    = $width;
                   12287:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   12288:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   12289:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  12290:     #
1.228     matthew  12291:     # Deal with other parameters
                   12292:     while (my ($key,$value) = each(%$extra_settings)) {
                   12293:         $ValuesHash{$id.'.'.$key} = $value;
                   12294:     }
                   12295:     #
1.646     raeburn  12296:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  12297:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12298: }
                   12299: 
                   12300: ############################################################
                   12301: ############################################################
                   12302: 
                   12303: =pod
                   12304: 
1.648     raeburn  12305: =item * &DrawXYGraph()
1.137     matthew  12306: 
1.138     matthew  12307: Facilitates the plotting of data in an XY graph.
                   12308: Puts plot definition data into the users environment in order for 
                   12309: graph.png to plot it.  Returns an <img> tag for the plot.
                   12310: 
                   12311: Inputs:
                   12312: 
                   12313: =over 4
                   12314: 
                   12315: =item $Title: string, the title of the plot
                   12316: 
                   12317: =item $xlabel: string, text describing the X-axis of the plot
                   12318: 
                   12319: =item $ylabel: string, text describing the Y-axis of the plot
                   12320: 
                   12321: =item $Max: scalar, the maximum Y value to use in the plot
                   12322: If $Max is < any data point, the graph will not be rendered.
                   12323: 
                   12324: =item $colors: Array ref containing the hex color codes for the data to be 
                   12325: plotted in.  If undefined, default values will be used.
                   12326: 
                   12327: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12328: 
                   12329: =item $Ydata: Array ref containing Array refs.  
1.185     www      12330: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  12331: 
                   12332: =item %Values: hash indicating or overriding any default values which are 
                   12333: passed to graph.png.  
                   12334: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12335: 
                   12336: =back
                   12337: 
                   12338: Returns:
                   12339: 
                   12340: An <img> tag which references graph.png and the appropriate identifying
                   12341: information for the plot.
                   12342: 
1.137     matthew  12343: =cut
                   12344: 
                   12345: ############################################################
                   12346: ############################################################
                   12347: sub DrawXYGraph {
                   12348:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   12349:     #
                   12350:     # Create the identifier for the graph
                   12351:     my $identifier = &get_cgi_id();
                   12352:     my $id = 'cgi.'.$identifier;
                   12353:     #
                   12354:     $Title  = '' if (! defined($Title));
                   12355:     $xlabel = '' if (! defined($xlabel));
                   12356:     $ylabel = '' if (! defined($ylabel));
                   12357:     my %ValuesHash = 
                   12358:         (
1.369     www      12359:          $id.'.title'  => &escape($Title),
                   12360:          $id.'.xlabel' => &escape($xlabel),
                   12361:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  12362:          $id.'.y_max_value'=> $Max,
                   12363:          $id.'.labels'     => join(',',@$Xlabels),
                   12364:          $id.'.PlotType'   => 'XY',
                   12365:          );
                   12366:     #
                   12367:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12368:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12369:     }
                   12370:     #
                   12371:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   12372:         return '';
                   12373:     }
                   12374:     my $NumSets=1;
1.138     matthew  12375:     foreach my $array (@{$Ydata}){
1.137     matthew  12376:         next if (! ref($array));
                   12377:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   12378:     }
1.138     matthew  12379:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  12380:     #
                   12381:     # Deal with other parameters
                   12382:     while (my ($key,$value) = each(%Values)) {
                   12383:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  12384:     }
                   12385:     #
1.646     raeburn  12386:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  12387:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   12388: }
                   12389: 
                   12390: ############################################################
                   12391: ############################################################
                   12392: 
                   12393: =pod
                   12394: 
1.648     raeburn  12395: =item * &DrawXYYGraph()
1.138     matthew  12396: 
                   12397: Facilitates the plotting of data in an XY graph with two Y axes.
                   12398: Puts plot definition data into the users environment in order for 
                   12399: graph.png to plot it.  Returns an <img> tag for the plot.
                   12400: 
                   12401: Inputs:
                   12402: 
                   12403: =over 4
                   12404: 
                   12405: =item $Title: string, the title of the plot
                   12406: 
                   12407: =item $xlabel: string, text describing the X-axis of the plot
                   12408: 
                   12409: =item $ylabel: string, text describing the Y-axis of the plot
                   12410: 
                   12411: =item $colors: Array ref containing the hex color codes for the data to be 
                   12412: plotted in.  If undefined, default values will be used.
                   12413: 
                   12414: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   12415: 
                   12416: =item $Ydata1: The first data set
                   12417: 
                   12418: =item $Min1: The minimum value of the left Y-axis
                   12419: 
                   12420: =item $Max1: The maximum value of the left Y-axis
                   12421: 
                   12422: =item $Ydata2: The second data set
                   12423: 
                   12424: =item $Min2: The minimum value of the right Y-axis
                   12425: 
                   12426: =item $Max2: The maximum value of the left Y-axis
                   12427: 
                   12428: =item %Values: hash indicating or overriding any default values which are 
                   12429: passed to graph.png.  
                   12430: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   12431: 
                   12432: =back
                   12433: 
                   12434: Returns:
                   12435: 
                   12436: An <img> tag which references graph.png and the appropriate identifying
                   12437: information for the plot.
1.136     matthew  12438: 
                   12439: =cut
                   12440: 
                   12441: ############################################################
                   12442: ############################################################
1.137     matthew  12443: sub DrawXYYGraph {
                   12444:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   12445:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  12446:     #
                   12447:     # Create the identifier for the graph
                   12448:     my $identifier = &get_cgi_id();
                   12449:     my $id = 'cgi.'.$identifier;
                   12450:     #
                   12451:     $Title  = '' if (! defined($Title));
                   12452:     $xlabel = '' if (! defined($xlabel));
                   12453:     $ylabel = '' if (! defined($ylabel));
                   12454:     my %ValuesHash = 
                   12455:         (
1.369     www      12456:          $id.'.title'  => &escape($Title),
                   12457:          $id.'.xlabel' => &escape($xlabel),
                   12458:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  12459:          $id.'.labels' => join(',',@$Xlabels),
                   12460:          $id.'.PlotType' => 'XY',
                   12461:          $id.'.NumSets' => 2,
1.137     matthew  12462:          $id.'.two_axes' => 1,
                   12463:          $id.'.y1_max_value' => $Max1,
                   12464:          $id.'.y1_min_value' => $Min1,
                   12465:          $id.'.y2_max_value' => $Max2,
                   12466:          $id.'.y2_min_value' => $Min2,
1.136     matthew  12467:          );
                   12468:     #
1.137     matthew  12469:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   12470:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   12471:     }
                   12472:     #
                   12473:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   12474:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  12475:         return '';
                   12476:     }
                   12477:     my $NumSets=1;
1.137     matthew  12478:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  12479:         next if (! ref($array));
                   12480:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  12481:     }
                   12482:     #
                   12483:     # Deal with other parameters
                   12484:     while (my ($key,$value) = each(%Values)) {
                   12485:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  12486:     }
                   12487:     #
1.646     raeburn  12488:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 12489:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  12490: }
                   12491: 
                   12492: ############################################################
                   12493: ############################################################
                   12494: 
                   12495: =pod
                   12496: 
1.157     matthew  12497: =back 
                   12498: 
1.139     matthew  12499: =head1 Statistics helper routines?  
                   12500: 
                   12501: Bad place for them but what the hell.
                   12502: 
1.157     matthew  12503: =over 4
                   12504: 
1.648     raeburn  12505: =item * &chartlink()
1.139     matthew  12506: 
                   12507: Returns a link to the chart for a specific student.  
                   12508: 
                   12509: Inputs:
                   12510: 
                   12511: =over 4
                   12512: 
                   12513: =item $linktext: The text of the link
                   12514: 
                   12515: =item $sname: The students username
                   12516: 
                   12517: =item $sdomain: The students domain
                   12518: 
                   12519: =back
                   12520: 
1.157     matthew  12521: =back
                   12522: 
1.139     matthew  12523: =cut
                   12524: 
                   12525: ############################################################
                   12526: ############################################################
                   12527: sub chartlink {
                   12528:     my ($linktext, $sname, $sdomain) = @_;
                   12529:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      12530:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 12531:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  12532:        '">'.$linktext.'</a>';
1.153     matthew  12533: }
                   12534: 
                   12535: #######################################################
                   12536: #######################################################
                   12537: 
                   12538: =pod
                   12539: 
                   12540: =head1 Course Environment Routines
1.157     matthew  12541: 
                   12542: =over 4
1.153     matthew  12543: 
1.648     raeburn  12544: =item * &restore_course_settings()
1.153     matthew  12545: 
1.648     raeburn  12546: =item * &store_course_settings()
1.153     matthew  12547: 
                   12548: Restores/Store indicated form parameters from the course environment.
                   12549: Will not overwrite existing values of the form parameters.
                   12550: 
                   12551: Inputs: 
                   12552: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   12553: 
                   12554: a hash ref describing the data to be stored.  For example:
                   12555:    
                   12556: %Save_Parameters = ('Status' => 'scalar',
                   12557:     'chartoutputmode' => 'scalar',
                   12558:     'chartoutputdata' => 'scalar',
                   12559:     'Section' => 'array',
1.373     raeburn  12560:     'Group' => 'array',
1.153     matthew  12561:     'StudentData' => 'array',
                   12562:     'Maps' => 'array');
                   12563: 
                   12564: Returns: both routines return nothing
                   12565: 
1.631     raeburn  12566: =back
                   12567: 
1.153     matthew  12568: =cut
                   12569: 
                   12570: #######################################################
                   12571: #######################################################
                   12572: sub store_course_settings {
1.496     albertel 12573:     return &store_settings($env{'request.course.id'},@_);
                   12574: }
                   12575: 
                   12576: sub store_settings {
1.153     matthew  12577:     # save to the environment
                   12578:     # appenv the same items, just to be safe
1.300     albertel 12579:     my $udom  = $env{'user.domain'};
                   12580:     my $uname = $env{'user.name'};
1.496     albertel 12581:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12582:     my %SaveHash;
                   12583:     my %AppHash;
                   12584:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 12585:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 12586:         my $envname = 'environment.'.$basename;
1.258     albertel 12587:         if (exists($env{'form.'.$setting})) {
1.153     matthew  12588:             # Save this value away
                   12589:             if ($type eq 'scalar' &&
1.258     albertel 12590:                 (! exists($env{$envname}) || 
                   12591:                  $env{$envname} ne $env{'form.'.$setting})) {
                   12592:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   12593:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  12594:             } elsif ($type eq 'array') {
                   12595:                 my $stored_form;
1.258     albertel 12596:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  12597:                     $stored_form = join(',',
                   12598:                                         map {
1.369     www      12599:                                             &escape($_);
1.258     albertel 12600:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  12601:                 } else {
                   12602:                     $stored_form = 
1.369     www      12603:                         &escape($env{'form.'.$setting});
1.153     matthew  12604:                 }
                   12605:                 # Determine if the array contents are the same.
1.258     albertel 12606:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  12607:                     $SaveHash{$basename} = $stored_form;
                   12608:                     $AppHash{$envname}   = $stored_form;
                   12609:                 }
                   12610:             }
                   12611:         }
                   12612:     }
                   12613:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 12614:                                           $udom,$uname);
1.153     matthew  12615:     if ($put_result !~ /^(ok|delayed)/) {
                   12616:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   12617:                                  'got error:'.$put_result);
                   12618:     }
                   12619:     # Make sure these settings stick around in this session, too
1.646     raeburn  12620:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  12621:     return;
                   12622: }
                   12623: 
                   12624: sub restore_course_settings {
1.499     albertel 12625:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 12626: }
                   12627: 
                   12628: sub restore_settings {
                   12629:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  12630:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 12631:         next if (exists($env{'form.'.$setting}));
1.496     albertel 12632:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  12633:             '.'.$setting;
1.258     albertel 12634:         if (exists($env{$envname})) {
1.153     matthew  12635:             if ($type eq 'scalar') {
1.258     albertel 12636:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  12637:             } elsif ($type eq 'array') {
1.258     albertel 12638:                 $env{'form.'.$setting} = [ 
1.153     matthew  12639:                                            map { 
1.369     www      12640:                                                &unescape($_); 
1.258     albertel 12641:                                            } split(',',$env{$envname})
1.153     matthew  12642:                                            ];
                   12643:             }
                   12644:         }
                   12645:     }
1.127     matthew  12646: }
                   12647: 
1.618     raeburn  12648: #######################################################
                   12649: #######################################################
                   12650: 
                   12651: =pod
                   12652: 
                   12653: =head1 Domain E-mail Routines  
                   12654: 
                   12655: =over 4
                   12656: 
1.648     raeburn  12657: =item * &build_recipient_list()
1.618     raeburn  12658: 
1.884     raeburn  12659: Build recipient lists for five types of e-mail:
1.766     raeburn  12660: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.884     raeburn  12661: (d) Help requests, (e) Course requests needing approval,  generated by
                   12662: lonerrorhandler.pm, CHECKRPMS, loncron, lonsupportreq.pm and
                   12663: loncoursequeueadmin.pm respectively.
1.618     raeburn  12664: 
                   12665: Inputs:
1.619     raeburn  12666: defmail (scalar - email address of default recipient), 
1.618     raeburn  12667: mailing type (scalar - errormail, packagesmail, or helpdeskmail), 
1.619     raeburn  12668: defdom (domain for which to retrieve configuration settings),
                   12669: origmail (scalar - email address of recipient from loncapa.conf, 
                   12670: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  12671: 
1.655     raeburn  12672: Returns: comma separated list of addresses to which to send e-mail.
                   12673: 
                   12674: =back
1.618     raeburn  12675: 
                   12676: =cut
                   12677: 
                   12678: ############################################################
                   12679: ############################################################
                   12680: sub build_recipient_list {
1.619     raeburn  12681:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  12682:     my @recipients;
                   12683:     my $otheremails;
                   12684:     my %domconfig =
                   12685:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   12686:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  12687:         if (exists($domconfig{'contacts'}{$mailing})) {
                   12688:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   12689:                 my @contacts = ('adminemail','supportemail');
                   12690:                 foreach my $item (@contacts) {
                   12691:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   12692:                         my $addr = $domconfig{'contacts'}{$item}; 
                   12693:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12694:                             push(@recipients,$addr);
                   12695:                         }
1.619     raeburn  12696:                     }
1.766     raeburn  12697:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  12698:                 }
                   12699:             }
1.766     raeburn  12700:         } elsif ($origmail ne '') {
                   12701:             push(@recipients,$origmail);
1.618     raeburn  12702:         }
1.619     raeburn  12703:     } elsif ($origmail ne '') {
                   12704:         push(@recipients,$origmail);
1.618     raeburn  12705:     }
1.688     raeburn  12706:     if (defined($defmail)) {
                   12707:         if ($defmail ne '') {
                   12708:             push(@recipients,$defmail);
                   12709:         }
1.618     raeburn  12710:     }
                   12711:     if ($otheremails) {
1.619     raeburn  12712:         my @others;
                   12713:         if ($otheremails =~ /,/) {
                   12714:             @others = split(/,/,$otheremails);
1.618     raeburn  12715:         } else {
1.619     raeburn  12716:             push(@others,$otheremails);
                   12717:         }
                   12718:         foreach my $addr (@others) {
                   12719:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   12720:                 push(@recipients,$addr);
                   12721:             }
1.618     raeburn  12722:         }
                   12723:     }
1.619     raeburn  12724:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  12725:     return $recipientlist;
                   12726: }
                   12727: 
1.127     matthew  12728: ############################################################
                   12729: ############################################################
1.154     albertel 12730: 
1.655     raeburn  12731: =pod
                   12732: 
                   12733: =head1 Course Catalog Routines
                   12734: 
                   12735: =over 4
                   12736: 
                   12737: =item * &gather_categories()
                   12738: 
                   12739: Converts category definitions - keys of categories hash stored in  
                   12740: coursecategories in configuration.db on the primary library server in a 
                   12741: domain - to an array.  Also generates javascript and idx hash used to 
                   12742: generate Domain Coordinator interface for editing Course Categories.
                   12743: 
                   12744: Inputs:
1.663     raeburn  12745: 
1.655     raeburn  12746: categories (reference to hash of category definitions).
1.663     raeburn  12747: 
1.655     raeburn  12748: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12749:       categories and subcategories).
1.663     raeburn  12750: 
1.655     raeburn  12751: idx (reference to hash of counters used in Domain Coordinator interface for 
                   12752:       editing Course Categories).
1.663     raeburn  12753: 
1.655     raeburn  12754: jsarray (reference to array of categories used to create Javascript arrays for
                   12755:          Domain Coordinator interface for editing Course Categories).
                   12756: 
                   12757: Returns: nothing
                   12758: 
                   12759: Side effects: populates cats, idx and jsarray. 
                   12760: 
                   12761: =cut
                   12762: 
                   12763: sub gather_categories {
                   12764:     my ($categories,$cats,$idx,$jsarray) = @_;
                   12765:     my %counters;
                   12766:     my $num = 0;
                   12767:     foreach my $item (keys(%{$categories})) {
                   12768:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   12769:         if ($container eq '' && $depth == 0) {
                   12770:             $cats->[$depth][$categories->{$item}] = $cat;
                   12771:         } else {
                   12772:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   12773:         }
                   12774:         my ($escitem,$tail) = split(/:/,$item,2);
                   12775:         if ($counters{$tail} eq '') {
                   12776:             $counters{$tail} = $num;
                   12777:             $num ++;
                   12778:         }
                   12779:         if (ref($idx) eq 'HASH') {
                   12780:             $idx->{$item} = $counters{$tail};
                   12781:         }
                   12782:         if (ref($jsarray) eq 'ARRAY') {
                   12783:             push(@{$jsarray->[$counters{$tail}]},$item);
                   12784:         }
                   12785:     }
                   12786:     return;
                   12787: }
                   12788: 
                   12789: =pod
                   12790: 
                   12791: =item * &extract_categories()
                   12792: 
                   12793: Used to generate breadcrumb trails for course categories.
                   12794: 
                   12795: Inputs:
1.663     raeburn  12796: 
1.655     raeburn  12797: categories (reference to hash of category definitions).
1.663     raeburn  12798: 
1.655     raeburn  12799: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12800:       categories and subcategories).
1.663     raeburn  12801: 
1.655     raeburn  12802: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  12803: 
1.655     raeburn  12804: allitems (reference to hash - key is category key 
                   12805:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12806: 
1.655     raeburn  12807: idx (reference to hash of counters used in Domain Coordinator interface for
                   12808:       editing Course Categories).
1.663     raeburn  12809: 
1.655     raeburn  12810: jsarray (reference to array of categories used to create Javascript arrays for
                   12811:          Domain Coordinator interface for editing Course Categories).
                   12812: 
1.665     raeburn  12813: subcats (reference to hash of arrays containing all subcategories within each 
                   12814:          category, -recursive)
                   12815: 
1.655     raeburn  12816: Returns: nothing
                   12817: 
                   12818: Side effects: populates trails and allitems hash references.
                   12819: 
                   12820: =cut
                   12821: 
                   12822: sub extract_categories {
1.665     raeburn  12823:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  12824:     if (ref($categories) eq 'HASH') {
                   12825:         &gather_categories($categories,$cats,$idx,$jsarray);
                   12826:         if (ref($cats->[0]) eq 'ARRAY') {
                   12827:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   12828:                 my $name = $cats->[0][$i];
                   12829:                 my $item = &escape($name).'::0';
                   12830:                 my $trailstr;
                   12831:                 if ($name eq 'instcode') {
                   12832:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  12833:                 } elsif ($name eq 'communities') {
                   12834:                     $trailstr = &mt('Communities');
1.655     raeburn  12835:                 } else {
                   12836:                     $trailstr = $name;
                   12837:                 }
                   12838:                 if ($allitems->{$item} eq '') {
                   12839:                     push(@{$trails},$trailstr);
                   12840:                     $allitems->{$item} = scalar(@{$trails})-1;
                   12841:                 }
                   12842:                 my @parents = ($name);
                   12843:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   12844:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   12845:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  12846:                         if (ref($subcats) eq 'HASH') {
                   12847:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   12848:                         }
                   12849:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   12850:                     }
                   12851:                 } else {
                   12852:                     if (ref($subcats) eq 'HASH') {
                   12853:                         $subcats->{$item} = [];
1.655     raeburn  12854:                     }
                   12855:                 }
                   12856:             }
                   12857:         }
                   12858:     }
                   12859:     return;
                   12860: }
                   12861: 
                   12862: =pod
                   12863: 
                   12864: =item *&recurse_categories()
                   12865: 
                   12866: Recursively used to generate breadcrumb trails for course categories.
                   12867: 
                   12868: Inputs:
1.663     raeburn  12869: 
1.655     raeburn  12870: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   12871:       categories and subcategories).
1.663     raeburn  12872: 
1.655     raeburn  12873: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  12874: 
                   12875: category (current course category, for which breadcrumb trail is being generated).
                   12876: 
                   12877: trails (reference to array of breadcrumb trails for each category).
                   12878: 
1.655     raeburn  12879: allitems (reference to hash - key is category key
                   12880:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  12881: 
1.655     raeburn  12882: parents (array containing containers directories for current category, 
                   12883:          back to top level). 
                   12884: 
                   12885: Returns: nothing
                   12886: 
                   12887: Side effects: populates trails and allitems hash references
                   12888: 
                   12889: =cut
                   12890: 
                   12891: sub recurse_categories {
1.665     raeburn  12892:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  12893:     my $shallower = $depth - 1;
                   12894:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   12895:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   12896:             my $name = $cats->[$depth]{$category}[$k];
                   12897:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   12898:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   12899:             if ($allitems->{$item} eq '') {
                   12900:                 push(@{$trails},$trailstr);
                   12901:                 $allitems->{$item} = scalar(@{$trails})-1;
                   12902:             }
                   12903:             my $deeper = $depth+1;
                   12904:             push(@{$parents},$category);
1.665     raeburn  12905:             if (ref($subcats) eq 'HASH') {
                   12906:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   12907:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   12908:                     my $higher;
                   12909:                     if ($j > 0) {
                   12910:                         $higher = &escape($parents->[$j]).':'.
                   12911:                                   &escape($parents->[$j-1]).':'.$j;
                   12912:                     } else {
                   12913:                         $higher = &escape($parents->[$j]).'::'.$j;
                   12914:                     }
                   12915:                     push(@{$subcats->{$higher}},$subcat);
                   12916:                 }
                   12917:             }
                   12918:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   12919:                                 $subcats);
1.655     raeburn  12920:             pop(@{$parents});
                   12921:         }
                   12922:     } else {
                   12923:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   12924:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   12925:         if ($allitems->{$item} eq '') {
                   12926:             push(@{$trails},$trailstr);
                   12927:             $allitems->{$item} = scalar(@{$trails})-1;
                   12928:         }
                   12929:     }
                   12930:     return;
                   12931: }
                   12932: 
1.663     raeburn  12933: =pod
                   12934: 
                   12935: =item *&assign_categories_table()
                   12936: 
                   12937: Create a datatable for display of hierarchical categories in a domain,
                   12938: with checkboxes to allow a course to be categorized. 
                   12939: 
                   12940: Inputs:
                   12941: 
                   12942: cathash - reference to hash of categories defined for the domain (from
                   12943:           configuration.db)
                   12944: 
                   12945: currcat - scalar with an & separated list of categories assigned to a course. 
                   12946: 
1.919     raeburn  12947: type    - scalar contains course type (Course or Community).
                   12948: 
1.663     raeburn  12949: Returns: $output (markup to be displayed) 
                   12950: 
                   12951: =cut
                   12952: 
                   12953: sub assign_categories_table {
1.919     raeburn  12954:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  12955:     my $output;
                   12956:     if (ref($cathash) eq 'HASH') {
                   12957:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   12958:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   12959:         $maxdepth = scalar(@cats);
                   12960:         if (@cats > 0) {
                   12961:             my $itemcount = 0;
                   12962:             if (ref($cats[0]) eq 'ARRAY') {
                   12963:                 my @currcategories;
                   12964:                 if ($currcat ne '') {
                   12965:                     @currcategories = split('&',$currcat);
                   12966:                 }
1.919     raeburn  12967:                 my $table;
1.663     raeburn  12968:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   12969:                     my $parent = $cats[0][$i];
1.919     raeburn  12970:                     next if ($parent eq 'instcode');
                   12971:                     if ($type eq 'Community') {
                   12972:                         next unless ($parent eq 'communities');
                   12973:                     } else {
                   12974:                         next if ($parent eq 'communities');
                   12975:                     }
1.663     raeburn  12976:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   12977:                     my $item = &escape($parent).'::0';
                   12978:                     my $checked = '';
                   12979:                     if (@currcategories > 0) {
                   12980:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   12981:                             $checked = ' checked="checked"';
1.663     raeburn  12982:                         }
                   12983:                     }
1.919     raeburn  12984:                     my $parent_title = $parent;
                   12985:                     if ($parent eq 'communities') {
                   12986:                         $parent_title = &mt('Communities');
                   12987:                     }
                   12988:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   12989:                               '<input type="checkbox" name="usecategory" value="'.
                   12990:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   12991:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  12992:                     my $depth = 1;
                   12993:                     push(@path,$parent);
1.919     raeburn  12994:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  12995:                     pop(@path);
1.919     raeburn  12996:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  12997:                     $itemcount ++;
                   12998:                 }
1.919     raeburn  12999:                 if ($itemcount) {
                   13000:                     $output = &Apache::loncommon::start_data_table().
                   13001:                               $table.
                   13002:                               &Apache::loncommon::end_data_table();
                   13003:                 }
1.663     raeburn  13004:             }
                   13005:         }
                   13006:     }
                   13007:     return $output;
                   13008: }
                   13009: 
                   13010: =pod
                   13011: 
                   13012: =item *&assign_category_rows()
                   13013: 
                   13014: Create a datatable row for display of nested categories in a domain,
                   13015: with checkboxes to allow a course to be categorized,called recursively.
                   13016: 
                   13017: Inputs:
                   13018: 
                   13019: itemcount - track row number for alternating colors
                   13020: 
                   13021: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13022:       categories and subcategories.
                   13023: 
                   13024: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13025: 
                   13026: parent - parent of current category item
                   13027: 
                   13028: path - Array containing all categories back up through the hierarchy from the
                   13029:        current category to the top level.
                   13030: 
                   13031: currcategories - reference to array of current categories assigned to the course
                   13032: 
                   13033: Returns: $output (markup to be displayed).
                   13034: 
                   13035: =cut
                   13036: 
                   13037: sub assign_category_rows {
                   13038:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13039:     my ($text,$name,$item,$chgstr);
                   13040:     if (ref($cats) eq 'ARRAY') {
                   13041:         my $maxdepth = scalar(@{$cats});
                   13042:         if (ref($cats->[$depth]) eq 'HASH') {
                   13043:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13044:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13045:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13046:                 $text .= '<td><table class="LC_datatable">';
                   13047:                 for (my $j=0; $j<$numchildren; $j++) {
                   13048:                     $name = $cats->[$depth]{$parent}[$j];
                   13049:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13050:                     my $deeper = $depth+1;
                   13051:                     my $checked = '';
                   13052:                     if (ref($currcategories) eq 'ARRAY') {
                   13053:                         if (@{$currcategories} > 0) {
                   13054:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13055:                                 $checked = ' checked="checked"';
1.663     raeburn  13056:                             }
                   13057:                         }
                   13058:                     }
1.664     raeburn  13059:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13060:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13061:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13062:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13063:                              '</td><td>';
1.663     raeburn  13064:                     if (ref($path) eq 'ARRAY') {
                   13065:                         push(@{$path},$name);
                   13066:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13067:                         pop(@{$path});
                   13068:                     }
                   13069:                     $text .= '</td></tr>';
                   13070:                 }
                   13071:                 $text .= '</table></td>';
                   13072:             }
                   13073:         }
                   13074:     }
                   13075:     return $text;
                   13076: }
                   13077: 
1.655     raeburn  13078: ############################################################
                   13079: ############################################################
                   13080: 
                   13081: 
1.443     albertel 13082: sub commit_customrole {
1.664     raeburn  13083:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  13084:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 13085:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   13086:                          ($end?', ending '.localtime($end):'').': <b>'.
                   13087:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  13088:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 13089:                  '</b><br />';
                   13090:     return $output;
                   13091: }
                   13092: 
                   13093: sub commit_standardrole {
1.541     raeburn  13094:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
                   13095:     my ($output,$logmsg,$linefeed);
                   13096:     if ($context eq 'auto') {
                   13097:         $linefeed = "\n";
                   13098:     } else {
                   13099:         $linefeed = "<br />\n";
                   13100:     }  
1.443     albertel 13101:     if ($three eq 'st') {
1.541     raeburn  13102:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
                   13103:                                          $one,$two,$sec,$context);
                   13104:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  13105:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   13106:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 13107:         } else {
1.541     raeburn  13108:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 13109:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13110:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   13111:             if ($context eq 'auto') {
                   13112:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   13113:             } else {
                   13114:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   13115:                &mt('Add to classlist').': <b>ok</b>';
                   13116:             }
                   13117:             $output .= $linefeed;
1.443     albertel 13118:         }
                   13119:     } else {
                   13120:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   13121:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  13122:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  13123:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  13124:         if ($context eq 'auto') {
                   13125:             $output .= $result.$linefeed;
                   13126:         } else {
                   13127:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   13128:         }
1.443     albertel 13129:     }
                   13130:     return $output;
                   13131: }
                   13132: 
                   13133: sub commit_studentrole {
1.541     raeburn  13134:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context) = @_;
1.626     raeburn  13135:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  13136:     if ($context eq 'auto') {
                   13137:         $linefeed = "\n";
                   13138:     } else {
                   13139:         $linefeed = '<br />'."\n";
                   13140:     }
1.443     albertel 13141:     if (defined($one) && defined($two)) {
                   13142:         my $cid=$one.'_'.$two;
                   13143:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   13144:         my $secchange = 0;
                   13145:         my $expire_role_result;
                   13146:         my $modify_section_result;
1.628     raeburn  13147:         if ($oldsec ne '-1') { 
                   13148:             if ($oldsec ne $sec) {
1.443     albertel 13149:                 $secchange = 1;
1.628     raeburn  13150:                 my $now = time;
1.443     albertel 13151:                 my $uurl='/'.$cid;
                   13152:                 $uurl=~s/\_/\//g;
                   13153:                 if ($oldsec) {
                   13154:                     $uurl.='/'.$oldsec;
                   13155:                 }
1.626     raeburn  13156:                 $oldsecurl = $uurl;
1.628     raeburn  13157:                 $expire_role_result = 
1.652     raeburn  13158:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  13159:                 if ($env{'request.course.sec'} ne '') { 
                   13160:                     if ($expire_role_result eq 'refused') {
                   13161:                         my @roles = ('st');
                   13162:                         my @statuses = ('previous');
                   13163:                         my @roledoms = ($one);
                   13164:                         my $withsec = 1;
                   13165:                         my %roleshash = 
                   13166:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   13167:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   13168:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   13169:                             my ($oldstart,$oldend) = 
                   13170:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   13171:                             if ($oldend > 0 && $oldend <= $now) {
                   13172:                                 $expire_role_result = 'ok';
                   13173:                             }
                   13174:                         }
                   13175:                     }
                   13176:                 }
1.443     albertel 13177:                 $result = $expire_role_result;
                   13178:             }
                   13179:         }
                   13180:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.652     raeburn  13181:             $modify_section_result = &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,undef,undef,undef,$sec,$end,$start,'','',$cid,'',$context);
1.443     albertel 13182:             if ($modify_section_result =~ /^ok/) {
                   13183:                 if ($secchange == 1) {
1.628     raeburn  13184:                     if ($sec eq '') {
                   13185:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   13186:                     } else {
                   13187:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   13188:                     }
1.443     albertel 13189:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  13190:                     if ($sec eq '') {
                   13191:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   13192:                     } else {
                   13193:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13194:                     }
1.443     albertel 13195:                 } else {
1.628     raeburn  13196:                     if ($sec eq '') {
                   13197:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   13198:                     } else {
                   13199:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   13200:                     }
1.443     albertel 13201:                 }
                   13202:             } else {
1.628     raeburn  13203:                 if ($secchange) {       
                   13204:                     $$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;
                   13205:                 } else {
                   13206:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   13207:                 }
1.443     albertel 13208:             }
                   13209:             $result = $modify_section_result;
                   13210:         } elsif ($secchange == 1) {
1.628     raeburn  13211:             if ($oldsec eq '') {
                   13212:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_3] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
                   13213:             } else {
                   13214:                 $$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;
                   13215:             }
1.626     raeburn  13216:             if ($expire_role_result eq 'refused') {
                   13217:                 my $newsecurl = '/'.$cid;
                   13218:                 $newsecurl =~ s/\_/\//g;
                   13219:                 if ($sec ne '') {
                   13220:                     $newsecurl.='/'.$sec;
                   13221:                 }
                   13222:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   13223:                     if ($sec eq '') {
                   13224:                         $$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;
                   13225:                     } else {
                   13226:                         $$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;
                   13227:                     }
                   13228:                 }
                   13229:             }
1.443     albertel 13230:         }
                   13231:     } else {
1.626     raeburn  13232:         $$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 13233:         $result = "error: incomplete course id\n";
                   13234:     }
                   13235:     return $result;
                   13236: }
                   13237: 
                   13238: ############################################################
                   13239: ############################################################
                   13240: 
1.566     albertel 13241: sub check_clone {
1.578     raeburn  13242:     my ($args,$linefeed) = @_;
1.566     albertel 13243:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   13244:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   13245:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   13246:     my $clonemsg;
                   13247:     my $can_clone = 0;
1.944     raeburn  13248:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  13249:     if ($lctype ne 'community') {
                   13250:         $lctype = 'course';
                   13251:     }
1.566     albertel 13252:     if ($clonehome eq 'no_host') {
1.944     raeburn  13253:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13254:             $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'});
                   13255:         } else {
                   13256:             $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'});
                   13257:         }     
1.566     albertel 13258:     } else {
                   13259: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  13260:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13261:             if ($clonedesc{'type'} ne 'Community') {
                   13262:                  $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'});
                   13263:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13264:             }
                   13265:         }
1.882     raeburn  13266: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   13267:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 13268: 	    $can_clone = 1;
                   13269: 	} else {
                   13270: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   13271: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   13272: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  13273:             if (grep(/^\*$/,@cloners)) {
                   13274:                 $can_clone = 1;
                   13275:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   13276:                 $can_clone = 1;
                   13277:             } else {
1.908     raeburn  13278:                 my $ccrole = 'cc';
1.944     raeburn  13279:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13280:                     $ccrole = 'co';
                   13281:                 }
1.578     raeburn  13282: 	        my %roleshash =
                   13283: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   13284: 					 $args->{'ccdomain'},
1.908     raeburn  13285:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  13286: 					 [$args->{'clonedomain'}]);
1.908     raeburn  13287: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  13288:                     $can_clone = 1;
                   13289:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   13290:                     $can_clone = 1;
                   13291:                 } else {
1.944     raeburn  13292:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  13293:                         $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'});
                   13294:                     } else {
                   13295:                         $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'});
                   13296:                     }
1.578     raeburn  13297: 	        }
1.566     albertel 13298: 	    }
1.578     raeburn  13299:         }
1.566     albertel 13300:     }
                   13301:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13302: }
                   13303: 
1.444     albertel 13304: sub construct_course {
1.885     raeburn  13305:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category) = @_;
1.444     albertel 13306:     my $outcome;
1.541     raeburn  13307:     my $linefeed =  '<br />'."\n";
                   13308:     if ($context eq 'auto') {
                   13309:         $linefeed = "\n";
                   13310:     }
1.566     albertel 13311: 
                   13312: #
                   13313: # Are we cloning?
                   13314: #
                   13315:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   13316:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  13317: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 13318: 	if ($context ne 'auto') {
1.578     raeburn  13319:             if ($clonemsg ne '') {
                   13320: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   13321:             }
1.566     albertel 13322: 	}
                   13323: 	$outcome .= $clonemsg.$linefeed;
                   13324: 
                   13325:         if (!$can_clone) {
                   13326: 	    return (0,$outcome);
                   13327: 	}
                   13328:     }
                   13329: 
1.444     albertel 13330: #
                   13331: # Open course
                   13332: #
                   13333:     my $crstype = lc($args->{'crstype'});
                   13334:     my %cenv=();
                   13335:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   13336:                                              $args->{'cdescr'},
                   13337:                                              $args->{'curl'},
                   13338:                                              $args->{'course_home'},
                   13339:                                              $args->{'nonstandard'},
                   13340:                                              $args->{'crscode'},
                   13341:                                              $args->{'ccuname'}.':'.
                   13342:                                              $args->{'ccdomain'},
1.882     raeburn  13343:                                              $args->{'crstype'},
1.885     raeburn  13344:                                              $cnum,$context,$category);
1.444     albertel 13345: 
                   13346:     # Note: The testing routines depend on this being output; see 
                   13347:     # Utils::Course. This needs to at least be output as a comment
                   13348:     # if anyone ever decides to not show this, and Utils::Course::new
                   13349:     # will need to be suitably modified.
1.541     raeburn  13350:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  13351:     if ($$courseid =~ /^error:/) {
                   13352:         return (0,$outcome);
                   13353:     }
                   13354: 
1.444     albertel 13355: #
                   13356: # Check if created correctly
                   13357: #
1.479     albertel 13358:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 13359:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  13360:     if ($crsuhome eq 'no_host') {
                   13361:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   13362:         return (0,$outcome);
                   13363:     }
1.541     raeburn  13364:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 13365: 
1.444     albertel 13366: #
1.566     albertel 13367: # Do the cloning
                   13368: #   
                   13369:     if ($can_clone && $cloneid) {
                   13370: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   13371: 	if ($context ne 'auto') {
                   13372: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   13373: 	}
                   13374: 	$outcome .= $clonemsg.$linefeed;
                   13375: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 13376: # Copy all files
1.637     www      13377: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 13378: # Restore URL
1.566     albertel 13379: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 13380: # Restore title
1.566     albertel 13381: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  13382: # Restore creation date, creator and creation context.
                   13383:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   13384:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   13385:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 13386: # Mark as cloned
1.566     albertel 13387: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      13388: # Need to clone grading mode
                   13389:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   13390:         $cenv{'grading'}=$newenv{'grading'};
                   13391: # Do not clone these environment entries
                   13392:         &Apache::lonnet::del('environment',
                   13393:                   ['default_enrollment_start_date',
                   13394:                    'default_enrollment_end_date',
                   13395:                    'question.email',
                   13396:                    'policy.email',
                   13397:                    'comment.email',
                   13398:                    'pch.users.denied',
1.725     raeburn  13399:                    'plc.users.denied',
                   13400:                    'hidefromcat',
                   13401:                    'categories'],
1.638     www      13402:                    $$crsudom,$$crsunum);
1.444     albertel 13403:     }
1.566     albertel 13404: 
1.444     albertel 13405: #
                   13406: # Set environment (will override cloned, if existing)
                   13407: #
                   13408:     my @sections = ();
                   13409:     my @xlists = ();
                   13410:     if ($args->{'crstype'}) {
                   13411:         $cenv{'type'}=$args->{'crstype'};
                   13412:     }
                   13413:     if ($args->{'crsid'}) {
                   13414:         $cenv{'courseid'}=$args->{'crsid'};
                   13415:     }
                   13416:     if ($args->{'crscode'}) {
                   13417:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   13418:     }
                   13419:     if ($args->{'crsquota'} ne '') {
                   13420:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   13421:     } else {
                   13422:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   13423:     }
                   13424:     if ($args->{'ccuname'}) {
                   13425:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   13426:                                         ':'.$args->{'ccdomain'};
                   13427:     } else {
                   13428:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   13429:     }
                   13430:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   13431:     if ($args->{'crssections'}) {
                   13432:         $cenv{'internal.sectionnums'} = '';
                   13433:         if ($args->{'crssections'} =~ m/,/) {
                   13434:             @sections = split/,/,$args->{'crssections'};
                   13435:         } else {
                   13436:             $sections[0] = $args->{'crssections'};
                   13437:         }
                   13438:         if (@sections > 0) {
                   13439:             foreach my $item (@sections) {
                   13440:                 my ($sec,$gp) = split/:/,$item;
                   13441:                 my $class = $args->{'crscode'}.$sec;
                   13442:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   13443:                 $cenv{'internal.sectionnums'} .= $item.',';
                   13444:                 unless ($addcheck eq 'ok') {
                   13445:                     push @badclasses, $class;
                   13446:                 }
                   13447:             }
                   13448:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   13449:         }
                   13450:     }
                   13451: # do not hide course coordinator from staff listing, 
                   13452: # even if privileged
                   13453:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13454: # add crosslistings
                   13455:     if ($args->{'crsxlist'}) {
                   13456:         $cenv{'internal.crosslistings'}='';
                   13457:         if ($args->{'crsxlist'} =~ m/,/) {
                   13458:             @xlists = split/,/,$args->{'crsxlist'};
                   13459:         } else {
                   13460:             $xlists[0] = $args->{'crsxlist'};
                   13461:         }
                   13462:         if (@xlists > 0) {
                   13463:             foreach my $item (@xlists) {
                   13464:                 my ($xl,$gp) = split/:/,$item;
                   13465:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   13466:                 $cenv{'internal.crosslistings'} .= $item.',';
                   13467:                 unless ($addcheck eq 'ok') {
                   13468:                     push @badclasses, $xl;
                   13469:                 }
                   13470:             }
                   13471:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   13472:         }
                   13473:     }
                   13474:     if ($args->{'autoadds'}) {
                   13475:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   13476:     }
                   13477:     if ($args->{'autodrops'}) {
                   13478:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   13479:     }
                   13480: # check for notification of enrollment changes
                   13481:     my @notified = ();
                   13482:     if ($args->{'notify_owner'}) {
                   13483:         if ($args->{'ccuname'} ne '') {
                   13484:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   13485:         }
                   13486:     }
                   13487:     if ($args->{'notify_dc'}) {
                   13488:         if ($uname ne '') { 
1.630     raeburn  13489:             push(@notified,$uname.':'.$udom);
1.444     albertel 13490:         }
                   13491:     }
                   13492:     if (@notified > 0) {
                   13493:         my $notifylist;
                   13494:         if (@notified > 1) {
                   13495:             $notifylist = join(',',@notified);
                   13496:         } else {
                   13497:             $notifylist = $notified[0];
                   13498:         }
                   13499:         $cenv{'internal.notifylist'} = $notifylist;
                   13500:     }
                   13501:     if (@badclasses > 0) {
                   13502:         my %lt=&Apache::lonlocal::texthash(
                   13503:                 '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',
                   13504:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   13505:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   13506:         );
1.541     raeburn  13507:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   13508:                            ' ('.$lt{'adby'}.')';
                   13509:         if ($context eq 'auto') {
                   13510:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 13511:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  13512:             foreach my $item (@badclasses) {
                   13513:                 if ($context eq 'auto') {
                   13514:                     $outcome .= " - $item\n";
                   13515:                 } else {
                   13516:                     $outcome .= "<li>$item</li>\n";
                   13517:                 }
                   13518:             }
                   13519:             if ($context eq 'auto') {
                   13520:                 $outcome .= $linefeed;
                   13521:             } else {
1.566     albertel 13522:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  13523:             }
                   13524:         } 
1.444     albertel 13525:     }
                   13526:     if ($args->{'no_end_date'}) {
                   13527:         $args->{'endaccess'} = 0;
                   13528:     }
                   13529:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   13530:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   13531:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   13532:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   13533:     if ($args->{'showphotos'}) {
                   13534:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   13535:     }
                   13536:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   13537:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   13538:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   13539:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  13540:             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'); 
                   13541:             if ($context eq 'auto') {
                   13542:                 $outcome .= $krb_msg;
                   13543:             } else {
1.566     albertel 13544:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  13545:             }
                   13546:             $outcome .= $linefeed;
1.444     albertel 13547:         }
                   13548:     }
                   13549:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   13550:        if ($args->{'setpolicy'}) {
                   13551:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13552:        }
                   13553:        if ($args->{'setcontent'}) {
                   13554:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   13555:        }
                   13556:     }
                   13557:     if ($args->{'reshome'}) {
                   13558: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   13559: 	$cenv{'reshome'}=~s/\/+$/\//;
                   13560:     }
                   13561: #
                   13562: # course has keyed access
                   13563: #
                   13564:     if ($args->{'setkeys'}) {
                   13565:        $cenv{'keyaccess'}='yes';
                   13566:     }
                   13567: # if specified, key authority is not course, but user
                   13568: # only active if keyaccess is yes
                   13569:     if ($args->{'keyauth'}) {
1.487     albertel 13570: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   13571: 	$user = &LONCAPA::clean_username($user);
                   13572: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     13573: 	if ($user ne '' && $domain ne '') {
1.487     albertel 13574: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 13575: 	}
                   13576:     }
                   13577: 
                   13578:     if ($args->{'disresdis'}) {
                   13579:         $cenv{'pch.roles.denied'}='st';
                   13580:     }
                   13581:     if ($args->{'disablechat'}) {
                   13582:         $cenv{'plc.roles.denied'}='st';
                   13583:     }
                   13584: 
                   13585:     # Record we've not yet viewed the Course Initialization Helper for this 
                   13586:     # course
                   13587:     $cenv{'course.helper.not.run'} = 1;
                   13588:     #
                   13589:     # Use new Randomseed
                   13590:     #
                   13591:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   13592:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   13593:     #
                   13594:     # The encryption code and receipt prefix for this course
                   13595:     #
                   13596:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   13597:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   13598:     #
                   13599:     # By default, use standard grading
                   13600:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   13601: 
1.541     raeburn  13602:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   13603:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13604: #
                   13605: # Open all assignments
                   13606: #
                   13607:     if ($args->{'openall'}) {
                   13608:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   13609:        my %storecontent = ($storeunder         => time,
                   13610:                            $storeunder.'.type' => 'date_start');
                   13611:        
                   13612:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  13613:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 13614:    }
                   13615: #
                   13616: # Set first page
                   13617: #
                   13618:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   13619: 	    || ($cloneid)) {
1.445     albertel 13620: 	use LONCAPA::map;
1.444     albertel 13621: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 13622: 
                   13623: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   13624:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   13625: 
1.444     albertel 13626:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   13627:         my $title; my $url;
                   13628:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   13629: 	    $title=&mt('Syllabus');
1.444     albertel 13630:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   13631:         } else {
1.963     raeburn  13632:             $title=&mt('Table of Contents');
1.444     albertel 13633:             $url='/adm/navmaps';
                   13634:         }
1.445     albertel 13635: 
                   13636:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   13637: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   13638: 
                   13639: 	if ($errtext) { $fatal=2; }
1.541     raeburn  13640:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 13641:     }
1.566     albertel 13642: 
                   13643:     return (1,$outcome);
1.444     albertel 13644: }
                   13645: 
                   13646: ############################################################
                   13647: ############################################################
                   13648: 
1.953     droeschl 13649: #SD
                   13650: # only Community and Course, or anything else?
1.378     raeburn  13651: sub course_type {
                   13652:     my ($cid) = @_;
                   13653:     if (!defined($cid)) {
                   13654:         $cid = $env{'request.course.id'};
                   13655:     }
1.404     albertel 13656:     if (defined($env{'course.'.$cid.'.type'})) {
                   13657:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  13658:     } else {
                   13659:         return 'Course';
1.377     raeburn  13660:     }
                   13661: }
1.156     albertel 13662: 
1.406     raeburn  13663: sub group_term {
                   13664:     my $crstype = &course_type();
                   13665:     my %names = (
                   13666:                   'Course' => 'group',
1.865     raeburn  13667:                   'Community' => 'group',
1.406     raeburn  13668:                 );
                   13669:     return $names{$crstype};
                   13670: }
                   13671: 
1.902     raeburn  13672: sub course_types {
                   13673:     my @types = ('official','unofficial','community');
                   13674:     my %typename = (
                   13675:                          official   => 'Official course',
                   13676:                          unofficial => 'Unofficial course',
                   13677:                          community  => 'Community',
                   13678:                    );
                   13679:     return (\@types,\%typename);
                   13680: }
                   13681: 
1.156     albertel 13682: sub icon {
                   13683:     my ($file)=@_;
1.505     albertel 13684:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 13685:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 13686:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 13687:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   13688: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   13689: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13690: 	            $curfext.".gif") {
                   13691: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   13692: 		$curfext.".gif";
                   13693: 	}
                   13694:     }
1.249     albertel 13695:     return &lonhttpdurl($iconname);
1.154     albertel 13696: } 
1.84      albertel 13697: 
1.575     albertel 13698: sub lonhttpdurl {
1.692     www      13699: #
                   13700: # Had been used for "small fry" static images on separate port 8080.
                   13701: # Modify here if lightweight http functionality desired again.
                   13702: # Currently eliminated due to increasing firewall issues.
                   13703: #
1.575     albertel 13704:     my ($url)=@_;
1.692     www      13705:     return $url;
1.215     albertel 13706: }
                   13707: 
1.213     albertel 13708: sub connection_aborted {
                   13709:     my ($r)=@_;
                   13710:     $r->print(" ");$r->rflush();
                   13711:     my $c = $r->connection;
                   13712:     return $c->aborted();
                   13713: }
                   13714: 
1.221     foxr     13715: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     13716: #    strings as 'strings'.
                   13717: sub escape_single {
1.221     foxr     13718:     my ($input) = @_;
1.223     albertel 13719:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     13720:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   13721:     return $input;
                   13722: }
1.223     albertel 13723: 
1.222     foxr     13724: #  Same as escape_single, but escape's "'s  This 
                   13725: #  can be used for  "strings"
                   13726: sub escape_double {
                   13727:     my ($input) = @_;
                   13728:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   13729:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   13730:     return $input;
                   13731: }
1.223     albertel 13732:  
1.222     foxr     13733: #   Escapes the last element of a full URL.
                   13734: sub escape_url {
                   13735:     my ($url)   = @_;
1.238     raeburn  13736:     my @urlslices = split(/\//, $url,-1);
1.369     www      13737:     my $lastitem = &escape(pop(@urlslices));
1.223     albertel 13738:     return join('/',@urlslices).'/'.$lastitem;
1.222     foxr     13739: }
1.462     albertel 13740: 
1.820     raeburn  13741: sub compare_arrays {
                   13742:     my ($arrayref1,$arrayref2) = @_;
                   13743:     my (@difference,%count);
                   13744:     @difference = ();
                   13745:     %count = ();
                   13746:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   13747:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   13748:         foreach my $element (keys(%count)) {
                   13749:             if ($count{$element} == 1) {
                   13750:                 push(@difference,$element);
                   13751:             }
                   13752:         }
                   13753:     }
                   13754:     return @difference;
                   13755: }
                   13756: 
1.817     bisitz   13757: # -------------------------------------------------------- Initialize user login
1.462     albertel 13758: sub init_user_environment {
1.463     albertel 13759:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 13760:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   13761: 
                   13762:     my $public=($username eq 'public' && $domain eq 'public');
                   13763: 
                   13764: # See if old ID present, if so, remove
                   13765: 
1.1062    raeburn  13766:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 13767:     my $now=time;
                   13768: 
                   13769:     if ($public) {
                   13770: 	my $max_public=100;
                   13771: 	my $oldest;
                   13772: 	my $oldest_time=0;
                   13773: 	for(my $next=1;$next<=$max_public;$next++) {
                   13774: 	    if (-e $lonids."/publicuser_$next.id") {
                   13775: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   13776: 		if ($mtime<$oldest_time || !$oldest_time) {
                   13777: 		    $oldest_time=$mtime;
                   13778: 		    $oldest=$next;
                   13779: 		}
                   13780: 	    } else {
                   13781: 		$cookie="publicuser_$next";
                   13782: 		last;
                   13783: 	    }
                   13784: 	}
                   13785: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   13786:     } else {
1.463     albertel 13787: 	# if this isn't a robot, kill any existing non-robot sessions
                   13788: 	if (!$args->{'robot'}) {
                   13789: 	    opendir(DIR,$lonids);
                   13790: 	    while ($filename=readdir(DIR)) {
                   13791: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   13792: 		    unlink($lonids.'/'.$filename);
                   13793: 		}
1.462     albertel 13794: 	    }
1.463     albertel 13795: 	    closedir(DIR);
1.462     albertel 13796: 	}
                   13797: # Give them a new cookie
1.463     albertel 13798: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      13799: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 13800: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 13801:     
                   13802: # Initialize roles
                   13803: 
1.1062    raeburn  13804: 	($userroles,$firstaccenv,$timerintenv) = 
                   13805:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 13806:     }
                   13807: # ------------------------------------ Check browser type and MathML capability
                   13808: 
                   13809:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
                   13810:         $clientunicode,$clientos) = &decode_user_agent($r);
                   13811: 
                   13812: # ------------------------------------------------------------- Get environment
                   13813: 
                   13814:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   13815:     my ($tmp) = keys(%userenv);
                   13816:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   13817:     } else {
                   13818: 	undef(%userenv);
                   13819:     }
                   13820:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   13821: 	$form->{'interface'}=$userenv{'interface'};
                   13822:     }
                   13823:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   13824: 
                   13825: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   13826:     foreach my $option ('interface','localpath','localres') {
                   13827:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 13828:     }
                   13829: # --------------------------------------------------------- Write first profile
                   13830: 
                   13831:     {
                   13832: 	my %initial_env = 
                   13833: 	    ("user.name"          => $username,
                   13834: 	     "user.domain"        => $domain,
                   13835: 	     "user.home"          => $authhost,
                   13836: 	     "browser.type"       => $clientbrowser,
                   13837: 	     "browser.version"    => $clientversion,
                   13838: 	     "browser.mathml"     => $clientmathml,
                   13839: 	     "browser.unicode"    => $clientunicode,
                   13840: 	     "browser.os"         => $clientos,
                   13841: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   13842: 	     "request.course.fn"  => '',
                   13843: 	     "request.course.uri" => '',
                   13844: 	     "request.course.sec" => '',
                   13845: 	     "request.role"       => 'cm',
                   13846: 	     "request.role.adv"   => $env{'user.adv'},
                   13847: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   13848: 
                   13849:         if ($form->{'localpath'}) {
                   13850: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   13851: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   13852:         }
                   13853: 	
                   13854: 	if ($form->{'interface'}) {
                   13855: 	    $form->{'interface'}=~s/\W//gs;
                   13856: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   13857: 	    $env{'browser.interface'}=$form->{'interface'};
                   13858: 	}
                   13859: 
1.981     raeburn  13860:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  13861:         my %domdef;
                   13862:         unless ($domain eq 'public') {
                   13863:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   13864:         }
1.980     raeburn  13865: 
1.1081    raeburn  13866:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  13867:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  13868:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   13869:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  13870:         }
                   13871: 
1.864     raeburn  13872:         foreach my $crstype ('official','unofficial','community') {
1.765     raeburn  13873:             $userenv{'canrequest.'.$crstype} =
                   13874:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  13875:                                                   'reload','requestcourses',
                   13876:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  13877:         }
                   13878: 
1.1092    raeburn  13879:         $userenv{'canrequest.author'} =
                   13880:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   13881:                                         'reload','requestauthor',
                   13882:                                         \%userenv,\%domdef,\%is_adv);
                   13883:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   13884:                                              $domain,$username);
                   13885:         my $reqstatus = $reqauthor{'author_status'};
                   13886:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   13887:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   13888:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   13889:                                                   $reqauthor{'author'}{'timestamp'};
                   13890:             }
                   13891:         }
                   13892: 
1.462     albertel 13893: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  13894: 
1.462     albertel 13895: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   13896: 		 &GDBM_WRCREAT(),0640)) {
                   13897: 	    &_add_to_env(\%disk_env,\%initial_env);
                   13898: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   13899: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  13900:             if (ref($firstaccenv) eq 'HASH') {
                   13901:                 &_add_to_env(\%disk_env,$firstaccenv);
                   13902:             }
                   13903:             if (ref($timerintenv) eq 'HASH') {
                   13904:                 &_add_to_env(\%disk_env,$timerintenv);
                   13905:             }
1.463     albertel 13906: 	    if (ref($args->{'extra_env'})) {
                   13907: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   13908: 	    }
1.462     albertel 13909: 	    untie(%disk_env);
                   13910: 	} else {
1.705     tempelho 13911: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   13912: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 13913: 	    return 'error: '.$!;
                   13914: 	}
                   13915:     }
                   13916:     $env{'request.role'}='cm';
                   13917:     $env{'request.role.adv'}=$env{'user.adv'};
                   13918:     $env{'browser.type'}=$clientbrowser;
                   13919: 
                   13920:     return $cookie;
                   13921: 
                   13922: }
                   13923: 
                   13924: sub _add_to_env {
                   13925:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  13926:     if (ref($env_data) eq 'HASH') {
                   13927:         while (my ($key,$value) = each(%$env_data)) {
                   13928: 	    $idf->{$prefix.$key} = $value;
                   13929: 	    $env{$prefix.$key}   = $value;
                   13930:         }
1.462     albertel 13931:     }
                   13932: }
                   13933: 
1.685     tempelho 13934: # --- Get the symbolic name of a problem and the url
                   13935: sub get_symb {
                   13936:     my ($request,$silent) = @_;
1.726     raeburn  13937:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 13938:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   13939:     if ($symb eq '') {
                   13940:         if (!$silent) {
1.1071    raeburn  13941:             if (ref($request)) { 
                   13942:                 $request->print("Unable to handle ambiguous references:$url:.");
                   13943:             }
1.685     tempelho 13944:             return ();
                   13945:         }
                   13946:     }
                   13947:     &Apache::lonenc::check_decrypt(\$symb);
                   13948:     return ($symb);
                   13949: }
                   13950: 
                   13951: # --------------------------------------------------------------Get annotation
                   13952: 
                   13953: sub get_annotation {
                   13954:     my ($symb,$enc) = @_;
                   13955: 
                   13956:     my $key = $symb;
                   13957:     if (!$enc) {
                   13958:         $key =
                   13959:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   13960:     }
                   13961:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   13962:     return $annotation{$key};
                   13963: }
                   13964: 
                   13965: sub clean_symb {
1.731     raeburn  13966:     my ($symb,$delete_enc) = @_;
1.685     tempelho 13967: 
                   13968:     &Apache::lonenc::check_decrypt(\$symb);
                   13969:     my $enc = $env{'request.enc'};
1.731     raeburn  13970:     if ($delete_enc) {
1.730     raeburn  13971:         delete($env{'request.enc'});
                   13972:     }
1.685     tempelho 13973: 
                   13974:     return ($symb,$enc);
                   13975: }
1.462     albertel 13976: 
1.990     raeburn  13977: sub build_release_hashes {
                   13978:     my ($checkparms,$checkresponsetypes,$checkcrstypes,$anonsurvey,$randomizetry) = @_;
                   13979:     return unless((ref($checkparms) eq 'HASH') && (ref($checkresponsetypes) eq 'HASH') &&
                   13980:                   (ref($checkcrstypes) eq 'HASH') && (ref($anonsurvey) eq 'HASH') &&
                   13981:                   (ref($randomizetry) eq 'HASH'));
                   13982:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   13983:         my ($item,$name,$value) = split(/:/,$key);
                   13984:         if ($item eq 'parameter') {
                   13985:             if (ref($checkparms->{$name}) eq 'ARRAY') {
                   13986:                 unless(grep(/^\Q$name\E$/,@{$checkparms->{$name}})) {
                   13987:                     push(@{$checkparms->{$name}},$value);
                   13988:                 }
                   13989:             } else {
                   13990:                 push(@{$checkparms->{$name}},$value);
                   13991:             }
                   13992:         } elsif ($item eq 'resourcetag') {
                   13993:             if ($name eq 'responsetype') {
                   13994:                 $checkresponsetypes->{$value} = $Apache::lonnet::needsrelease{$key}
                   13995:             }
                   13996:         } elsif ($item eq 'course') {
                   13997:             if ($name eq 'crstype') {
                   13998:                 $checkcrstypes->{$value} = $Apache::lonnet::needsrelease{$key};
                   13999:             }
                   14000:         }
                   14001:     }
                   14002:     ($anonsurvey->{major},$anonsurvey->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:anonsurvey'});
                   14003:     ($randomizetry->{major},$randomizetry->{minor}) = split(/\./,$Apache::lonnet::needsrelease{'parameter:type:randomizetry'});
                   14004:     return;
                   14005: }
                   14006: 
1.1083    raeburn  14007: sub update_content_constraints {
                   14008:     my ($cdom,$cnum,$chome,$cid) = @_;
                   14009:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   14010:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   14011:     my %checkresponsetypes;
                   14012:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   14013:         my ($item,$name,$value) = split(/:/,$key);
                   14014:         if ($item eq 'resourcetag') {
                   14015:             if ($name eq 'responsetype') {
                   14016:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   14017:             }
                   14018:         }
                   14019:     }
                   14020:     my $navmap = Apache::lonnavmaps::navmap->new();
                   14021:     if (defined($navmap)) {
                   14022:         my %allresponses;
                   14023:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   14024:             my %responses = $res->responseTypes();
                   14025:             foreach my $key (keys(%responses)) {
                   14026:                 next unless(exists($checkresponsetypes{$key}));
                   14027:                 $allresponses{$key} += $responses{$key};
                   14028:             }
                   14029:         }
                   14030:         foreach my $key (keys(%allresponses)) {
                   14031:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   14032:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   14033:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   14034:             }
                   14035:         }
                   14036:         undef($navmap);
                   14037:     }
                   14038:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   14039:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   14040:     }
                   14041:     return;
                   14042: }
                   14043: 
                   14044: sub parse_supplemental_title {
                   14045:     my ($title) = @_;
                   14046: 
                   14047:     my ($foldertitle,$renametitle);
                   14048:     if ($title =~ /&amp;&amp;&amp;/) {
                   14049:         $title = &HTML::Entites::decode($title);
                   14050:     }
                   14051:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   14052:         $renametitle=$4;
                   14053:         my ($time,$uname,$udom) = ($1,$2,$3);
                   14054:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   14055:         my $name =  &plainname($uname,$udom);
                   14056:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   14057:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   14058:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   14059:             $name.': <br />'.$foldertitle;
                   14060:     }
                   14061:     if (wantarray) {
                   14062:         return ($title,$foldertitle,$renametitle);
                   14063:     }
                   14064:     return $title;
                   14065: }
                   14066: 
1.41      ng       14067: =pod
                   14068: 
                   14069: =back
                   14070: 
1.112     bowersj2 14071: =cut
1.41      ng       14072: 
1.112     bowersj2 14073: 1;
                   14074: __END__;
1.41      ng       14075: 

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