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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1217  ! raeburn     4: # $Id: loncommon.pm,v 1.1216 2015/04/09 14:34:38 droeschl Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1108    raeburn    70: use Apache::lonuserutils();
1.1110    raeburn    71: use Apache::lonuserstate();
1.1182    raeburn    72: use Apache::courseclassifier();
1.479     albertel   73: use LONCAPA qw(:DEFAULT :match);
1.657     raeburn    74: use DateTime::TimeZone;
1.687     raeburn    75: use DateTime::Locale::Catalog;
1.1091    foxr       76: use Text::Aspell;
1.1094    raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1174    raeburn    79: use Crypt::DES;
                     80: use DynaLoader; # for Crypt::DES version
1.117     www        81: 
1.517     raeburn    82: # ---------------------------------------------- Designs
                     83: use vars qw(%defaultdesign);
                     84: 
1.22      www        85: my $readit;
                     86: 
1.517     raeburn    87: 
1.157     matthew    88: ##
                     89: ## Global Variables
                     90: ##
1.46      matthew    91: 
1.643     foxr       92: 
                     93: # ----------------------------------------------- SSI with retries:
                     94: #
                     95: 
                     96: =pod
                     97: 
1.648     raeburn    98: =head1 Server Side include with retries:
1.643     foxr       99: 
                    100: =over 4
                    101: 
1.648     raeburn   102: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      103: 
                    104: Performs an ssi with some number of retries.  Retries continue either
                    105: until the result is ok or until the retry count supplied by the
                    106: caller is exhausted.  
                    107: 
                    108: Inputs:
1.648     raeburn   109: 
                    110: =over 4
                    111: 
1.643     foxr      112: resource   - Identifies the resource to insert.
1.648     raeburn   113: 
1.643     foxr      114: retries    - Count of the number of retries allowed.
1.648     raeburn   115: 
1.643     foxr      116: form       - Hash that identifies the rendering options.
                    117: 
1.648     raeburn   118: =back
                    119: 
                    120: Returns:
                    121: 
                    122: =over 4
                    123: 
1.643     foxr      124: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   125: 
1.643     foxr      126: response   - The response from the last attempt (which may or may not have been successful.
                    127: 
1.648     raeburn   128: =back
                    129: 
                    130: =back
                    131: 
1.643     foxr      132: =cut
                    133: 
                    134: sub ssi_with_retries {
                    135:     my ($resource, $retries, %form) = @_;
                    136: 
                    137: 
                    138:     my $ok = 0;			# True if we got a good response.
                    139:     my $content;
                    140:     my $response;
                    141: 
                    142:     # Try to get the ssi done. within the retries count:
                    143: 
                    144:     do {
                    145: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    146: 	$ok      = $response->is_success;
1.650     www       147:         if (!$ok) {
                    148:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    149:         }
1.643     foxr      150: 	$retries--;
                    151:     } while (!$ok && ($retries > 0));
                    152: 
                    153:     if (!$ok) {
                    154: 	$content = '';		# On error return an empty content.
                    155:     }
                    156:     return ($content, $response);
                    157: 
                    158: }
                    159: 
                    160: 
                    161: 
1.20      www       162: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  163: my %language;
1.124     www       164: my %supported_language;
1.1088    foxr      165: my %supported_codes;
1.1048    foxr      166: my %latex_language;		# For choosing hyphenation in <transl..>
                    167: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  168: my %cprtag;
1.192     taceyjo1  169: my %scprtag;
1.351     www       170: my %fe; my %fd; my %fm;
1.41      ng        171: my %category_extensions;
1.12      harris41  172: 
1.46      matthew   173: # ---------------------------------------------- Thesaurus variables
1.144     matthew   174: #
                    175: # %Keywords:
                    176: #      A hash used by &keyword to determine if a word is considered a keyword.
                    177: # $thesaurus_db_file 
                    178: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   179: 
                    180: my %Keywords;
                    181: my $thesaurus_db_file;
                    182: 
1.144     matthew   183: #
                    184: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    185: # thesaurus.tab, and filecategories.tab.
                    186: #
1.18      www       187: BEGIN {
1.46      matthew   188:     # Variable initialization
                    189:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    190:     #
1.22      www       191:     unless ($readit) {
1.12      harris41  192: # ------------------------------------------------------------------- languages
                    193:     {
1.158     raeburn   194:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    195:                                    '/language.tab';
                    196:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  197:             while (my $line = <$fh>) {
                    198:                 next if ($line=~/^\#/);
                    199:                 chomp($line);
1.1088    foxr      200:                 my ($key,$code,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   201:                 $language{$key}=$val.' - '.$enc;
                    202:                 if ($sup) {
                    203:                     $supported_language{$key}=$sup;
1.1088    foxr      204: 		    $supported_codes{$key}   = $code;
1.158     raeburn   205:                 }
1.1048    foxr      206: 		if ($latex) {
                    207: 		    $latex_language_bykey{$key} = $latex;
1.1088    foxr      208: 		    $latex_language{$code} = $latex;
1.1048    foxr      209: 		}
1.158     raeburn   210:             }
                    211:             close($fh);
                    212:         }
1.12      harris41  213:     }
                    214: # ------------------------------------------------------------------ copyrights
                    215:     {
1.158     raeburn   216:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    217:                                   '/copyright.tab';
                    218:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  219:             while (my $line = <$fh>) {
                    220:                 next if ($line=~/^\#/);
                    221:                 chomp($line);
                    222:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   223:                 $cprtag{$key}=$val;
                    224:             }
                    225:             close($fh);
                    226:         }
1.12      harris41  227:     }
1.351     www       228: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  229:     {
                    230:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    231:                                   '/source_copyright.tab';
                    232:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  233:             while (my $line = <$fh>) {
                    234:                 next if ($line =~ /^\#/);
                    235:                 chomp($line);
                    236:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  237:                 $scprtag{$key}=$val;
                    238:             }
                    239:             close($fh);
                    240:         }
                    241:     }
1.63      www       242: 
1.517     raeburn   243: # -------------------------------------------------------------- default domain designs
1.63      www       244:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   245:     my $designfile = $designdir.'/default.tab';
                    246:     if ( open (my $fh,"<$designfile") ) {
                    247:         while (my $line = <$fh>) {
                    248:             next if ($line =~ /^\#/);
                    249:             chomp($line);
                    250:             my ($key,$val)=(split(/\=/,$line));
                    251:             if ($val) { $defaultdesign{$key}=$val; }
                    252:         }
                    253:         close($fh);
1.63      www       254:     }
                    255: 
1.15      harris41  256: # ------------------------------------------------------------- file categories
                    257:     {
1.158     raeburn   258:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    259:                                   '/filecategories.tab';
                    260:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  261: 	    while (my $line = <$fh>) {
                    262: 		next if ($line =~ /^\#/);
                    263: 		chomp($line);
                    264:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   265:                 push @{$category_extensions{lc($category)}},$extension;
                    266:             }
                    267:             close($fh);
                    268:         }
                    269: 
1.15      harris41  270:     }
1.12      harris41  271: # ------------------------------------------------------------------ file types
                    272:     {
1.158     raeburn   273:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    274:                '/filetypes.tab';
                    275:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  276:             while (my $line = <$fh>) {
                    277: 		next if ($line =~ /^\#/);
                    278: 		chomp($line);
                    279:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   280:                 if ($descr ne '') {
                    281:                     $fe{$ending}=lc($emb);
                    282:                     $fd{$ending}=$descr;
1.351     www       283:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   284:                 }
                    285:             }
                    286:             close($fh);
                    287:         }
1.12      harris41  288:     }
1.22      www       289:     &Apache::lonnet::logthis(
1.705     tempelho  290:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       291:     $readit=1;
1.46      matthew   292:     }  # end of unless($readit) 
1.32      matthew   293:     
                    294: }
1.112     bowersj2  295: 
1.42      matthew   296: ###############################################################
                    297: ##           HTML and Javascript Helper Functions            ##
                    298: ###############################################################
                    299: 
                    300: =pod 
                    301: 
1.112     bowersj2  302: =head1 HTML and Javascript Functions
1.42      matthew   303: 
1.112     bowersj2  304: =over 4
                    305: 
1.648     raeburn   306: =item * &browser_and_searcher_javascript()
1.112     bowersj2  307: 
                    308: X<browsing, javascript>X<searching, javascript>Returns a string
                    309: containing javascript with two functions, C<openbrowser> and
                    310: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    311: tags.
1.42      matthew   312: 
1.648     raeburn   313: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   314: 
                    315: inputs: formname, elementname, only, omit
                    316: 
                    317: formname and elementname indicate the name of the html form and name of
                    318: the element that the results of the browsing selection are to be placed in. 
                    319: 
                    320: Specifying 'only' will restrict the browser to displaying only files
1.185     www       321: with the given extension.  Can be a comma separated list.
1.42      matthew   322: 
                    323: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       324: with the given extension.  Can be a comma separated list.
1.42      matthew   325: 
1.648     raeburn   326: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   327: 
                    328: Inputs: formname, elementname
                    329: 
                    330: formname and elementname specify the name of the html form and the name
                    331: of the element the selection from the search results will be placed in.
1.542     raeburn   332: 
1.42      matthew   333: =cut
                    334: 
                    335: sub browser_and_searcher_javascript {
1.199     albertel  336:     my ($mode)=@_;
                    337:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  338:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   339:     return <<END;
1.219     albertel  340: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   341:     var editbrowser = null;
1.135     albertel  342:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       343:         var url = '$resurl/?';
1.42      matthew   344:         if (editbrowser == null) {
                    345:             url += 'launch=1&';
                    346:         }
                    347:         url += 'catalogmode=interactive&';
1.199     albertel  348:         url += 'mode=$mode&';
1.611     albertel  349:         url += 'inhibitmenu=yes&';
1.42      matthew   350:         url += 'form=' + formname + '&';
                    351:         if (only != null) {
                    352:             url += 'only=' + only + '&';
1.217     albertel  353:         } else {
                    354:             url += 'only=&';
                    355: 	}
1.42      matthew   356:         if (omit != null) {
                    357:             url += 'omit=' + omit + '&';
1.217     albertel  358:         } else {
                    359:             url += 'omit=&';
                    360: 	}
1.135     albertel  361:         if (titleelement != null) {
                    362:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  363:         } else {
                    364: 	    url += 'titleelement=&';
                    365: 	}
1.42      matthew   366:         url += 'element=' + elementname + '';
                    367:         var title = 'Browser';
1.435     albertel  368:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   369:         options += ',width=700,height=600';
                    370:         editbrowser = open(url,title,options,'1');
                    371:         editbrowser.focus();
                    372:     }
                    373:     var editsearcher;
1.135     albertel  374:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   375:         var url = '/adm/searchcat?';
                    376:         if (editsearcher == null) {
                    377:             url += 'launch=1&';
                    378:         }
                    379:         url += 'catalogmode=interactive&';
1.199     albertel  380:         url += 'mode=$mode&';
1.42      matthew   381:         url += 'form=' + formname + '&';
1.135     albertel  382:         if (titleelement != null) {
                    383:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  384:         } else {
                    385: 	    url += 'titleelement=&';
                    386: 	}
1.42      matthew   387:         url += 'element=' + elementname + '';
                    388:         var title = 'Search';
1.435     albertel  389:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   390:         options += ',width=700,height=600';
                    391:         editsearcher = open(url,title,options,'1');
                    392:         editsearcher.focus();
                    393:     }
1.219     albertel  394: // END LON-CAPA Internal -->
1.42      matthew   395: END
1.170     www       396: }
                    397: 
                    398: sub lastresurl {
1.258     albertel  399:     if ($env{'environment.lastresurl'}) {
                    400: 	return $env{'environment.lastresurl'}
1.170     www       401:     } else {
                    402: 	return '/res';
                    403:     }
                    404: }
                    405: 
                    406: sub storeresurl {
                    407:     my $resurl=&Apache::lonnet::clutter(shift);
                    408:     unless ($resurl=~/^\/res/) { return 0; }
                    409:     $resurl=~s/\/$//;
                    410:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   411:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       412:     return 1;
1.42      matthew   413: }
                    414: 
1.74      www       415: sub studentbrowser_javascript {
1.111     www       416:    unless (
1.258     albertel  417:             (($env{'request.course.id'}) && 
1.302     albertel  418:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    419: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    420: 					  '/'.$env{'request.course.sec'})
                    421: 	      ))
1.258     albertel  422:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       423:           ) { return ''; }  
1.74      www       424:    return (<<'ENDSTDBRW');
1.776     bisitz    425: <script type="text/javascript" language="Javascript">
1.824     bisitz    426: // <![CDATA[
1.74      www       427:     var stdeditbrowser;
1.999     www       428:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       429:         var url = '/adm/pickstudent?';
                    430:         var filter;
1.558     albertel  431: 	if (!ignorefilter) {
                    432: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    433: 	}
1.74      www       434:         if (filter != null) {
                    435:            if (filter != '') {
                    436:                url += 'filter='+filter+'&';
                    437: 	   }
                    438:         }
                    439:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       440:                                     '&udomelement='+udom+
                    441:                                     '&clicker='+clicker;
1.111     www       442: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   443:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       444:         var title = 'Student_Browser';
1.74      www       445:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    446:         options += ',width=700,height=600';
                    447:         stdeditbrowser = open(url,title,options,'1');
                    448:         stdeditbrowser.focus();
                    449:     }
1.824     bisitz    450: // ]]>
1.74      www       451: </script>
                    452: ENDSTDBRW
                    453: }
1.42      matthew   454: 
1.1003    www       455: sub resourcebrowser_javascript {
                    456:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       457:    return (<<'ENDRESBRW');
1.1003    www       458: <script type="text/javascript" language="Javascript">
                    459: // <![CDATA[
                    460:     var reseditbrowser;
1.1004    www       461:     function openresbrowser(formname,reslink) {
1.1005    www       462:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       463:         var title = 'Resource_Browser';
                    464:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       465:         options += ',width=700,height=500';
1.1004    www       466:         reseditbrowser = open(url,title,options,'1');
                    467:         reseditbrowser.focus();
1.1003    www       468:     }
                    469: // ]]>
                    470: </script>
1.1004    www       471: ENDRESBRW
1.1003    www       472: }
                    473: 
1.74      www       474: sub selectstudent_link {
1.999     www       475:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    476:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    477:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    478:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  479:    if ($env{'request.course.id'}) {  
1.302     albertel  480:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    481: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    482: 					'/'.$env{'request.course.sec'})) {
1.111     www       483: 	   return '';
                    484:        }
1.999     www       485:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   486:        if ($courseadvonly)  {
                    487:            $callargs .= ",'',1,1";
                    488:        }
                    489:        return '<span class="LC_nobreak">'.
                    490:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    491:               &mt('Select User').'</a></span>';
1.74      www       492:    }
1.258     albertel  493:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       494:        $callargs .= ",'',1"; 
1.793     raeburn   495:        return '<span class="LC_nobreak">'.
                    496:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    497:               &mt('Select User').'</a></span>';
1.111     www       498:    }
                    499:    return '';
1.91      www       500: }
                    501: 
1.1004    www       502: sub selectresource_link {
                    503:    my ($form,$reslink,$arg)=@_;
                    504:    
                    505:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    506:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    507:    unless ($env{'request.course.id'}) { return $arg; }
                    508:    return '<span class="LC_nobreak">'.
                    509:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    510:               $arg.'</a></span>';
                    511: }
                    512: 
                    513: 
                    514: 
1.653     raeburn   515: sub authorbrowser_javascript {
                    516:     return <<"ENDAUTHORBRW";
1.776     bisitz    517: <script type="text/javascript" language="JavaScript">
1.824     bisitz    518: // <![CDATA[
1.653     raeburn   519: var stdeditbrowser;
                    520: 
                    521: function openauthorbrowser(formname,udom) {
                    522:     var url = '/adm/pickauthor?';
                    523:     url += 'form='+formname+'&roledom='+udom;
                    524:     var title = 'Author_Browser';
                    525:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    526:     options += ',width=700,height=600';
                    527:     stdeditbrowser = open(url,title,options,'1');
                    528:     stdeditbrowser.focus();
                    529: }
                    530: 
1.824     bisitz    531: // ]]>
1.653     raeburn   532: </script>
                    533: ENDAUTHORBRW
                    534: }
                    535: 
1.91      www       536: sub coursebrowser_javascript {
1.1116    raeburn   537:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
                    538:         $credits_element) = @_;
1.932     raeburn   539:     my $wintitle = 'Course_Browser';
1.931     raeburn   540:     if ($crstype eq 'Community') {
1.932     raeburn   541:         $wintitle = 'Community_Browser';
1.909     raeburn   542:     }
1.876     raeburn   543:     my $id_functions = &javascript_index_functions();
                    544:     my $output = '
1.776     bisitz    545: <script type="text/javascript" language="JavaScript">
1.824     bisitz    546: // <![CDATA[
1.468     raeburn   547:     var stdeditbrowser;'."\n";
1.876     raeburn   548: 
                    549:     $output .= <<"ENDSTDBRW";
1.909     raeburn   550:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       551:         var url = '/adm/pickcourse?';
1.895     raeburn   552:         var formid = getFormIdByName(formname);
1.876     raeburn   553:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  554:         if (domainfilter != null) {
                    555:            if (domainfilter != '') {
                    556:                url += 'domainfilter='+domainfilter+'&';
                    557: 	   }
                    558:         }
1.91      www       559:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  560: 	                            '&cdomelement='+udom+
                    561:                                     '&cnameelement='+desc;
1.468     raeburn   562:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   563:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   564:                 url += '&roleelement='+extra_element;
                    565:                 if (domainfilter == null || domainfilter == '') {
                    566:                     url += '&domainfilter='+extra_element;
                    567:                 }
1.234     raeburn   568:             }
1.468     raeburn   569:             else {
                    570:                 if (formname == 'portform') {
                    571:                     url += '&setroles='+extra_element;
1.800     raeburn   572:                 } else {
                    573:                     if (formname == 'rules') {
                    574:                         url += '&fixeddom='+extra_element; 
                    575:                     }
1.468     raeburn   576:                 }
                    577:             }     
1.230     raeburn   578:         }
1.909     raeburn   579:         if (type != null && type != '') {
                    580:             url += '&type='+type;
                    581:         }
                    582:         if (type_elem != null && type_elem != '') {
                    583:             url += '&typeelement='+type_elem;
                    584:         }
1.872     raeburn   585:         if (formname == 'ccrs') {
                    586:             var ownername = document.forms[formid].ccuname.value;
                    587:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
                    588:             url += '&cloner='+ownername+':'+ownerdom;
                    589:         }
1.293     raeburn   590:         if (multflag !=null && multflag != '') {
                    591:             url += '&multiple='+multflag;
                    592:         }
1.909     raeburn   593:         var title = '$wintitle';
1.91      www       594:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    595:         options += ',width=700,height=600';
                    596:         stdeditbrowser = open(url,title,options,'1');
                    597:         stdeditbrowser.focus();
                    598:     }
1.876     raeburn   599: $id_functions
                    600: ENDSTDBRW
1.1116    raeburn   601:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    602:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    603:                                       $credits_element);
1.876     raeburn   604:     }
                    605:     $output .= '
                    606: // ]]>
                    607: </script>';
                    608:     return $output;
                    609: }
                    610: 
                    611: sub javascript_index_functions {
                    612:     return <<"ENDJS";
                    613: 
                    614: function getFormIdByName(formname) {
                    615:     for (var i=0;i<document.forms.length;i++) {
                    616:         if (document.forms[i].name == formname) {
                    617:             return i;
                    618:         }
                    619:     }
                    620:     return -1;
                    621: }
                    622: 
                    623: function getIndexByName(formid,item) {
                    624:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    625:         if (document.forms[formid].elements[i].name == item) {
                    626:             return i;
                    627:         }
                    628:     }
                    629:     return -1;
                    630: }
1.468     raeburn   631: 
1.876     raeburn   632: function getDomainFromSelectbox(formname,udom) {
                    633:     var userdom;
                    634:     var formid = getFormIdByName(formname);
                    635:     if (formid > -1) {
                    636:         var domid = getIndexByName(formid,udom);
                    637:         if (domid > -1) {
                    638:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    639:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    640:             }
                    641:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    642:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   643:             }
                    644:         }
                    645:     }
1.876     raeburn   646:     return userdom;
                    647: }
                    648: 
                    649: ENDJS
1.468     raeburn   650: 
1.876     raeburn   651: }
                    652: 
1.1017    raeburn   653: sub javascript_array_indexof {
1.1018    raeburn   654:     return <<ENDJS;
1.1017    raeburn   655: <script type="text/javascript" language="JavaScript">
                    656: // <![CDATA[
                    657: 
                    658: if (!Array.prototype.indexOf) {
                    659:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    660:         "use strict";
                    661:         if (this === void 0 || this === null) {
                    662:             throw new TypeError();
                    663:         }
                    664:         var t = Object(this);
                    665:         var len = t.length >>> 0;
                    666:         if (len === 0) {
                    667:             return -1;
                    668:         }
                    669:         var n = 0;
                    670:         if (arguments.length > 0) {
                    671:             n = Number(arguments[1]);
1.1088    foxr      672:             if (n !== n) { // shortcut for verifying if it is NaN
1.1017    raeburn   673:                 n = 0;
                    674:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    675:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    676:             }
                    677:         }
                    678:         if (n >= len) {
                    679:             return -1;
                    680:         }
                    681:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    682:         for (; k < len; k++) {
                    683:             if (k in t && t[k] === searchElement) {
                    684:                 return k;
                    685:             }
                    686:         }
                    687:         return -1;
                    688:     }
                    689: }
                    690: 
                    691: // ]]>
                    692: </script>
                    693: 
                    694: ENDJS
                    695: 
                    696: }
                    697: 
1.876     raeburn   698: sub userbrowser_javascript {
                    699:     my $id_functions = &javascript_index_functions();
                    700:     return <<"ENDUSERBRW";
                    701: 
1.888     raeburn   702: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   703:     var url = '/adm/pickuser?';
                    704:     var userdom = getDomainFromSelectbox(formname,udom);
                    705:     if (userdom != null) {
                    706:        if (userdom != '') {
                    707:            url += 'srchdom='+userdom+'&';
                    708:        }
                    709:     }
                    710:     url += 'form=' + formname + '&unameelement='+uname+
                    711:                                 '&udomelement='+udom+
                    712:                                 '&ulastelement='+ulast+
                    713:                                 '&ufirstelement='+ufirst+
                    714:                                 '&uemailelement='+uemail+
1.881     raeburn   715:                                 '&hideudomelement='+hideudom+
                    716:                                 '&coursedom='+crsdom;
1.888     raeburn   717:     if ((caller != null) && (caller != undefined)) {
                    718:         url += '&caller='+caller;
                    719:     }
1.876     raeburn   720:     var title = 'User_Browser';
                    721:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    722:     options += ',width=700,height=600';
                    723:     var stdeditbrowser = open(url,title,options,'1');
                    724:     stdeditbrowser.focus();
                    725: }
                    726: 
1.888     raeburn   727: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   728:     var formid = getFormIdByName(formname);
                    729:     if (formid > -1) {
1.888     raeburn   730:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   731:         var domid = getIndexByName(formid,udom);
                    732:         var hidedomid = getIndexByName(formid,origdom);
                    733:         if (hidedomid > -1) {
                    734:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   735:             var unameval = document.forms[formid].elements[unameid].value;
                    736:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    737:                 if (domid > -1) {
                    738:                     var slct = document.forms[formid].elements[domid];
                    739:                     if (slct.type == 'select-one') {
                    740:                         var i;
                    741:                         for (i=0;i<slct.length;i++) {
                    742:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    743:                         }
                    744:                     }
                    745:                     if (slct.type == 'hidden') {
                    746:                         slct.value = fixeddom;
1.876     raeburn   747:                     }
                    748:                 }
1.468     raeburn   749:             }
                    750:         }
                    751:     }
1.876     raeburn   752:     return;
                    753: }
                    754: 
                    755: $id_functions
                    756: ENDUSERBRW
1.468     raeburn   757: }
                    758: 
                    759: sub setsec_javascript {
1.1116    raeburn   760:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   761:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    762:         $communityrolestr);
                    763:     if ($role_element ne '') {
                    764:         my @allroles = ('st','ta','ep','in','ad');
                    765:         foreach my $crstype ('Course','Community') {
                    766:             if ($crstype eq 'Community') {
                    767:                 foreach my $role (@allroles) {
                    768:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    769:                 }
                    770:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    771:             } else {
                    772:                 foreach my $role (@allroles) {
                    773:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    774:                 }
                    775:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    776:             }
                    777:         }
                    778:         $rolestr = '"'.join('","',@allroles).'"';
                    779:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    780:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    781:     }
1.468     raeburn   782:     my $setsections = qq|
                    783: function setSect(sectionlist) {
1.629     raeburn   784:     var sectionsArray = new Array();
                    785:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    786:         sectionsArray = sectionlist.split(",");
                    787:     }
1.468     raeburn   788:     var numSections = sectionsArray.length;
                    789:     document.$formname.$sec_element.length = 0;
                    790:     if (numSections == 0) {
                    791:         document.$formname.$sec_element.multiple=false;
                    792:         document.$formname.$sec_element.size=1;
                    793:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    794:     } else {
                    795:         if (numSections == 1) {
                    796:             document.$formname.$sec_element.multiple=false;
                    797:             document.$formname.$sec_element.size=1;
                    798:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    799:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    800:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    801:         } else {
                    802:             for (var i=0; i<numSections; i++) {
                    803:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    804:             }
                    805:             document.$formname.$sec_element.multiple=true
                    806:             if (numSections < 3) {
                    807:                 document.$formname.$sec_element.size=numSections;
                    808:             } else {
                    809:                 document.$formname.$sec_element.size=3;
                    810:             }
                    811:             document.$formname.$sec_element.options[0].selected = false
                    812:         }
                    813:     }
1.91      www       814: }
1.905     raeburn   815: 
                    816: function setRole(crstype) {
1.468     raeburn   817: |;
1.905     raeburn   818:     if ($role_element eq '') {
                    819:         $setsections .= '    return;
                    820: }
                    821: ';
                    822:     } else {
                    823:         $setsections .= qq|
                    824:     var elementLength = document.$formname.$role_element.length;
                    825:     var allroles = Array($rolestr);
                    826:     var courserolenames = Array($courserolestr);
                    827:     var communityrolenames = Array($communityrolestr);
                    828:     if (elementLength != undefined) {
                    829:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    830:             if (crstype == 'Course') {
                    831:                 return;
                    832:             } else {
                    833:                 allroles[5] = 'co';
                    834:                 for (var i=0; i<6; i++) {
                    835:                     document.$formname.$role_element.options[i].value = allroles[i];
                    836:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    837:                 }
                    838:             }
                    839:         } else {
                    840:             if (crstype == 'Community') {
                    841:                 return;
                    842:             } else {
                    843:                 allroles[5] = 'cc';
                    844:                 for (var i=0; i<6; i++) {
                    845:                     document.$formname.$role_element.options[i].value = allroles[i];
                    846:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    847:                 }
                    848:             }
                    849:         }
                    850:     }
                    851:     return;
                    852: }
                    853: |;
                    854:     }
1.1116    raeburn   855:     if ($credits_element) {
                    856:         $setsections .= qq|
                    857: function setCredits(defaultcredits) {
                    858:     document.$formname.$credits_element.value = defaultcredits;
                    859:     return;
                    860: }
                    861: |;
                    862:     }
1.468     raeburn   863:     return $setsections;
                    864: }
                    865: 
1.91      www       866: sub selectcourse_link {
1.909     raeburn   867:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    868:        $typeelement) = @_;
                    869:    my $type = $selecttype;
1.871     raeburn   870:    my $linktext = &mt('Select Course');
                    871:    if ($selecttype eq 'Community') {
1.909     raeburn   872:        $linktext = &mt('Select Community');
1.906     raeburn   873:    } elsif ($selecttype eq 'Course/Community') {
                    874:        $linktext = &mt('Select Course/Community');
1.909     raeburn   875:        $type = '';
1.1019    raeburn   876:    } elsif ($selecttype eq 'Select') {
                    877:        $linktext = &mt('Select');
                    878:        $type = '';
1.871     raeburn   879:    }
1.787     bisitz    880:    return '<span class="LC_nobreak">'
                    881:          ."<a href='"
                    882:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    883:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   884:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   885:          ."'>".$linktext.'</a>'
1.787     bisitz    886:          .'</span>';
1.74      www       887: }
1.42      matthew   888: 
1.653     raeburn   889: sub selectauthor_link {
                    890:    my ($form,$udom)=@_;
                    891:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    892:           &mt('Select Author').'</a>';
                    893: }
                    894: 
1.876     raeburn   895: sub selectuser_link {
1.881     raeburn   896:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   897:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   898:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   899:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   900:            ');">'.$linktext.'</a>';
1.876     raeburn   901: }
                    902: 
1.273     raeburn   903: sub check_uncheck_jscript {
                    904:     my $jscript = <<"ENDSCRT";
                    905: function checkAll(field) {
                    906:     if (field.length > 0) {
                    907:         for (i = 0; i < field.length; i++) {
1.1093    raeburn   908:             if (!field[i].disabled) { 
                    909:                 field[i].checked = true;
                    910:             }
1.273     raeburn   911:         }
                    912:     } else {
1.1093    raeburn   913:         if (!field.disabled) { 
                    914:             field.checked = true;
                    915:         }
1.273     raeburn   916:     }
                    917: }
                    918:  
                    919: function uncheckAll(field) {
                    920:     if (field.length > 0) {
                    921:         for (i = 0; i < field.length; i++) {
                    922:             field[i].checked = false ;
1.543     albertel  923:         }
                    924:     } else {
1.273     raeburn   925:         field.checked = false ;
                    926:     }
                    927: }
                    928: ENDSCRT
                    929:     return $jscript;
                    930: }
                    931: 
1.656     www       932: sub select_timezone {
1.659     raeburn   933:    my ($name,$selected,$onchange,$includeempty)=@_;
                    934:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    935:    if ($includeempty) {
                    936:        $output .= '<option value=""';
                    937:        if (($selected eq '') || ($selected eq 'local')) {
                    938:            $output .= ' selected="selected" ';
                    939:        }
                    940:        $output .= '> </option>';
                    941:    }
1.657     raeburn   942:    my @timezones = DateTime::TimeZone->all_names;
                    943:    foreach my $tzone (@timezones) {
                    944:        $output.= '<option value="'.$tzone.'"';
                    945:        if ($tzone eq $selected) {
                    946:            $output.=' selected="selected"';
                    947:        }
                    948:        $output.=">$tzone</option>\n";
1.656     www       949:    }
                    950:    $output.="</select>";
                    951:    return $output;
                    952: }
1.273     raeburn   953: 
1.687     raeburn   954: sub select_datelocale {
                    955:     my ($name,$selected,$onchange,$includeempty)=@_;
                    956:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    957:     if ($includeempty) {
                    958:         $output .= '<option value=""';
                    959:         if ($selected eq '') {
                    960:             $output .= ' selected="selected" ';
                    961:         }
                    962:         $output .= '> </option>';
                    963:     }
                    964:     my (@possibles,%locale_names);
                    965:     my @locales = DateTime::Locale::Catalog::Locales;
                    966:     foreach my $locale (@locales) {
                    967:         if (ref($locale) eq 'HASH') {
                    968:             my $id = $locale->{'id'};
                    969:             if ($id ne '') {
                    970:                 my $en_terr = $locale->{'en_territory'};
                    971:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   972:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   973:                 if (grep(/^en$/,@languages) || !@languages) {
                    974:                     if ($en_terr ne '') {
                    975:                         $locale_names{$id} = '('.$en_terr.')';
                    976:                     } elsif ($native_terr ne '') {
                    977:                         $locale_names{$id} = $native_terr;
                    978:                     }
                    979:                 } else {
                    980:                     if ($native_terr ne '') {
                    981:                         $locale_names{$id} = $native_terr.' ';
                    982:                     } elsif ($en_terr ne '') {
                    983:                         $locale_names{$id} = '('.$en_terr.')';
                    984:                     }
                    985:                 }
                    986:                 push (@possibles,$id);
                    987:             }
                    988:         }
                    989:     }
                    990:     foreach my $item (sort(@possibles)) {
                    991:         $output.= '<option value="'.$item.'"';
                    992:         if ($item eq $selected) {
                    993:             $output.=' selected="selected"';
                    994:         }
                    995:         $output.=">$item";
                    996:         if ($locale_names{$item} ne '') {
                    997:             $output.="  $locale_names{$item}</option>\n";
                    998:         }
                    999:         $output.="</option>\n";
                   1000:     }
                   1001:     $output.="</select>";
                   1002:     return $output;
                   1003: }
                   1004: 
1.792     raeburn  1005: sub select_language {
                   1006:     my ($name,$selected,$includeempty) = @_;
                   1007:     my %langchoices;
                   1008:     if ($includeempty) {
1.1117    raeburn  1009:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1010:     }
                   1011:     foreach my $id (&languageids()) {
                   1012:         my $code = &supportedlanguagecode($id);
                   1013:         if ($code) {
                   1014:             $langchoices{$code} = &plainlanguagedescription($id);
                   1015:         }
                   1016:     }
1.1117    raeburn  1017:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1018:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1019: }
                   1020: 
1.42      matthew  1021: =pod
1.36      matthew  1022: 
1.1088    foxr     1023: 
                   1024: =item * &list_languages()
                   1025: 
                   1026: Returns an array reference that is suitable for use in language prompters.
                   1027: Each array element is itself a two element array.  The first element
                   1028: is the language code.  The second element a descsriptiuon of the 
                   1029: language itself.  This is suitable for use in e.g.
                   1030: &Apache::edit::select_arg (once dereferenced that is).
                   1031: 
                   1032: =cut 
                   1033: 
                   1034: sub list_languages {
                   1035:     my @lang_choices;
                   1036: 
                   1037:     foreach my $id (&languageids()) {
                   1038: 	my $code = &supportedlanguagecode($id);
                   1039: 	if ($code) {
                   1040: 	    my $selector    = $supported_codes{$id};
                   1041: 	    my $description = &plainlanguagedescription($id);
                   1042: 	    push (@lang_choices, [$selector, $description]);
                   1043: 	}
                   1044:     }
                   1045:     return \@lang_choices;
                   1046: }
                   1047: 
                   1048: =pod
                   1049: 
1.648     raeburn  1050: =item * &linked_select_forms(...)
1.36      matthew  1051: 
                   1052: linked_select_forms returns a string containing a <script></script> block
                   1053: and html for two <select> menus.  The select menus will be linked in that
                   1054: changing the value of the first menu will result in new values being placed
                   1055: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1056: order unless a defined order is provided.
1.36      matthew  1057: 
                   1058: linked_select_forms takes the following ordered inputs:
                   1059: 
                   1060: =over 4
                   1061: 
1.112     bowersj2 1062: =item * $formname, the name of the <form> tag
1.36      matthew  1063: 
1.112     bowersj2 1064: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1065: 
1.112     bowersj2 1066: =item * $firstdefault, the default value for the first menu
1.36      matthew  1067: 
1.112     bowersj2 1068: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1069: 
1.112     bowersj2 1070: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1071: 
1.112     bowersj2 1072: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1073: 
1.609     raeburn  1074: =item * $menuorder, the order of values in the first menu
                   1075: 
1.1115    raeburn  1076: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1077:         event for the first <select> tag
                   1078: 
                   1079: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1080:         event for the second <select> tag
                   1081: 
1.41      ng       1082: =back 
                   1083: 
1.36      matthew  1084: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1085: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1086: values for the first select menu.  The text that coincides with the 
1.41      ng       1087: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1088: and text for the second menu are given in the hash pointed to by 
                   1089: $menu{$choice1}->{'select2'}.  
                   1090: 
1.112     bowersj2 1091:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1092:                        default => "B3",
                   1093:                        select2 => { 
                   1094:                            B1 => "Choice B1",
                   1095:                            B2 => "Choice B2",
                   1096:                            B3 => "Choice B3",
                   1097:                            B4 => "Choice B4"
1.609     raeburn  1098:                            },
                   1099:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1100:                    },
                   1101:                A2 => { text =>"Choice A2" ,
                   1102:                        default => "C2",
                   1103:                        select2 => { 
                   1104:                            C1 => "Choice C1",
                   1105:                            C2 => "Choice C2",
                   1106:                            C3 => "Choice C3"
1.609     raeburn  1107:                            },
                   1108:                        order => ['C2','C1','C3'],
1.112     bowersj2 1109:                    },
                   1110:                A3 => { text =>"Choice A3" ,
                   1111:                        default => "D6",
                   1112:                        select2 => { 
                   1113:                            D1 => "Choice D1",
                   1114:                            D2 => "Choice D2",
                   1115:                            D3 => "Choice D3",
                   1116:                            D4 => "Choice D4",
                   1117:                            D5 => "Choice D5",
                   1118:                            D6 => "Choice D6",
                   1119:                            D7 => "Choice D7"
1.609     raeburn  1120:                            },
                   1121:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1122:                    }
                   1123:                );
1.36      matthew  1124: 
                   1125: =cut
                   1126: 
                   1127: sub linked_select_forms {
                   1128:     my ($formname,
                   1129:         $middletext,
                   1130:         $firstdefault,
                   1131:         $firstselectname,
                   1132:         $secondselectname, 
1.609     raeburn  1133:         $hashref,
                   1134:         $menuorder,
1.1115    raeburn  1135:         $onchangefirst,
                   1136:         $onchangesecond
1.36      matthew  1137:         ) = @_;
                   1138:     my $second = "document.$formname.$secondselectname";
                   1139:     my $first = "document.$formname.$firstselectname";
                   1140:     # output the javascript to do the changing
                   1141:     my $result = '';
1.776     bisitz   1142:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1143:     $result.="// <![CDATA[\n";
1.36      matthew  1144:     $result.="var select2data = new Object();\n";
                   1145:     $" = '","';
                   1146:     my $debug = '';
                   1147:     foreach my $s1 (sort(keys(%$hashref))) {
                   1148:         $result.="select2data.d_$s1 = new Object();\n";        
                   1149:         $result.="select2data.d_$s1.def = new String('".
                   1150:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1151:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1152:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1153:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1154:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1155:         }
1.36      matthew  1156:         $result.="\"@s2values\");\n";
                   1157:         $result.="select2data.d_$s1.texts = new Array(";        
                   1158:         my @s2texts;
                   1159:         foreach my $value (@s2values) {
                   1160:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1161:         }
                   1162:         $result.="\"@s2texts\");\n";
                   1163:     }
                   1164:     $"=' ';
                   1165:     $result.= <<"END";
                   1166: 
                   1167: function select1_changed() {
                   1168:     // Determine new choice
                   1169:     var newvalue = "d_" + $first.value;
                   1170:     // update select2
                   1171:     var values     = select2data[newvalue].values;
                   1172:     var texts      = select2data[newvalue].texts;
                   1173:     var select2def = select2data[newvalue].def;
                   1174:     var i;
                   1175:     // out with the old
                   1176:     for (i = 0; i < $second.options.length; i++) {
                   1177:         $second.options[i] = null;
                   1178:     }
                   1179:     // in with the nuclear
                   1180:     for (i=0;i<values.length; i++) {
                   1181:         $second.options[i] = new Option(values[i]);
1.143     matthew  1182:         $second.options[i].value = values[i];
1.36      matthew  1183:         $second.options[i].text = texts[i];
                   1184:         if (values[i] == select2def) {
                   1185:             $second.options[i].selected = true;
                   1186:         }
                   1187:     }
                   1188: }
1.824     bisitz   1189: // ]]>
1.36      matthew  1190: </script>
                   1191: END
                   1192:     # output the initial values for the selection lists
1.1115    raeburn  1193:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1194:     my @order = sort(keys(%{$hashref}));
                   1195:     if (ref($menuorder) eq 'ARRAY') {
                   1196:         @order = @{$menuorder};
                   1197:     }
                   1198:     foreach my $value (@order) {
1.36      matthew  1199:         $result.="    <option value=\"$value\" ";
1.253     albertel 1200:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1201:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1202:     }
                   1203:     $result .= "</select>\n";
                   1204:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1205:     $result .= $middletext;
1.1115    raeburn  1206:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1207:     if ($onchangesecond) {
                   1208:         $result .= ' onchange="'.$onchangesecond.'"';
                   1209:     }
                   1210:     $result .= ">\n";
1.36      matthew  1211:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1212:     
                   1213:     my @secondorder = sort(keys(%select2));
                   1214:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1215:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1216:     }
                   1217:     foreach my $value (@secondorder) {
1.36      matthew  1218:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1219:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1220:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1221:     }
                   1222:     $result .= "</select>\n";
                   1223:     #    return $debug;
                   1224:     return $result;
                   1225: }   #  end of sub linked_select_forms {
                   1226: 
1.45      matthew  1227: =pod
1.44      bowersj2 1228: 
1.973     raeburn  1229: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1230: 
1.112     bowersj2 1231: Returns a string corresponding to an HTML link to the given help
                   1232: $topic, where $topic corresponds to the name of a .tex file in
                   1233: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1234: spaces. 
                   1235: 
                   1236: $text will optionally be linked to the same topic, allowing you to
                   1237: link text in addition to the graphic. If you do not want to link
                   1238: text, but wish to specify one of the later parameters, pass an
                   1239: empty string. 
                   1240: 
                   1241: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1242: the link will not open a new window. If false, the link will open
                   1243: a new window using Javascript. (Default is false.) 
                   1244: 
                   1245: $width and $height are optional numerical parameters that will
                   1246: override the width and height of the popped up window, which may
1.973     raeburn  1247: be useful for certain help topics with big pictures included.
                   1248: 
                   1249: $imgid is the id of the img tag used for the help icon. This may be
                   1250: used in a javascript call to switch the image src.  See 
                   1251: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1252: 
                   1253: =cut
                   1254: 
                   1255: sub help_open_topic {
1.973     raeburn  1256:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1257:     $text = "" if (not defined $text);
1.44      bowersj2 1258:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1259:     $width = 500 if (not defined $width);
1.44      bowersj2 1260:     $height = 400 if (not defined $height);
                   1261:     my $filename = $topic;
                   1262:     $filename =~ s/ /_/g;
                   1263: 
1.48      bowersj2 1264:     my $template = "";
                   1265:     my $link;
1.572     banghart 1266:     
1.159     www      1267:     $topic=~s/\W/\_/g;
1.44      bowersj2 1268: 
1.572     banghart 1269:     if (!$stayOnPage) {
1.1033    www      1270: 	$link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
1.1037    www      1271:     } elsif ($stayOnPage eq 'popup') {
                   1272:         $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
1.572     banghart 1273:     } else {
1.48      bowersj2 1274: 	$link = "/adm/help/${filename}.hlp";
                   1275:     }
                   1276: 
                   1277:     # Add the text
1.755     neumanie 1278:     if ($text ne "") {	
1.763     bisitz   1279: 	$template.='<span class="LC_help_open_topic">'
                   1280:                   .'<a target="_top" href="'.$link.'">'
                   1281:                   .$text.'</a>';
1.48      bowersj2 1282:     }
                   1283: 
1.763     bisitz   1284:     # (Always) Add the graphic
1.179     matthew  1285:     my $title = &mt('Online Help');
1.667     raeburn  1286:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1287:     if ($imgid ne '') {
                   1288:         $imgid = ' id="'.$imgid.'"';
                   1289:     }
1.763     bisitz   1290:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1291:               .'<img src="'.$helpicon.'" border="0"'
                   1292:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1293:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1294:               .' /></a>';
                   1295:     if ($text ne "") {	
                   1296:         $template.='</span>';
                   1297:     }
1.44      bowersj2 1298:     return $template;
                   1299: 
1.106     bowersj2 1300: }
                   1301: 
                   1302: # This is a quicky function for Latex cheatsheet editing, since it 
                   1303: # appears in at least four places
                   1304: sub helpLatexCheatsheet {
1.1037    www      1305:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1306:     my $out;
1.106     bowersj2 1307:     my $addOther = '';
1.732     raeburn  1308:     if ($topic) {
1.1037    www      1309: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1310:     }
                   1311:     $out = '<span>' # Start cheatsheet
                   1312: 	  .$addOther
                   1313:           .'<span>'
1.1037    www      1314: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1315: 	  .'</span> <span>'
1.1037    www      1316: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1317: 	  .'</span>';
1.732     raeburn  1318:     unless ($not_author) {
1.1186    kruse    1319:         $out .= '<span>'
                   1320:                .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
                   1321:                .'</span> <span>'
                   1322:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('How to create problems in different languages'),$stayOnPage,undef,600)
1.763     bisitz   1323: 	       .'</span>';
1.732     raeburn  1324:     }
1.763     bisitz   1325:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1326:     return $out;
1.172     www      1327: }
                   1328: 
1.430     albertel 1329: sub general_help {
                   1330:     my $helptopic='Student_Intro';
                   1331:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1332: 	$helptopic='Authoring_Intro';
1.907     raeburn  1333:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1334: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1335:     } elsif ($env{'request.role'}=~/^dc/) {
                   1336:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1337:     }
                   1338:     return $helptopic;
                   1339: }
                   1340: 
                   1341: sub update_help_link {
                   1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1343:     my $origurl = $ENV{'REQUEST_URI'};
                   1344:     $origurl=~s|^/~|/priv/|;
                   1345:     my $timestamp = time;
                   1346:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1347:         $$datum = &escape($$datum);
                   1348:     }
                   1349: 
                   1350:     my $banner_link = "/adm/helpmenu?page=banner&amp;topic=$topic&amp;component_help=$component_help&amp;faq=$faq&amp;bug=$bug&amp;origurl=$origurl&amp;stamp=$timestamp&amp;stayonpage=$stayOnPage";
                   1351:     my $output .= <<"ENDOUTPUT";
                   1352: <script type="text/javascript">
1.824     bisitz   1353: // <![CDATA[
1.430     albertel 1354: banner_link = '$banner_link';
1.824     bisitz   1355: // ]]>
1.430     albertel 1356: </script>
                   1357: ENDOUTPUT
                   1358:     return $output;
                   1359: }
                   1360: 
                   1361: # now just updates the help link and generates a blue icon
1.193     raeburn  1362: sub help_open_menu {
1.430     albertel 1363:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1364: 	= @_;    
1.949     droeschl 1365:     $stayOnPage = 1;
1.430     albertel 1366:     my $output;
                   1367:     if ($component_help) {
                   1368: 	if (!$text) {
                   1369: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1370: 				       $width,$height);
                   1371: 	} else {
                   1372: 	    my $help_text;
                   1373: 	    $help_text=&unescape($topic);
                   1374: 	    $output='<table><tr><td>'.
                   1375: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1376: 				 $width,$height).'</td></tr></table>';
                   1377: 	}
                   1378:     }
                   1379:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1380:     return $output.$banner_link;
                   1381: }
                   1382: 
                   1383: sub top_nav_help {
                   1384:     my ($text) = @_;
1.436     albertel 1385:     $text = &mt($text);
1.949     droeschl 1386:     my $stay_on_page = 1;
                   1387: 
1.1168    raeburn  1388:     my ($link,$banner_link);
                   1389:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1390:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1391: 	                         : "javascript:helpMenu('open')";
                   1392:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1393:     }
1.201     raeburn  1394:     my $title = &mt('Get help');
1.1168    raeburn  1395:     if ($link) {
                   1396:         return <<"END";
1.436     albertel 1397: $banner_link
1.1159    raeburn  1398: <a href="$link" title="$title">$text</a>
1.436     albertel 1399: END
1.1168    raeburn  1400:     } else {
                   1401:         return '&nbsp;'.$text.'&nbsp;';
                   1402:     }
1.436     albertel 1403: }
                   1404: 
                   1405: sub help_menu_js {
1.1154    raeburn  1406:     my ($httphost) = @_;
1.949     droeschl 1407:     my $stayOnPage = 1;
1.436     albertel 1408:     my $width = 620;
                   1409:     my $height = 600;
1.430     albertel 1410:     my $helptopic=&general_help();
1.1154    raeburn  1411:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1412:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1413:     my $start_page =
                   1414:         &Apache::loncommon::start_page('Help Menu', undef,
                   1415: 				       {'frameset'    => 1,
                   1416: 					'js_ready'    => 1,
1.1154    raeburn  1417:                                         'use_absolute' => $httphost,
1.331     albertel 1418: 					'add_entries' => {
1.1168    raeburn  1419: 					    'border' => '0', 
1.579     raeburn  1420: 					    'rows'   => "110,*",},});
1.331     albertel 1421:     my $end_page =
                   1422:         &Apache::loncommon::end_page({'frameset' => 1,
                   1423: 				      'js_ready' => 1,});
                   1424: 
1.436     albertel 1425:     my $template .= <<"ENDTEMPLATE";
                   1426: <script type="text/javascript">
1.877     bisitz   1427: // <![CDATA[
1.253     albertel 1428: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1429: var banner_link = '';
1.243     raeburn  1430: function helpMenu(target) {
                   1431:     var caller = this;
                   1432:     if (target == 'open') {
                   1433:         var newWindow = null;
                   1434:         try {
1.262     albertel 1435:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1436:         }
                   1437:         catch(error) {
                   1438:             writeHelp(caller);
                   1439:             return;
                   1440:         }
                   1441:         if (newWindow) {
                   1442:             caller = newWindow;
                   1443:         }
1.193     raeburn  1444:     }
1.243     raeburn  1445:     writeHelp(caller);
                   1446:     return;
                   1447: }
                   1448: function writeHelp(caller) {
1.1168    raeburn  1449:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1450:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1451:     caller.document.close();
                   1452:     caller.focus();
1.193     raeburn  1453: }
1.877     bisitz   1454: // END LON-CAPA Internal -->
1.253     albertel 1455: // ]]>
1.436     albertel 1456: </script>
1.193     raeburn  1457: ENDTEMPLATE
                   1458:     return $template;
                   1459: }
                   1460: 
1.172     www      1461: sub help_open_bug {
                   1462:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1463:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1464:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1465:     $text = "" if (not defined $text);
                   1466: 	$stayOnPage=1;
1.184     albertel 1467:     $width = 600 if (not defined $width);
                   1468:     $height = 600 if (not defined $height);
1.172     www      1469: 
                   1470:     $topic=~s/\W+/\+/g;
                   1471:     my $link='';
                   1472:     my $template='';
1.379     albertel 1473:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1474: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1475:     if (!$stayOnPage)
                   1476:     {
                   1477: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1478:     }
                   1479:     else
                   1480:     {
                   1481: 	$link = $url;
                   1482:     }
                   1483:     # Add the text
                   1484:     if ($text ne "")
                   1485:     {
                   1486: 	$template .= 
                   1487:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1488:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1489:     }
                   1490: 
                   1491:     # Add the graphic
1.179     matthew  1492:     my $title = &mt('Report a Bug');
1.215     albertel 1493:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1494:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1495:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1496: ENDTEMPLATE
                   1497:     if ($text ne '') { $template.='</td></tr></table>' };
                   1498:     return $template;
                   1499: 
                   1500: }
                   1501: 
                   1502: sub help_open_faq {
                   1503:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1504:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1505:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1506:     $text = "" if (not defined $text);
                   1507: 	$stayOnPage=1;
                   1508:     $width = 350 if (not defined $width);
                   1509:     $height = 400 if (not defined $height);
                   1510: 
                   1511:     $topic=~s/\W+/\+/g;
                   1512:     my $link='';
                   1513:     my $template='';
                   1514:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1515:     if (!$stayOnPage)
                   1516:     {
                   1517: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1518:     }
                   1519:     else
                   1520:     {
                   1521: 	$link = $url;
                   1522:     }
                   1523: 
                   1524:     # Add the text
                   1525:     if ($text ne "")
                   1526:     {
                   1527: 	$template .= 
1.173     www      1528:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1529:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1530:     }
                   1531: 
                   1532:     # Add the graphic
1.179     matthew  1533:     my $title = &mt('View the FAQ');
1.215     albertel 1534:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1535:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1536:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1537: ENDTEMPLATE
                   1538:     if ($text ne '') { $template.='</td></tr></table>' };
                   1539:     return $template;
                   1540: 
1.44      bowersj2 1541: }
1.37      matthew  1542: 
1.180     matthew  1543: ###############################################################
                   1544: ###############################################################
                   1545: 
1.45      matthew  1546: =pod
                   1547: 
1.648     raeburn  1548: =item * &change_content_javascript():
1.256     matthew  1549: 
                   1550: This and the next function allow you to create small sections of an
                   1551: otherwise static HTML page that you can update on the fly with
                   1552: Javascript, even in Netscape 4.
                   1553: 
                   1554: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1555: must be written to the HTML page once. It will prove the Javascript
                   1556: function "change(name, content)". Calling the change function with the
                   1557: name of the section 
                   1558: you want to update, matching the name passed to C<changable_area>, and
                   1559: the new content you want to put in there, will put the content into
                   1560: that area.
                   1561: 
                   1562: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1563: to contain room for the original contents. You need to "make space"
                   1564: for whatever changes you wish to make, and be B<sure> to check your
                   1565: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1566: it's adequate for updating a one-line status display, but little more.
                   1567: This script will set the space to 100% width, so you only need to
                   1568: worry about height in Netscape 4.
                   1569: 
                   1570: Modern browsers are much less limiting, and if you can commit to the
                   1571: user not using Netscape 4, this feature may be used freely with
                   1572: pretty much any HTML.
                   1573: 
                   1574: =cut
                   1575: 
                   1576: sub change_content_javascript {
                   1577:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1578:     if ($env{'browser.type'} eq 'netscape' &&
                   1579: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1580: 	return (<<NETSCAPE4);
                   1581: 	function change(name, content) {
                   1582: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1583: 	    doc.open();
                   1584: 	    doc.write(content);
                   1585: 	    doc.close();
                   1586: 	}
                   1587: NETSCAPE4
                   1588:     } else {
                   1589: 	# Otherwise, we need to use semi-standards-compliant code
                   1590: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1591: 	# is really scary, and every useful browser supports it
                   1592: 	return (<<DOMBASED);
                   1593: 	function change(name, content) {
                   1594: 	    element = document.getElementById(name);
                   1595: 	    element.innerHTML = content;
                   1596: 	}
                   1597: DOMBASED
                   1598:     }
                   1599: }
                   1600: 
                   1601: =pod
                   1602: 
1.648     raeburn  1603: =item * &changable_area($name,$origContent):
1.256     matthew  1604: 
                   1605: This provides a "changable area" that can be modified on the fly via
                   1606: the Javascript code provided in C<change_content_javascript>. $name is
                   1607: the name you will use to reference the area later; do not repeat the
                   1608: same name on a given HTML page more then once. $origContent is what
                   1609: the area will originally contain, which can be left blank.
                   1610: 
                   1611: =cut
                   1612: 
                   1613: sub changable_area {
                   1614:     my ($name, $origContent) = @_;
                   1615: 
1.258     albertel 1616:     if ($env{'browser.type'} eq 'netscape' &&
                   1617: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1618: 	# If this is netscape 4, we need to use the Layer tag
                   1619: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1620:     } else {
                   1621: 	return "<span id='$name'>$origContent</span>";
                   1622:     }
                   1623: }
                   1624: 
                   1625: =pod
                   1626: 
1.648     raeburn  1627: =item * &viewport_geometry_js 
1.590     raeburn  1628: 
                   1629: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1630: 
                   1631: =cut
                   1632: 
                   1633: 
                   1634: sub viewport_geometry_js { 
                   1635:     return <<"GEOMETRY";
                   1636: var Geometry = {};
                   1637: function init_geometry() {
                   1638:     if (Geometry.init) { return };
                   1639:     Geometry.init=1;
                   1640:     if (window.innerHeight) {
                   1641:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1642:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1643:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1644:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1645:     }
                   1646:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1647:         Geometry.getViewportHeight =
                   1648:             function() { return document.documentElement.clientHeight; };
                   1649:         Geometry.getViewportWidth =
                   1650:             function() { return document.documentElement.clientWidth; };
                   1651: 
                   1652:         Geometry.getHorizontalScroll =
                   1653:             function() { return document.documentElement.scrollLeft; };
                   1654:         Geometry.getVerticalScroll =
                   1655:             function() { return document.documentElement.scrollTop; };
                   1656:     }
                   1657:     else if (document.body.clientHeight) {
                   1658:         Geometry.getViewportHeight =
                   1659:             function() { return document.body.clientHeight; };
                   1660:         Geometry.getViewportWidth =
                   1661:             function() { return document.body.clientWidth; };
                   1662:         Geometry.getHorizontalScroll =
                   1663:             function() { return document.body.scrollLeft; };
                   1664:         Geometry.getVerticalScroll =
                   1665:             function() { return document.body.scrollTop; };
                   1666:     }
                   1667: }
                   1668: 
                   1669: GEOMETRY
                   1670: }
                   1671: 
                   1672: =pod
                   1673: 
1.648     raeburn  1674: =item * &viewport_size_js()
1.590     raeburn  1675: 
                   1676: Provides a javascript function to set values of two form elements - width and height (elements are passed in as arguments to the javascript function) to the dimensions of the user's browser window. 
                   1677: 
                   1678: =cut
                   1679: 
                   1680: sub viewport_size_js {
                   1681:     my $geometry = &viewport_geometry_js();
                   1682:     return <<"DIMS";
                   1683: 
                   1684: $geometry
                   1685: 
                   1686: function getViewportDims(width,height) {
                   1687:     init_geometry();
                   1688:     width.value = Geometry.getViewportWidth();
                   1689:     height.value = Geometry.getViewportHeight();
                   1690:     return;
                   1691: }
                   1692: 
                   1693: DIMS
                   1694: }
                   1695: 
                   1696: =pod
                   1697: 
1.648     raeburn  1698: =item * &resize_textarea_js()
1.565     albertel 1699: 
                   1700: emits the needed javascript to resize a textarea to be as big as possible
                   1701: 
                   1702: creates a function resize_textrea that takes two IDs first should be
                   1703: the id of the element to resize, second should be the id of a div that
                   1704: surrounds everything that comes after the textarea, this routine needs
                   1705: to be attached to the <body> for the onload and onresize events.
                   1706: 
1.648     raeburn  1707: =back
1.565     albertel 1708: 
                   1709: =cut
                   1710: 
                   1711: sub resize_textarea_js {
1.590     raeburn  1712:     my $geometry = &viewport_geometry_js();
1.565     albertel 1713:     return <<"RESIZE";
                   1714:     <script type="text/javascript">
1.824     bisitz   1715: // <![CDATA[
1.590     raeburn  1716: $geometry
1.565     albertel 1717: 
1.588     albertel 1718: function getX(element) {
                   1719:     var x = 0;
                   1720:     while (element) {
                   1721: 	x += element.offsetLeft;
                   1722: 	element = element.offsetParent;
                   1723:     }
                   1724:     return x;
                   1725: }
                   1726: function getY(element) {
                   1727:     var y = 0;
                   1728:     while (element) {
                   1729: 	y += element.offsetTop;
                   1730: 	element = element.offsetParent;
                   1731:     }
                   1732:     return y;
                   1733: }
                   1734: 
                   1735: 
1.565     albertel 1736: function resize_textarea(textarea_id,bottom_id) {
                   1737:     init_geometry();
                   1738:     var textarea        = document.getElementById(textarea_id);
                   1739:     //alert(textarea);
                   1740: 
1.588     albertel 1741:     var textarea_top    = getY(textarea);
1.565     albertel 1742:     var textarea_height = textarea.offsetHeight;
                   1743:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1744:     var bottom_top      = getY(bottom);
1.565     albertel 1745:     var bottom_height   = bottom.offsetHeight;
                   1746:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1747:     var fudge           = 23;
1.565     albertel 1748:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1749:     if (new_height < 300) {
                   1750: 	new_height = 300;
                   1751:     }
                   1752:     textarea.style.height=new_height+'px';
                   1753: }
1.824     bisitz   1754: // ]]>
1.565     albertel 1755: </script>
                   1756: RESIZE
                   1757: 
                   1758: }
                   1759: 
1.1205    golterma 1760: sub colorfuleditor_js {
                   1761:     return <<"COLORFULEDIT"
                   1762: <script type="text/javascript">
                   1763: // <![CDATA[>
                   1764:     function fold_box(curDepth, lastresource){
                   1765: 
                   1766:     // we need a list because there can be several blocks you need to fold in one tag
                   1767:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1768:     // but there is only one folding button per tag
                   1769:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1770: 
                   1771:         if(block.item(0).style.display == 'none'){
                   1772: 
                   1773:             foldbutton.value = '@{[&mt("Hide")]}';
                   1774:             for (i = 0; i < block.length; i++){
                   1775:                 block.item(i).style.display = '';
                   1776:             }
                   1777:         }else{
                   1778: 
                   1779:             foldbutton.value = '@{[&mt("Show")]}';
                   1780:             for (i = 0; i < block.length; i++){
                   1781:                 // block.item(i).style.visibility = 'collapse';
                   1782:                 block.item(i).style.display = 'none';
                   1783:             }
                   1784:         };
                   1785:         saveState(lastresource);
                   1786:     }
                   1787: 
                   1788:     function saveState (lastresource) {
                   1789: 
                   1790:         var tag_list = getTagList();
                   1791:         if(tag_list != null){
                   1792:             var timestamp = new Date().getTime();
                   1793:             var key = lastresource;
                   1794: 
                   1795:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1796:             // starting with timestamp
                   1797:             var value = timestamp+';';
                   1798: 
                   1799:             // building the list of key-value pairs
                   1800:             for(var i = 0; i < tag_list.length; i++){
                   1801:                 value += tag_list[i]+',';
                   1802:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1803:             }
                   1804: 
                   1805:             // only iterate whole storage if nothing to override
                   1806:             if(localStorage.getItem(key) == null){        
                   1807: 
                   1808:                 // prevent storage from growing large
                   1809:                 if(localStorage.length > 50){
                   1810:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1811:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1812:                     var oldest_key;
                   1813:                     
                   1814:                     for(var i = 1; i < localStorage.length; i++){
                   1815:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1816:                             oldest_key = localStorage.key(i);
                   1817:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1818:                         }
                   1819:                     }
                   1820:                     localStorage.removeItem(oldest_key);
                   1821:                 }
                   1822:             }
                   1823:             localStorage.setItem(key,value);
                   1824:         }
                   1825:     }
                   1826: 
                   1827:     // restore folding status of blocks (on page load)
                   1828:     function restoreState (lastresource) {
                   1829:         if(localStorage.getItem(lastresource) != null){
                   1830:             var key = lastresource;
                   1831:             var value = localStorage.getItem(key);
                   1832:             var regex_delTimestamp = /^\d+;/;
                   1833: 
                   1834:             value.replace(regex_delTimestamp, '');
                   1835: 
                   1836:             var valueArr = value.split(';');
                   1837:             var pairs;
                   1838:             var elements;
                   1839:             for (var i = 0; i < valueArr.length; i++){
                   1840:                 pairs = valueArr[i].split(',');
                   1841:                 elements = document.getElementsByName(pairs[0]);
                   1842: 
                   1843:                 for (var j = 0; j < elements.length; j++){  
                   1844:                     elements[j].style.display = pairs[1];
                   1845:                     if (pairs[1] == "none"){
                   1846:                         var regex_id = /([_\\d]+)\$/;
                   1847:                         regex_id.exec(pairs[0]);
                   1848:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1849:                     }
                   1850:                 }
                   1851:             }
                   1852:         }
                   1853:     }
                   1854: 
                   1855:     function getTagList () {
                   1856:         
                   1857:         var stringToSearch = document.lonhomework.innerHTML;
                   1858: 
                   1859:         var ret = new Array();
                   1860:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1861:         var tag_list = stringToSearch.match(regex_findBlock);
                   1862: 
                   1863:         if(tag_list != null){
                   1864:             for(var i = 0; i < tag_list.length; i++){            
                   1865:                 ret.push(tag_list[i].replace(/"/, ''));
                   1866:             }
                   1867:         }
                   1868:         return ret;
                   1869:     }
                   1870: 
                   1871:     function saveScrollPosition (resource) {
                   1872:         var tag_list = getTagList();
                   1873: 
                   1874:         // we dont always want to jump to the first block
                   1875:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1876:         if(\$(window).scrollTop() > 170){
                   1877:             if(tag_list != null){
                   1878:                 var result;
                   1879:                 for(var i = 0; i < tag_list.length; i++){
                   1880:                     if(isElementInViewport(tag_list[i])){
                   1881:                         result += tag_list[i]+';';
                   1882:                     }
                   1883:                 }
                   1884:                 sessionStorage.setItem('anchor_'+resource, result);
                   1885:             }
                   1886:         } else {
                   1887:             // we dont need to save zero, just delete the item to leave everything tidy
                   1888:             sessionStorage.removeItem('anchor_'+resource);
                   1889:         }
                   1890:     }
                   1891: 
                   1892:     function restoreScrollPosition(resource){
                   1893: 
                   1894:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1895:         if(elem != null){
                   1896:             var tag_list = elem.split(';');
                   1897:             var elem_list;
                   1898: 
                   1899:             for(var i = 0; i < tag_list.length; i++){
                   1900:                 elem_list = document.getElementsByName(tag_list[i]);
                   1901:                 
                   1902:                 if(elem_list.length > 0){
                   1903:                     elem = elem_list[0];
                   1904:                     break;
                   1905:                 }
                   1906:             }
                   1907:             elem.scrollIntoView();
                   1908:         }
                   1909:     }
                   1910: 
                   1911:     function isElementInViewport(el) {
                   1912: 
                   1913:         // change to last element instead of first
                   1914:         var elem = document.getElementsByName(el);
                   1915:         var rect = elem[0].getBoundingClientRect();
                   1916: 
                   1917:         return (
                   1918:             rect.top >= 0 &&
                   1919:             rect.left >= 0 &&
                   1920:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1921:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1922:         );
                   1923:     }
                   1924:     
                   1925:     function autosize(depth){
                   1926:         var cmInst = window['cm'+depth];
                   1927:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1928: 
                   1929:         // is fixed size, switching to dynamic
                   1930:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1931:             cmInst.setSize("","auto");
                   1932:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1933:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1934: 
                   1935:         // is dynamic size, switching to fixed
                   1936:         } else {
                   1937:             cmInst.setSize("","300px");
                   1938:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1939:             sessionStorage.removeItem("autosized_"+depth);
                   1940:         }
                   1941:     }
                   1942: 
                   1943: 
                   1944: 
                   1945: // ]]>
                   1946: </script>
                   1947: COLORFULEDIT
                   1948: }
                   1949: 
                   1950: sub xmleditor_js {
                   1951:     return <<XMLEDIT
                   1952: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1953: <script type="text/javascript">
                   1954: // <![CDATA[>
                   1955: 
                   1956:     function saveScrollPosition (resource) {
                   1957: 
                   1958:         var scrollPos = \$(window).scrollTop();
                   1959:         sessionStorage.setItem(resource,scrollPos);
                   1960:     }
                   1961: 
                   1962:     function restoreScrollPosition(resource){
                   1963: 
                   1964:         var scrollPos = sessionStorage.getItem(resource);
                   1965:         \$(window).scrollTop(scrollPos);
                   1966:     }
                   1967: 
                   1968:     // unless internet explorer
                   1969:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1970: 
                   1971:         \$(document).ready(function() {
                   1972:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1973:         });
                   1974:     }
                   1975: 
                   1976:     // inserts text at cursor position into codemirror (xml editor only)
                   1977:     function insertText(text){
                   1978:         cm.focus();
                   1979:         var curPos = cm.getCursor();
                   1980:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1981:     }
                   1982: // ]]>
                   1983: </script>
                   1984: XMLEDIT
                   1985: }
                   1986: 
                   1987: sub insert_folding_button {
                   1988:     my $curDepth = $Apache::lonxml::curdepth;
                   1989:     my $lastresource = $env{'request.ambiguous'};
                   1990: 
                   1991:     return "<input type=\"button\" id=\"folding_btn_$curDepth\" 
                   1992:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1993: }
                   1994: 
1.565     albertel 1995: =pod
                   1996: 
1.256     matthew  1997: =head1 Excel and CSV file utility routines
                   1998: 
                   1999: =cut
                   2000: 
                   2001: ###############################################################
                   2002: ###############################################################
                   2003: 
                   2004: =pod
                   2005: 
1.1162    raeburn  2006: =over 4
                   2007: 
1.648     raeburn  2008: =item * &csv_translate($text) 
1.37      matthew  2009: 
1.185     www      2010: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2011: format.
                   2012: 
                   2013: =cut
                   2014: 
1.180     matthew  2015: ###############################################################
                   2016: ###############################################################
1.37      matthew  2017: sub csv_translate {
                   2018:     my $text = shift;
                   2019:     $text =~ s/\"/\"\"/g;
1.209     albertel 2020:     $text =~ s/\n/ /g;
1.37      matthew  2021:     return $text;
                   2022: }
1.180     matthew  2023: 
                   2024: ###############################################################
                   2025: ###############################################################
                   2026: 
                   2027: =pod
                   2028: 
1.648     raeburn  2029: =item * &define_excel_formats()
1.180     matthew  2030: 
                   2031: Define some commonly used Excel cell formats.
                   2032: 
                   2033: Currently supported formats:
                   2034: 
                   2035: =over 4
                   2036: 
                   2037: =item header
                   2038: 
                   2039: =item bold
                   2040: 
                   2041: =item h1
                   2042: 
                   2043: =item h2
                   2044: 
                   2045: =item h3
                   2046: 
1.256     matthew  2047: =item h4
                   2048: 
                   2049: =item i
                   2050: 
1.180     matthew  2051: =item date
                   2052: 
                   2053: =back
                   2054: 
                   2055: Inputs: $workbook
                   2056: 
                   2057: Returns: $format, a hash reference.
                   2058: 
1.1057    foxr     2059: 
1.180     matthew  2060: =cut
                   2061: 
                   2062: ###############################################################
                   2063: ###############################################################
                   2064: sub define_excel_formats {
                   2065:     my ($workbook) = @_;
                   2066:     my $format;
                   2067:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2068:                                                 bottom    => 1,
                   2069:                                                 align     => 'center');
                   2070:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2071:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2072:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2073:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2074:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2075:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2076:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2077:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2078:     return $format;
                   2079: }
                   2080: 
                   2081: ###############################################################
                   2082: ###############################################################
1.113     bowersj2 2083: 
                   2084: =pod
                   2085: 
1.648     raeburn  2086: =item * &create_workbook()
1.255     matthew  2087: 
                   2088: Create an Excel worksheet.  If it fails, output message on the
                   2089: request object and return undefs.
                   2090: 
                   2091: Inputs: Apache request object
                   2092: 
                   2093: Returns (undef) on failure, 
                   2094:     Excel worksheet object, scalar with filename, and formats 
                   2095:     from &Apache::loncommon::define_excel_formats on success
                   2096: 
                   2097: =cut
                   2098: 
                   2099: ###############################################################
                   2100: ###############################################################
                   2101: sub create_workbook {
                   2102:     my ($r) = @_;
                   2103:         #
                   2104:     # Create the excel spreadsheet
                   2105:     my $filename = '/prtspool/'.
1.258     albertel 2106:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2107:         time.'_'.rand(1000000000).'.xls';
                   2108:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2109:     if (! defined($workbook)) {
                   2110:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2111:         $r->print(
                   2112:             '<p class="LC_error">'
                   2113:            .&mt('Problems occurred in creating the new Excel file.')
                   2114:            .' '.&mt('This error has been logged.')
                   2115:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2116:            .'</p>'
                   2117:         );
1.255     matthew  2118:         return (undef);
                   2119:     }
                   2120:     #
1.1014    foxr     2121:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2122:     #
                   2123:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2124:     return ($workbook,$filename,$format);
                   2125: }
                   2126: 
                   2127: ###############################################################
                   2128: ###############################################################
                   2129: 
                   2130: =pod
                   2131: 
1.648     raeburn  2132: =item * &create_text_file()
1.113     bowersj2 2133: 
1.542     raeburn  2134: Create a file to write to and eventually make available to the user.
1.256     matthew  2135: If file creation fails, outputs an error message on the request object and 
                   2136: return undefs.
1.113     bowersj2 2137: 
1.256     matthew  2138: Inputs: Apache request object, and file suffix
1.113     bowersj2 2139: 
1.256     matthew  2140: Returns (undef) on failure, 
                   2141:     Filehandle and filename on success.
1.113     bowersj2 2142: 
                   2143: =cut
                   2144: 
1.256     matthew  2145: ###############################################################
                   2146: ###############################################################
                   2147: sub create_text_file {
                   2148:     my ($r,$suffix) = @_;
                   2149:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2150:     my $fh;
                   2151:     my $filename = '/prtspool/'.
1.258     albertel 2152:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2153:         time.'_'.rand(1000000000).'.'.$suffix;
                   2154:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2155:     if (! defined($fh)) {
                   2156:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2157:         $r->print(
                   2158:             '<p class="LC_error">'
                   2159:            .&mt('Problems occurred in creating the output file.')
                   2160:            .' '.&mt('This error has been logged.')
                   2161:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2162:            .'</p>'
                   2163:         );
1.113     bowersj2 2164:     }
1.256     matthew  2165:     return ($fh,$filename)
1.113     bowersj2 2166: }
                   2167: 
                   2168: 
1.256     matthew  2169: =pod 
1.113     bowersj2 2170: 
                   2171: =back
                   2172: 
                   2173: =cut
1.37      matthew  2174: 
                   2175: ###############################################################
1.33      matthew  2176: ##        Home server <option> list generating code          ##
                   2177: ###############################################################
1.35      matthew  2178: 
1.169     www      2179: # ------------------------------------------
                   2180: 
                   2181: sub domain_select {
                   2182:     my ($name,$value,$multiple)=@_;
                   2183:     my %domains=map { 
1.514     albertel 2184: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2185:     } &Apache::lonnet::all_domains();
1.169     www      2186:     if ($multiple) {
                   2187: 	$domains{''}=&mt('Any domain');
1.550     albertel 2188: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2189: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2190:     } else {
1.550     albertel 2191: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2192: 	return &select_form($name,$value,\%domains);
1.169     www      2193:     }
                   2194: }
                   2195: 
1.282     albertel 2196: #-------------------------------------------
                   2197: 
                   2198: =pod
                   2199: 
1.519     raeburn  2200: =head1 Routines for form select boxes
                   2201: 
                   2202: =over 4
                   2203: 
1.648     raeburn  2204: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2205: 
                   2206: Returns a string containing a <select> element int multiple mode
                   2207: 
                   2208: 
                   2209: Args:
                   2210:   $name - name of the <select> element
1.506     raeburn  2211:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2212:   $size - number of rows long the select element is
1.283     albertel 2213:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2214:           (shown text should already have been &mt())
1.506     raeburn  2215:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2216: 
1.282     albertel 2217: =cut
                   2218: 
                   2219: #-------------------------------------------
1.169     www      2220: sub multiple_select_form {
1.284     albertel 2221:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2222:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2223:     my $output='';
1.191     matthew  2224:     if (! defined($size)) {
                   2225:         $size = 4;
1.283     albertel 2226:         if (scalar(keys(%$hash))<4) {
                   2227:             $size = scalar(keys(%$hash));
1.191     matthew  2228:         }
                   2229:     }
1.734     bisitz   2230:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2231:     my @order;
1.506     raeburn  2232:     if (ref($order) eq 'ARRAY')  {
                   2233:         @order = @{$order};
                   2234:     } else {
                   2235:         @order = sort(keys(%$hash));
1.501     banghart 2236:     }
                   2237:     if (exists($$hash{'select_form_order'})) {
                   2238:         @order = @{$$hash{'select_form_order'}};
                   2239:     }
                   2240:         
1.284     albertel 2241:     foreach my $key (@order) {
1.356     albertel 2242:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2243:         $output.='selected="selected" ' if ($selected{$key});
                   2244:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2245:     }
                   2246:     $output.="</select>\n";
                   2247:     return $output;
                   2248: }
                   2249: 
1.88      www      2250: #-------------------------------------------
                   2251: 
                   2252: =pod
                   2253: 
1.970     raeburn  2254: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2255: 
                   2256: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2257: allow a user to select options from a ref to a hash containing:
                   2258: option_name => displayed text. An optional $onchange can include
                   2259: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2260: 
1.88      www      2261: See lonrights.pm for an example invocation and use.
                   2262: 
                   2263: =cut
                   2264: 
                   2265: #-------------------------------------------
                   2266: sub select_form {
1.970     raeburn  2267:     my ($def,$name,$hashref,$onchange) = @_;
                   2268:     return unless (ref($hashref) eq 'HASH');
                   2269:     if ($onchange) {
                   2270:         $onchange = ' onchange="'.$onchange.'"';
                   2271:     }
                   2272:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2273:     my @keys;
1.970     raeburn  2274:     if (exists($hashref->{'select_form_order'})) {
                   2275: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2276:     } else {
1.970     raeburn  2277: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2278:     }
1.356     albertel 2279:     foreach my $key (@keys) {
                   2280:         $selectform.=
                   2281: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2282:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2283:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2284:     }
                   2285:     $selectform.="</select>";
                   2286:     return $selectform;
                   2287: }
                   2288: 
1.475     www      2289: # For display filters
                   2290: 
                   2291: sub display_filter {
1.1074    raeburn  2292:     my ($context) = @_;
1.475     www      2293:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2294:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2295:     my $phraseinput = 'hidden';
                   2296:     my $includeinput = 'hidden';
                   2297:     my ($checked,$includetypestext);
                   2298:     if ($env{'form.displayfilter'} eq 'containing') {
                   2299:         $phraseinput = 'text'; 
                   2300:         if ($context eq 'parmslog') {
                   2301:             $includeinput = 'checkbox';
                   2302:             if ($env{'form.includetypes'}) {
                   2303:                 $checked = ' checked="checked"';
                   2304:             }
                   2305:             $includetypestext = &mt('Include parameter types');
                   2306:         }
                   2307:     } else {
                   2308:         $includetypestext = '&nbsp;';
                   2309:     }
                   2310:     my ($additional,$secondid,$thirdid);
                   2311:     if ($context eq 'parmslog') {
                   2312:         $additional = 
                   2313:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2314:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2315:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2316:             '</label>';
                   2317:         $secondid = 'includetypes';
                   2318:         $thirdid = 'includetypestext';
                   2319:     }
                   2320:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2321:                                                     '$secondid','$thirdid')";
                   2322:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2323: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2324: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2325: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2326:            &mt('Filter: [_1]',
1.477     www      2327: 	   &select_form($env{'form.displayfilter'},
                   2328: 			'displayfilter',
1.970     raeburn  2329: 			{'currentfolder' => 'Current folder/page',
1.477     www      2330: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2331: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2332: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2333:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2334:                          '" />'.$additional;
                   2335: }
                   2336: 
                   2337: sub display_filter_js {
                   2338:     my $includetext = &mt('Include parameter types');
                   2339:     return <<"ENDJS";
                   2340:   
                   2341: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2342:     var firstType = 'hidden';
                   2343:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2344:         firstType = 'text';
                   2345:     }
                   2346:     firstObject = document.getElementById(firstid);
                   2347:     if (typeof(firstObject) == 'object') {
                   2348:         if (firstObject.type != firstType) {
                   2349:             changeInputType(firstObject,firstType);
                   2350:         }
                   2351:     }
                   2352:     if (context == 'parmslog') {
                   2353:         var secondType = 'hidden';
                   2354:         if (firstType == 'text') {
                   2355:             secondType = 'checkbox';
                   2356:         }
                   2357:         secondObject = document.getElementById(secondid);  
                   2358:         if (typeof(secondObject) == 'object') {
                   2359:             if (secondObject.type != secondType) {
                   2360:                 changeInputType(secondObject,secondType);
                   2361:             }
                   2362:         }
                   2363:         var textItem = document.getElementById(thirdid);
                   2364:         var currtext = textItem.innerHTML;
                   2365:         var newtext;
                   2366:         if (firstType == 'text') {
                   2367:             newtext = '$includetext';
                   2368:         } else {
                   2369:             newtext = '&nbsp;';
                   2370:         }
                   2371:         if (currtext != newtext) {
                   2372:             textItem.innerHTML = newtext;
                   2373:         }
                   2374:     }
                   2375:     return;
                   2376: }
                   2377: 
                   2378: function changeInputType(oldObject,newType) {
                   2379:     var newObject = document.createElement('input');
                   2380:     newObject.type = newType;
                   2381:     if (oldObject.size) {
                   2382:         newObject.size = oldObject.size;
                   2383:     }
                   2384:     if (oldObject.value) {
                   2385:         newObject.value = oldObject.value;
                   2386:     }
                   2387:     if (oldObject.name) {
                   2388:         newObject.name = oldObject.name;
                   2389:     }
                   2390:     if (oldObject.id) {
                   2391:         newObject.id = oldObject.id;
                   2392:     }
                   2393:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2394:     return;
                   2395: }
                   2396: 
                   2397: ENDJS
1.475     www      2398: }
                   2399: 
1.167     www      2400: sub gradeleveldescription {
                   2401:     my $gradelevel=shift;
                   2402:     my %gradelevels=(0 => 'Not specified',
                   2403: 		     1 => 'Grade 1',
                   2404: 		     2 => 'Grade 2',
                   2405: 		     3 => 'Grade 3',
                   2406: 		     4 => 'Grade 4',
                   2407: 		     5 => 'Grade 5',
                   2408: 		     6 => 'Grade 6',
                   2409: 		     7 => 'Grade 7',
                   2410: 		     8 => 'Grade 8',
                   2411: 		     9 => 'Grade 9',
                   2412: 		     10 => 'Grade 10',
                   2413: 		     11 => 'Grade 11',
                   2414: 		     12 => 'Grade 12',
                   2415: 		     13 => 'Grade 13',
                   2416: 		     14 => '100 Level',
                   2417: 		     15 => '200 Level',
                   2418: 		     16 => '300 Level',
                   2419: 		     17 => '400 Level',
                   2420: 		     18 => 'Graduate Level');
                   2421:     return &mt($gradelevels{$gradelevel});
                   2422: }
                   2423: 
1.163     www      2424: sub select_level_form {
                   2425:     my ($deflevel,$name)=@_;
                   2426:     unless ($deflevel) { $deflevel=0; }
1.167     www      2427:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2428:     for (my $i=0; $i<=18; $i++) {
                   2429:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2430:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2431:                 ">".&gradeleveldescription($i)."</option>\n";
                   2432:     }
                   2433:     $selectform.="</select>";
                   2434:     return $selectform;
1.163     www      2435: }
1.167     www      2436: 
1.35      matthew  2437: #-------------------------------------------
                   2438: 
1.45      matthew  2439: =pod
                   2440: 
1.1121    raeburn  2441: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2442: 
                   2443: Returns a string containing a <select name='$name' size='1'> form to 
                   2444: allow a user to select the domain to preform an operation in.  
                   2445: See loncreateuser.pm for an example invocation and use.
                   2446: 
1.90      www      2447: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2448: selected");
                   2449: 
1.743     raeburn  2450: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2451: 
1.910     raeburn  2452: The optional $onchange argument specifies what should occur if the domain selector is changed, e.g., 'this.form.submit()' if the form is to be automatically submitted.
                   2453: 
1.1121    raeburn  2454: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2455: 
                   2456: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
1.563     raeburn  2457: 
1.35      matthew  2458: =cut
                   2459: 
                   2460: #-------------------------------------------
1.34      matthew  2461: sub select_dom_form {
1.1121    raeburn  2462:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2463:     if ($onchange) {
1.874     raeburn  2464:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2465:     }
1.1121    raeburn  2466:     my (@domains,%exclude);
1.910     raeburn  2467:     if (ref($incdoms) eq 'ARRAY') {
                   2468:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2469:     } else {
                   2470:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2471:     }
1.90      www      2472:     if ($includeempty) { @domains=('',@domains); }
1.1121    raeburn  2473:     if (ref($excdoms) eq 'ARRAY') {
                   2474:         map { $exclude{$_} = 1; } @{$excdoms}; 
                   2475:     }
1.743     raeburn  2476:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2477:     foreach my $dom (@domains) {
1.1121    raeburn  2478:         next if ($exclude{$dom});
1.356     albertel 2479:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2480:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2481:         if ($showdomdesc) {
                   2482:             if ($dom ne '') {
                   2483:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2484:                 if ($domdesc ne '') {
                   2485:                     $selectdomain .= ' ('.$domdesc.')';
                   2486:                 }
                   2487:             } 
                   2488:         }
                   2489:         $selectdomain .= "</option>\n";
1.34      matthew  2490:     }
                   2491:     $selectdomain.="</select>";
                   2492:     return $selectdomain;
                   2493: }
                   2494: 
1.35      matthew  2495: #-------------------------------------------
                   2496: 
1.45      matthew  2497: =pod
                   2498: 
1.648     raeburn  2499: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2500: 
1.586     raeburn  2501: input: 4 arguments (two required, two optional) - 
                   2502:     $domain - domain of new user
                   2503:     $name - name of form element
                   2504:     $default - Value of 'default' causes a default item to be first 
                   2505:                             option, and selected by default. 
                   2506:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2507:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2508: output: returns 2 items: 
1.586     raeburn  2509: (a) form element which contains either:
                   2510:    (i) <select name="$name">
                   2511:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2512:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2513:        </select>
                   2514:        form item if there are multiple library servers in $domain, or
                   2515:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2516:        if there is only one library server in $domain.
                   2517: 
                   2518: (b) number of library servers found.
                   2519: 
                   2520: See loncreateuser.pm for example of use.
1.35      matthew  2521: 
                   2522: =cut
                   2523: 
                   2524: #-------------------------------------------
1.586     raeburn  2525: sub home_server_form_item {
                   2526:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2527:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2528:     my $result;
                   2529:     my $numlib = keys(%servers);
                   2530:     if ($numlib > 1) {
                   2531:         $result .= '<select name="'.$name.'" />'."\n";
                   2532:         if ($default) {
1.804     bisitz   2533:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2534:                        '</option>'."\n";
                   2535:         }
                   2536:         foreach my $hostid (sort(keys(%servers))) {
                   2537:             $result.= '<option value="'.$hostid.'">'.
                   2538: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2539:         }
                   2540:         $result .= '</select>'."\n";
                   2541:     } elsif ($numlib == 1) {
                   2542:         my $hostid;
                   2543:         foreach my $item (keys(%servers)) {
                   2544:             $hostid = $item;
                   2545:         }
                   2546:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2547:                    $hostid.'" />';
                   2548:                    if (!$hide) {
                   2549:                        $result .= $hostid.' '.$servers{$hostid};
                   2550:                    }
                   2551:                    $result .= "\n";
                   2552:     } elsif ($default) {
                   2553:         $result .= '<input type="hidden" name="'.$name.
                   2554:                    '" value="default" />';
                   2555:                    if (!$hide) {
                   2556:                        $result .= &mt('default');
                   2557:                    }
                   2558:                    $result .= "\n";
1.33      matthew  2559:     }
1.586     raeburn  2560:     return ($result,$numlib);
1.33      matthew  2561: }
1.112     bowersj2 2562: 
                   2563: =pod
                   2564: 
1.534     albertel 2565: =back 
                   2566: 
1.112     bowersj2 2567: =cut
1.87      matthew  2568: 
                   2569: ###############################################################
1.112     bowersj2 2570: ##                  Decoding User Agent                      ##
1.87      matthew  2571: ###############################################################
                   2572: 
                   2573: =pod
                   2574: 
1.112     bowersj2 2575: =head1 Decoding the User Agent
                   2576: 
                   2577: =over 4
                   2578: 
                   2579: =item * &decode_user_agent()
1.87      matthew  2580: 
                   2581: Inputs: $r
                   2582: 
                   2583: Outputs:
                   2584: 
                   2585: =over 4
                   2586: 
1.112     bowersj2 2587: =item * $httpbrowser
1.87      matthew  2588: 
1.112     bowersj2 2589: =item * $clientbrowser
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientversion
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientmathml
1.87      matthew  2594: 
1.112     bowersj2 2595: =item * $clientunicode
1.87      matthew  2596: 
1.112     bowersj2 2597: =item * $clientos
1.87      matthew  2598: 
1.1137    raeburn  2599: =item * $clientmobile
                   2600: 
1.1141    raeburn  2601: =item * $clientinfo
                   2602: 
1.1194    raeburn  2603: =item * $clientosversion
                   2604: 
1.87      matthew  2605: =back
                   2606: 
1.157     matthew  2607: =back 
                   2608: 
1.87      matthew  2609: =cut
                   2610: 
                   2611: ###############################################################
                   2612: ###############################################################
                   2613: sub decode_user_agent {
1.247     albertel 2614:     my ($r)=@_;
1.87      matthew  2615:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2616:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2617:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2618:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2619:     my $clientbrowser='unknown';
                   2620:     my $clientversion='0';
                   2621:     my $clientmathml='';
                   2622:     my $clientunicode='0';
1.1137    raeburn  2623:     my $clientmobile=0;
1.1194    raeburn  2624:     my $clientosversion='';
1.87      matthew  2625:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1193    raeburn  2626:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2627: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2628: 	    $clientbrowser=$bname;
                   2629:             $httpbrowser=~/$vreg/i;
                   2630: 	    $clientversion=$1;
                   2631:             $clientmathml=($clientversion>=$minv);
                   2632:             $clientunicode=($clientversion>=$univ);
                   2633: 	}
                   2634:     }
                   2635:     my $clientos='unknown';
1.1141    raeburn  2636:     my $clientinfo;
1.87      matthew  2637:     if (($httpbrowser=~/linux/i) ||
                   2638:         ($httpbrowser=~/unix/i) ||
                   2639:         ($httpbrowser=~/ux/i) ||
                   2640:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2641:     if (($httpbrowser=~/vax/i) ||
                   2642:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2643:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2644:     if (($httpbrowser=~/mac/i) ||
                   2645:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1194    raeburn  2646:     if ($httpbrowser=~/win/i) {
                   2647:         $clientos='win';
                   2648:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2649:             $clientosversion = $1;
                   2650:         }
                   2651:     }
1.87      matthew  2652:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1137    raeburn  2653:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2654:         $clientmobile=lc($1);
                   2655:     }
1.1141    raeburn  2656:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2657:         $clientinfo = 'firefox-'.$1;
                   2658:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2659:         $clientinfo = 'chromeframe-'.$1;
                   2660:     }
1.87      matthew  2661:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1194    raeburn  2662:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2663:             $clientosversion);
1.87      matthew  2664: }
                   2665: 
1.32      matthew  2666: ###############################################################
                   2667: ##    Authentication changing form generation subroutines    ##
                   2668: ###############################################################
                   2669: ##
                   2670: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2671: ## hash, and have reasonable default values.
                   2672: ##
                   2673: ##    formname = the name given in the <form> tag.
1.35      matthew  2674: #-------------------------------------------
                   2675: 
1.45      matthew  2676: =pod
                   2677: 
1.112     bowersj2 2678: =head1 Authentication Routines
                   2679: 
                   2680: =over 4
                   2681: 
1.648     raeburn  2682: =item * &authform_xxxxxx()
1.35      matthew  2683: 
                   2684: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2685: handle some of the conveniences required for authentication forms.  
                   2686: This is not an optimal method, but it works.  
                   2687: 
                   2688: =over 4
                   2689: 
1.112     bowersj2 2690: =item * authform_header
1.35      matthew  2691: 
1.112     bowersj2 2692: =item * authform_authorwarning
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_nochange
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_kerberos
1.35      matthew  2697: 
1.112     bowersj2 2698: =item * authform_internal
1.35      matthew  2699: 
1.112     bowersj2 2700: =item * authform_filesystem
1.35      matthew  2701: 
                   2702: =back
                   2703: 
1.648     raeburn  2704: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2705: 
1.35      matthew  2706: =cut
                   2707: 
                   2708: #-------------------------------------------
1.32      matthew  2709: sub authform_header{  
                   2710:     my %in = (
                   2711:         formname => 'cu',
1.80      albertel 2712:         kerb_def_dom => '',
1.32      matthew  2713:         @_,
                   2714:     );
                   2715:     $in{'formname'} = 'document.' . $in{'formname'};
                   2716:     my $result='';
1.80      albertel 2717: 
                   2718: #---------------------------------------------- Code for upper case translation
                   2719:     my $Javascript_toUpperCase;
                   2720:     unless ($in{kerb_def_dom}) {
                   2721:         $Javascript_toUpperCase =<<"END";
                   2722:         switch (choice) {
                   2723:            case 'krb': currentform.elements[choicearg].value =
                   2724:                currentform.elements[choicearg].value.toUpperCase();
                   2725:                break;
                   2726:            default:
                   2727:         }
                   2728: END
                   2729:     } else {
                   2730:         $Javascript_toUpperCase = "";
                   2731:     }
                   2732: 
1.165     raeburn  2733:     my $radioval = "'nochange'";
1.591     raeburn  2734:     if (defined($in{'curr_authtype'})) {
                   2735:         if ($in{'curr_authtype'} ne '') {
                   2736:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2737:         }
1.174     matthew  2738:     }
1.165     raeburn  2739:     my $argfield = 'null';
1.591     raeburn  2740:     if (defined($in{'mode'})) {
1.165     raeburn  2741:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2742:             if (defined($in{'curr_autharg'})) {
                   2743:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2744:                     $argfield = "'$in{'curr_autharg'}'";
                   2745:                 }
                   2746:             }
                   2747:         }
                   2748:     }
                   2749: 
1.32      matthew  2750:     $result.=<<"END";
                   2751: var current = new Object();
1.165     raeburn  2752: current.radiovalue = $radioval;
                   2753: current.argfield = $argfield;
1.32      matthew  2754: 
                   2755: function changed_radio(choice,currentform) {
                   2756:     var choicearg = choice + 'arg';
                   2757:     // If a radio button in changed, we need to change the argfield
                   2758:     if (current.radiovalue != choice) {
                   2759:         current.radiovalue = choice;
                   2760:         if (current.argfield != null) {
                   2761:             currentform.elements[current.argfield].value = '';
                   2762:         }
                   2763:         if (choice == 'nochange') {
                   2764:             current.argfield = null;
                   2765:         } else {
                   2766:             current.argfield = choicearg;
                   2767:             switch(choice) {
                   2768:                 case 'krb': 
                   2769:                     currentform.elements[current.argfield].value = 
                   2770:                         "$in{'kerb_def_dom'}";
                   2771:                 break;
                   2772:               default:
                   2773:                 break;
                   2774:             }
                   2775:         }
                   2776:     }
                   2777:     return;
                   2778: }
1.22      www      2779: 
1.32      matthew  2780: function changed_text(choice,currentform) {
                   2781:     var choicearg = choice + 'arg';
                   2782:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2783:         $Javascript_toUpperCase
1.32      matthew  2784:         // clear old field
                   2785:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2786:             currentform.elements[current.argfield].value = '';
                   2787:         }
                   2788:         current.argfield = choicearg;
                   2789:     }
                   2790:     set_auth_radio_buttons(choice,currentform);
                   2791:     return;
1.20      www      2792: }
1.32      matthew  2793: 
                   2794: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2795:     var numauthchoices = currentform.login.length;
                   2796:     if (typeof numauthchoices  == "undefined") {
                   2797:         return;
                   2798:     } 
1.32      matthew  2799:     var i=0;
1.986     raeburn  2800:     while (i < numauthchoices) {
1.32      matthew  2801:         if (currentform.login[i].value == newvalue) { break; }
                   2802:         i++;
                   2803:     }
1.986     raeburn  2804:     if (i == numauthchoices) {
1.32      matthew  2805:         return;
                   2806:     }
                   2807:     current.radiovalue = newvalue;
                   2808:     currentform.login[i].checked = true;
                   2809:     return;
                   2810: }
                   2811: END
                   2812:     return $result;
                   2813: }
                   2814: 
1.1106    raeburn  2815: sub authform_authorwarning {
1.32      matthew  2816:     my $result='';
1.144     matthew  2817:     $result='<i>'.
                   2818:         &mt('As a general rule, only authors or co-authors should be '.
                   2819:             'filesystem authenticated '.
                   2820:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2821:     return $result;
                   2822: }
                   2823: 
1.1106    raeburn  2824: sub authform_nochange {
1.32      matthew  2825:     my %in = (
                   2826:               formname => 'document.cu',
                   2827:               kerb_def_dom => 'MSU.EDU',
                   2828:               @_,
                   2829:           );
1.1106    raeburn  2830:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.586     raeburn  2831:     my $result;
1.1104    raeburn  2832:     if (!$authnum) {
1.1105    raeburn  2833:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2834:     } else {
                   2835:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2836:                   '<input type="radio" name="login" value="nochange" '.
                   2837:                   'checked="checked" onclick="'.
1.281     albertel 2838:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2839: 	    '</label>';
1.586     raeburn  2840:     }
1.32      matthew  2841:     return $result;
                   2842: }
                   2843: 
1.591     raeburn  2844: sub authform_kerberos {
1.32      matthew  2845:     my %in = (
                   2846:               formname => 'document.cu',
                   2847:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2848:               kerb_def_auth => 'krb4',
1.32      matthew  2849:               @_,
                   2850:               );
1.586     raeburn  2851:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2852:         $autharg,$jscall);
1.1106    raeburn  2853:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2854:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2855:        $check5 = ' checked="checked"';
1.80      albertel 2856:     } else {
1.772     bisitz   2857:        $check4 = ' checked="checked"';
1.80      albertel 2858:     }
1.165     raeburn  2859:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2860:     if (defined($in{'curr_authtype'})) {
                   2861:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2862:             $krbcheck = ' checked="checked"';
1.623     raeburn  2863:             if (defined($in{'mode'})) {
                   2864:                 if ($in{'mode'} eq 'modifyuser') {
                   2865:                     $krbcheck = '';
                   2866:                 }
                   2867:             }
1.591     raeburn  2868:             if (defined($in{'curr_kerb_ver'})) {
                   2869:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2870:                     $check5 = ' checked="checked"';
1.591     raeburn  2871:                     $check4 = '';
                   2872:                 } else {
1.772     bisitz   2873:                     $check4 = ' checked="checked"';
1.591     raeburn  2874:                     $check5 = '';
                   2875:                 }
1.586     raeburn  2876:             }
1.591     raeburn  2877:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2878:                 $krbarg = $in{'curr_autharg'};
                   2879:             }
1.586     raeburn  2880:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2881:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2882:                     $result = 
                   2883:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2884:         $in{'curr_autharg'},$krbver);
                   2885:                 } else {
                   2886:                     $result =
                   2887:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2888:                 }
                   2889:                 return $result; 
                   2890:             }
                   2891:         }
                   2892:     } else {
                   2893:         if ($authnum == 1) {
1.784     bisitz   2894:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2895:         }
                   2896:     }
1.586     raeburn  2897:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2898:         return;
1.587     raeburn  2899:     } elsif ($authtype eq '') {
1.591     raeburn  2900:         if (defined($in{'mode'})) {
1.587     raeburn  2901:             if ($in{'mode'} eq 'modifycourse') {
                   2902:                 if ($authnum == 1) {
1.1104    raeburn  2903:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2904:                 }
                   2905:             }
                   2906:         }
1.586     raeburn  2907:     }
                   2908:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2909:     if ($authtype eq '') {
                   2910:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2911:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2912:                     $krbcheck.' />';
                   2913:     }
                   2914:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1106    raeburn  2915:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2916:          $in{'curr_authtype'} eq 'krb5') ||
1.1106    raeburn  2917:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2918:          $in{'curr_authtype'} eq 'krb4')) {
                   2919:         $result .= &mt
1.144     matthew  2920:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2921:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2922:          '<label>'.$authtype,
1.281     albertel 2923:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2924:              'value="'.$krbarg.'" '.
1.144     matthew  2925:              'onchange="'.$jscall.'" />',
1.281     albertel 2926:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2927:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2928: 	 '</label>');
1.586     raeburn  2929:     } elsif ($can_assign{'krb4'}) {
                   2930:         $result .= &mt
                   2931:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2932:          '[_3] Version 4 [_4]',
                   2933:          '<label>'.$authtype,
                   2934:          '</label><input type="text" size="10" name="krbarg" '.
                   2935:              'value="'.$krbarg.'" '.
                   2936:              'onchange="'.$jscall.'" />',
                   2937:          '<label><input type="hidden" name="krbver" value="4" />',
                   2938:          '</label>');
                   2939:     } elsif ($can_assign{'krb5'}) {
                   2940:         $result .= &mt
                   2941:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2942:          '[_3] Version 5 [_4]',
                   2943:          '<label>'.$authtype,
                   2944:          '</label><input type="text" size="10" name="krbarg" '.
                   2945:              'value="'.$krbarg.'" '.
                   2946:              'onchange="'.$jscall.'" />',
                   2947:          '<label><input type="hidden" name="krbver" value="5" />',
                   2948:          '</label>');
                   2949:     }
1.32      matthew  2950:     return $result;
                   2951: }
                   2952: 
1.1106    raeburn  2953: sub authform_internal {
1.586     raeburn  2954:     my %in = (
1.32      matthew  2955:                 formname => 'document.cu',
                   2956:                 kerb_def_dom => 'MSU.EDU',
                   2957:                 @_,
                   2958:                 );
1.586     raeburn  2959:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  2960:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2961:     if (defined($in{'curr_authtype'})) {
                   2962:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2963:             if ($can_assign{'int'}) {
1.772     bisitz   2964:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2965:                 if (defined($in{'mode'})) {
                   2966:                     if ($in{'mode'} eq 'modifyuser') {
                   2967:                         $intcheck = '';
                   2968:                     }
                   2969:                 }
1.591     raeburn  2970:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2971:                     $intarg = $in{'curr_autharg'};
                   2972:                 }
                   2973:             } else {
                   2974:                 $result = &mt('Currently internally authenticated.');
                   2975:                 return $result;
1.165     raeburn  2976:             }
                   2977:         }
1.586     raeburn  2978:     } else {
                   2979:         if ($authnum == 1) {
1.784     bisitz   2980:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2981:         }
                   2982:     }
                   2983:     if (!$can_assign{'int'}) {
                   2984:         return;
1.587     raeburn  2985:     } elsif ($authtype eq '') {
1.591     raeburn  2986:         if (defined($in{'mode'})) {
1.587     raeburn  2987:             if ($in{'mode'} eq 'modifycourse') {
                   2988:                 if ($authnum == 1) {
1.1104    raeburn  2989:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2990:                 }
                   2991:             }
                   2992:         }
1.165     raeburn  2993:     }
1.586     raeburn  2994:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2995:     if ($authtype eq '') {
                   2996:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2997:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2998:     }
1.605     bisitz   2999:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  3000:                $intarg.'" onchange="'.$jscall.'" />';
                   3001:     $result = &mt
1.144     matthew  3002:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3003:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   3004:     $result.="<label><input type=\"checkbox\" name=\"visible\" onclick='if (this.checked) { this.form.intarg.type=\"text\" } else { this.form.intarg.type=\"password\" }' />".&mt('Visible input').'</label>';
1.32      matthew  3005:     return $result;
                   3006: }
                   3007: 
1.1104    raeburn  3008: sub authform_local {
1.32      matthew  3009:     my %in = (
                   3010:               formname => 'document.cu',
                   3011:               kerb_def_dom => 'MSU.EDU',
                   3012:               @_,
                   3013:               );
1.586     raeburn  3014:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3015:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3016:     if (defined($in{'curr_authtype'})) {
                   3017:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3018:             if ($can_assign{'loc'}) {
1.772     bisitz   3019:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3020:                 if (defined($in{'mode'})) {
                   3021:                     if ($in{'mode'} eq 'modifyuser') {
                   3022:                         $loccheck = '';
                   3023:                     }
                   3024:                 }
1.591     raeburn  3025:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3026:                     $locarg = $in{'curr_autharg'};
                   3027:                 }
                   3028:             } else {
                   3029:                 $result = &mt('Currently using local (institutional) authentication.');
                   3030:                 return $result;
1.165     raeburn  3031:             }
                   3032:         }
1.586     raeburn  3033:     } else {
                   3034:         if ($authnum == 1) {
1.784     bisitz   3035:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3036:         }
                   3037:     }
                   3038:     if (!$can_assign{'loc'}) {
                   3039:         return;
1.587     raeburn  3040:     } elsif ($authtype eq '') {
1.591     raeburn  3041:         if (defined($in{'mode'})) {
1.587     raeburn  3042:             if ($in{'mode'} eq 'modifycourse') {
                   3043:                 if ($authnum == 1) {
1.1104    raeburn  3044:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  3045:                 }
                   3046:             }
                   3047:         }
1.165     raeburn  3048:     }
1.586     raeburn  3049:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3050:     if ($authtype eq '') {
                   3051:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3052:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   3053:                     $jscall.'" />';
                   3054:     }
                   3055:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   3056:                $locarg.'" onchange="'.$jscall.'" />';
                   3057:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3058:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3059:     return $result;
                   3060: }
                   3061: 
1.1106    raeburn  3062: sub authform_filesystem {
1.32      matthew  3063:     my %in = (
                   3064:               formname => 'document.cu',
                   3065:               kerb_def_dom => 'MSU.EDU',
                   3066:               @_,
                   3067:               );
1.586     raeburn  3068:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1106    raeburn  3069:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  3070:     if (defined($in{'curr_authtype'})) {
                   3071:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3072:             if ($can_assign{'fsys'}) {
1.772     bisitz   3073:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3074:                 if (defined($in{'mode'})) {
                   3075:                     if ($in{'mode'} eq 'modifyuser') {
                   3076:                         $fsyscheck = '';
                   3077:                     }
                   3078:                 }
1.586     raeburn  3079:             } else {
                   3080:                 $result = &mt('Currently Filesystem Authenticated.');
                   3081:                 return $result;
                   3082:             }           
                   3083:         }
                   3084:     } else {
                   3085:         if ($authnum == 1) {
1.784     bisitz   3086:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3087:         }
                   3088:     }
                   3089:     if (!$can_assign{'fsys'}) {
                   3090:         return;
1.587     raeburn  3091:     } elsif ($authtype eq '') {
1.591     raeburn  3092:         if (defined($in{'mode'})) {
1.587     raeburn  3093:             if ($in{'mode'} eq 'modifycourse') {
                   3094:                 if ($authnum == 1) {
1.1104    raeburn  3095:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  3096:                 }
                   3097:             }
                   3098:         }
1.586     raeburn  3099:     }
                   3100:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3101:     if ($authtype eq '') {
                   3102:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3103:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   3104:                     $jscall.'" />';
                   3105:     }
                   3106:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   3107:                ' onchange="'.$jscall.'" />';
                   3108:     $result = &mt
1.144     matthew  3109:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3110:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  3111:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   3112:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  3113:                   'onchange="'.$jscall.'" />');
1.32      matthew  3114:     return $result;
                   3115: }
                   3116: 
1.586     raeburn  3117: sub get_assignable_auth {
                   3118:     my ($dom) = @_;
                   3119:     if ($dom eq '') {
                   3120:         $dom = $env{'request.role.domain'};
                   3121:     }
                   3122:     my %can_assign = (
                   3123:                           krb4 => 1,
                   3124:                           krb5 => 1,
                   3125:                           int  => 1,
                   3126:                           loc  => 1,
                   3127:                      );
                   3128:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3129:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3130:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3131:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3132:             my $context;
                   3133:             if ($env{'request.role'} =~ /^au/) {
                   3134:                 $context = 'author';
                   3135:             } elsif ($env{'request.role'} =~ /^dc/) {
                   3136:                 $context = 'domain';
                   3137:             } elsif ($env{'request.course.id'}) {
                   3138:                 $context = 'course';
                   3139:             }
                   3140:             if ($context) {
                   3141:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3142:                    %can_assign = %{$authhash->{$context}}; 
                   3143:                 }
                   3144:             }
                   3145:         }
                   3146:     }
                   3147:     my $authnum = 0;
                   3148:     foreach my $key (keys(%can_assign)) {
                   3149:         if ($can_assign{$key}) {
                   3150:             $authnum ++;
                   3151:         }
                   3152:     }
                   3153:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3154:         $authnum --;
                   3155:     }
                   3156:     return ($authnum,%can_assign);
                   3157: }
                   3158: 
1.80      albertel 3159: ###############################################################
                   3160: ##    Get Kerberos Defaults for Domain                 ##
                   3161: ###############################################################
                   3162: ##
                   3163: ## Returns default kerberos version and an associated argument
                   3164: ## as listed in file domain.tab. If not listed, provides
                   3165: ## appropriate default domain and kerberos version.
                   3166: ##
                   3167: #-------------------------------------------
                   3168: 
                   3169: =pod
                   3170: 
1.648     raeburn  3171: =item * &get_kerberos_defaults()
1.80      albertel 3172: 
                   3173: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3174: version and domain. If not found, it defaults to version 4 and the 
                   3175: domain of the server.
1.80      albertel 3176: 
1.648     raeburn  3177: =over 4
                   3178: 
1.80      albertel 3179: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3180: 
1.648     raeburn  3181: =back
                   3182: 
                   3183: =back
                   3184: 
1.80      albertel 3185: =cut
                   3186: 
                   3187: #-------------------------------------------
                   3188: sub get_kerberos_defaults {
                   3189:     my $domain=shift;
1.641     raeburn  3190:     my ($krbdef,$krbdefdom);
                   3191:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3192:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3193:         $krbdef = $domdefaults{'auth_def'};
                   3194:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3195:     } else {
1.80      albertel 3196:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3197:         my $krbdefdom=$1;
                   3198:         $krbdefdom=~tr/a-z/A-Z/;
                   3199:         $krbdef = "krb4";
                   3200:     }
                   3201:     return ($krbdef,$krbdefdom);
                   3202: }
1.112     bowersj2 3203: 
1.32      matthew  3204: 
1.46      matthew  3205: ###############################################################
                   3206: ##                Thesaurus Functions                        ##
                   3207: ###############################################################
1.20      www      3208: 
1.46      matthew  3209: =pod
1.20      www      3210: 
1.112     bowersj2 3211: =head1 Thesaurus Functions
                   3212: 
                   3213: =over 4
                   3214: 
1.648     raeburn  3215: =item * &initialize_keywords()
1.46      matthew  3216: 
                   3217: Initializes the package variable %Keywords if it is empty.  Uses the
                   3218: package variable $thesaurus_db_file.
                   3219: 
                   3220: =cut
                   3221: 
                   3222: ###################################################
                   3223: 
                   3224: sub initialize_keywords {
                   3225:     return 1 if (scalar keys(%Keywords));
                   3226:     # If we are here, %Keywords is empty, so fill it up
                   3227:     #   Make sure the file we need exists...
                   3228:     if (! -e $thesaurus_db_file) {
                   3229:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3230:                                  " failed because it does not exist");
                   3231:         return 0;
                   3232:     }
                   3233:     #   Set up the hash as a database
                   3234:     my %thesaurus_db;
                   3235:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3236:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3237:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3238:                                  $thesaurus_db_file);
                   3239:         return 0;
                   3240:     } 
                   3241:     #  Get the average number of appearances of a word.
                   3242:     my $avecount = $thesaurus_db{'average.count'};
                   3243:     #  Put keywords (those that appear > average) into %Keywords
                   3244:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3245:         my ($count,undef) = split /:/,$data;
                   3246:         $Keywords{$word}++ if ($count > $avecount);
                   3247:     }
                   3248:     untie %thesaurus_db;
                   3249:     # Remove special values from %Keywords.
1.356     albertel 3250:     foreach my $value ('total.count','average.count') {
                   3251:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3252:   }
1.46      matthew  3253:     return 1;
                   3254: }
                   3255: 
                   3256: ###################################################
                   3257: 
                   3258: =pod
                   3259: 
1.648     raeburn  3260: =item * &keyword($word)
1.46      matthew  3261: 
                   3262: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3263: than the average number of times in the thesaurus database.  Calls 
                   3264: &initialize_keywords
                   3265: 
                   3266: =cut
                   3267: 
                   3268: ###################################################
1.20      www      3269: 
                   3270: sub keyword {
1.46      matthew  3271:     return if (!&initialize_keywords());
                   3272:     my $word=lc(shift());
                   3273:     $word=~s/\W//g;
                   3274:     return exists($Keywords{$word});
1.20      www      3275: }
1.46      matthew  3276: 
                   3277: ###############################################################
                   3278: 
                   3279: =pod 
1.20      www      3280: 
1.648     raeburn  3281: =item * &get_related_words()
1.46      matthew  3282: 
1.160     matthew  3283: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3284: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3285: will be returned.  The order of the words returned is determined by the
                   3286: database which holds them.
                   3287: 
                   3288: Uses global $thesaurus_db_file.
                   3289: 
1.1057    foxr     3290: 
1.46      matthew  3291: =cut
                   3292: 
                   3293: ###############################################################
                   3294: sub get_related_words {
                   3295:     my $keyword = shift;
                   3296:     my %thesaurus_db;
                   3297:     if (! -e $thesaurus_db_file) {
                   3298:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3299:                                  "failed because the file does not exist");
                   3300:         return ();
                   3301:     }
                   3302:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3303:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3304:         return ();
                   3305:     } 
                   3306:     my @Words=();
1.429     www      3307:     my $count=0;
1.46      matthew  3308:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3309: 	# The first element is the number of times
                   3310: 	# the word appears.  We do not need it now.
1.429     www      3311: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3312: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3313: 	my $threshold=$mostfrequentcount/10;
                   3314:         foreach my $possibleword (@RelatedWords) {
                   3315:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3316:             if ($wordcount>$threshold) {
                   3317: 		push(@Words,$word);
                   3318:                 $count++;
                   3319:                 if ($count>10) { last; }
                   3320: 	    }
1.20      www      3321:         }
                   3322:     }
1.46      matthew  3323:     untie %thesaurus_db;
                   3324:     return @Words;
1.14      harris41 3325: }
1.1090    foxr     3326: ###############################################################
                   3327: #
                   3328: #  Spell checking
                   3329: #
                   3330: 
                   3331: =pod
                   3332: 
1.1142    raeburn  3333: =back
                   3334: 
1.1090    foxr     3335: =head1 Spell checking
                   3336: 
                   3337: =over 4
                   3338: 
                   3339: =item * &check_spelling($wordlist $language)
                   3340: 
                   3341: Takes a string containing words and feeds it to an external
                   3342: spellcheck program via a pipeline. Returns a string containing
                   3343: them mis-spelled words.
                   3344: 
                   3345: Parameters:
                   3346: 
                   3347: =over 4
                   3348: 
                   3349: =item - $wordlist
                   3350: 
                   3351: String that will be fed into the spellcheck program.
                   3352: 
                   3353: =item - $language
                   3354: 
                   3355: Language string that specifies the language for which the spell
                   3356: check will be performed.
                   3357: 
                   3358: =back
                   3359: 
                   3360: =back
                   3361: 
                   3362: Note: This sub assumes that aspell is installed.
                   3363: 
                   3364: 
                   3365: =cut
                   3366: 
1.46      matthew  3367: 
1.1090    foxr     3368: sub check_spelling {
                   3369:     my ($wordlist, $language) = @_;
1.1091    foxr     3370:     my @misspellings;
                   3371:     
                   3372:     # Generate the speller and set the langauge.
                   3373:     # if explicitly selected:
1.1090    foxr     3374: 
1.1091    foxr     3375:     my $speller = Text::Aspell->new;
1.1090    foxr     3376:     if ($language) {
1.1091    foxr     3377: 	$speller->set_option('lang', $language);
1.1090    foxr     3378:     }
                   3379: 
1.1091    foxr     3380:     # Turn the word list into an array of words by splittingon whitespace
1.1090    foxr     3381: 
1.1091    foxr     3382:     my @words = split(/\s+/, $wordlist);
1.1090    foxr     3383: 
1.1091    foxr     3384:     foreach my $word (@words) {
                   3385: 	if(! $speller->check($word)) {
                   3386: 	    push(@misspellings, $word);
1.1090    foxr     3387: 	}
                   3388:     }
1.1091    foxr     3389:     return join(' ', @misspellings);
                   3390:     
1.1090    foxr     3391: }
                   3392: 
1.61      www      3393: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3394: =pod
                   3395: 
1.112     bowersj2 3396: =head1 User Name Functions
                   3397: 
                   3398: =over 4
                   3399: 
1.648     raeburn  3400: =item * &plainname($uname,$udom,$first)
1.81      albertel 3401: 
1.112     bowersj2 3402: Takes a users logon name and returns it as a string in
1.226     albertel 3403: "first middle last generation" form 
                   3404: if $first is set to 'lastname' then it returns it as
                   3405: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3406: 
                   3407: =cut
1.61      www      3408: 
1.295     www      3409: 
1.81      albertel 3410: ###############################################################
1.61      www      3411: sub plainname {
1.226     albertel 3412:     my ($uname,$udom,$first)=@_;
1.537     albertel 3413:     return if (!defined($uname) || !defined($udom));
1.295     www      3414:     my %names=&getnames($uname,$udom);
1.226     albertel 3415:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3416: 					  $names{'middlename'},
                   3417: 					  $names{'lastname'},
                   3418: 					  $names{'generation'},$first);
                   3419:     $name=~s/^\s+//;
1.62      www      3420:     $name=~s/\s+$//;
                   3421:     $name=~s/\s+/ /g;
1.353     albertel 3422:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3423:     return $name;
1.61      www      3424: }
1.66      www      3425: 
                   3426: # -------------------------------------------------------------------- Nickname
1.81      albertel 3427: =pod
                   3428: 
1.648     raeburn  3429: =item * &nickname($uname,$udom)
1.81      albertel 3430: 
                   3431: Gets a users name and returns it as a string as
                   3432: 
                   3433: "&quot;nickname&quot;"
1.66      www      3434: 
1.81      albertel 3435: if the user has a nickname or
                   3436: 
                   3437: "first middle last generation"
                   3438: 
                   3439: if the user does not
                   3440: 
                   3441: =cut
1.66      www      3442: 
                   3443: sub nickname {
                   3444:     my ($uname,$udom)=@_;
1.537     albertel 3445:     return if (!defined($uname) || !defined($udom));
1.295     www      3446:     my %names=&getnames($uname,$udom);
1.68      albertel 3447:     my $name=$names{'nickname'};
1.66      www      3448:     if ($name) {
                   3449:        $name='&quot;'.$name.'&quot;'; 
                   3450:     } else {
                   3451:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3452: 	     $names{'lastname'}.' '.$names{'generation'};
                   3453:        $name=~s/\s+$//;
                   3454:        $name=~s/\s+/ /g;
                   3455:     }
                   3456:     return $name;
                   3457: }
                   3458: 
1.295     www      3459: sub getnames {
                   3460:     my ($uname,$udom)=@_;
1.537     albertel 3461:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3462:     if ($udom eq 'public' && $uname eq 'public') {
                   3463: 	return ('lastname' => &mt('Public'));
                   3464:     }
1.295     www      3465:     my $id=$uname.':'.$udom;
                   3466:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3467:     if ($cached) {
                   3468: 	return %{$names};
                   3469:     } else {
                   3470: 	my %loadnames=&Apache::lonnet::get('environment',
                   3471:                     ['firstname','middlename','lastname','generation','nickname'],
                   3472: 					 $udom,$uname);
                   3473: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3474: 	return %loadnames;
                   3475:     }
                   3476: }
1.61      www      3477: 
1.542     raeburn  3478: # -------------------------------------------------------------------- getemails
1.648     raeburn  3479: 
1.542     raeburn  3480: =pod
                   3481: 
1.648     raeburn  3482: =item * &getemails($uname,$udom)
1.542     raeburn  3483: 
                   3484: Gets a user's email information and returns it as a hash with keys:
                   3485: notification, critnotification, permanentemail
                   3486: 
                   3487: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3488: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3489:  
1.648     raeburn  3490: 
1.542     raeburn  3491: =cut
                   3492: 
1.648     raeburn  3493: 
1.466     albertel 3494: sub getemails {
                   3495:     my ($uname,$udom)=@_;
                   3496:     if ($udom eq 'public' && $uname eq 'public') {
                   3497: 	return;
                   3498:     }
1.467     www      3499:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3500:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3501:     my $id=$uname.':'.$udom;
                   3502:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3503:     if ($cached) {
                   3504: 	return %{$names};
                   3505:     } else {
                   3506: 	my %loadnames=&Apache::lonnet::get('environment',
                   3507:                     			   ['notification','critnotification',
                   3508: 					    'permanentemail'],
                   3509: 					   $udom,$uname);
                   3510: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3511: 	return %loadnames;
                   3512:     }
                   3513: }
                   3514: 
1.551     albertel 3515: sub flush_email_cache {
                   3516:     my ($uname,$udom)=@_;
                   3517:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3518:     if (!$uname) { $uname=$env{'user.name'};   }
                   3519:     return if ($udom eq 'public' && $uname eq 'public');
                   3520:     my $id=$uname.':'.$udom;
                   3521:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3522: }
                   3523: 
1.728     raeburn  3524: # -------------------------------------------------------------------- getlangs
                   3525: 
                   3526: =pod
                   3527: 
                   3528: =item * &getlangs($uname,$udom)
                   3529: 
                   3530: Gets a user's language preference and returns it as a hash with key:
                   3531: language.
                   3532: 
                   3533: =cut
                   3534: 
                   3535: 
                   3536: sub getlangs {
                   3537:     my ($uname,$udom) = @_;
                   3538:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3539:     if (!$uname) { $uname=$env{'user.name'};   }
                   3540:     my $id=$uname.':'.$udom;
                   3541:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3542:     if ($cached) {
                   3543:         return %{$langs};
                   3544:     } else {
                   3545:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3546:                                            $udom,$uname);
                   3547:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3548:         return %loadlangs;
                   3549:     }
                   3550: }
                   3551: 
                   3552: sub flush_langs_cache {
                   3553:     my ($uname,$udom)=@_;
                   3554:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3555:     if (!$uname) { $uname=$env{'user.name'};   }
                   3556:     return if ($udom eq 'public' && $uname eq 'public');
                   3557:     my $id=$uname.':'.$udom;
                   3558:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3559: }
                   3560: 
1.61      www      3561: # ------------------------------------------------------------------ Screenname
1.81      albertel 3562: 
                   3563: =pod
                   3564: 
1.648     raeburn  3565: =item * &screenname($uname,$udom)
1.81      albertel 3566: 
                   3567: Gets a users screenname and returns it as a string
                   3568: 
                   3569: =cut
1.61      www      3570: 
                   3571: sub screenname {
                   3572:     my ($uname,$udom)=@_;
1.258     albertel 3573:     if ($uname eq $env{'user.name'} &&
                   3574: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3575:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3576:     return $names{'screenname'};
1.62      www      3577: }
                   3578: 
1.212     albertel 3579: 
1.802     bisitz   3580: # ------------------------------------------------------------- Confirm Wrapper
                   3581: =pod
                   3582: 
1.1142    raeburn  3583: =item * &confirmwrapper($message)
1.802     bisitz   3584: 
                   3585: Wrap messages about completion of operation in box
                   3586: 
                   3587: =cut
                   3588: 
                   3589: sub confirmwrapper {
                   3590:     my ($message)=@_;
                   3591:     if ($message) {
                   3592:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3593:                .$message."\n"
                   3594:                .'</div>'."\n";
                   3595:     } else {
                   3596:         return $message;
                   3597:     }
                   3598: }
                   3599: 
1.62      www      3600: # ------------------------------------------------------------- Message Wrapper
                   3601: 
                   3602: sub messagewrapper {
1.369     www      3603:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3604:     return 
1.441     albertel 3605:         '<a href="/adm/email?compose=individual&amp;'.
                   3606:         'recname='.$username.'&amp;recdom='.$domain.
                   3607: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3608:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3609: }
1.802     bisitz   3610: 
1.74      www      3611: # --------------------------------------------------------------- Notes Wrapper
                   3612: 
                   3613: sub noteswrapper {
                   3614:     my ($link,$un,$do)=@_;
                   3615:     return 
1.896     amueller 3616: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3617: }
1.802     bisitz   3618: 
1.62      www      3619: # ------------------------------------------------------------- Aboutme Wrapper
                   3620: 
                   3621: sub aboutmewrapper {
1.1070    raeburn  3622:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3623:     if (!defined($username)  && !defined($domain)) {
                   3624:         return;
                   3625:     }
1.1096    raeburn  3626:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3627: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3628: }
                   3629: 
                   3630: # ------------------------------------------------------------ Syllabus Wrapper
                   3631: 
                   3632: sub syllabuswrapper {
1.707     bisitz   3633:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3634:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3635: }
1.14      harris41 3636: 
1.802     bisitz   3637: # -----------------------------------------------------------------------------
                   3638: 
1.208     matthew  3639: sub track_student_link {
1.887     raeburn  3640:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3641:     my $link ="/adm/trackstudent?";
1.208     matthew  3642:     my $title = 'View recent activity';
                   3643:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3644:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3645:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3646:         $title .= ' of this student';
1.268     albertel 3647:     } 
1.208     matthew  3648:     if (defined($target) && $target !~ /^\s*$/) {
                   3649:         $target = qq{target="$target"};
                   3650:     } else {
                   3651:         $target = '';
                   3652:     }
1.268     albertel 3653:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3654:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3655:     $title = &mt($title);
                   3656:     $linktext = &mt($linktext);
1.448     albertel 3657:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3658: 	&help_open_topic('View_recent_activity');
1.208     matthew  3659: }
                   3660: 
1.781     raeburn  3661: sub slot_reservations_link {
                   3662:     my ($linktext,$sname,$sdom,$target) = @_;
                   3663:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3664:     my $title = 'View slot reservation history';
                   3665:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3666:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3667:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3668:         $title .= ' of this student';
                   3669:     }
                   3670:     if (defined($target) && $target !~ /^\s*$/) {
                   3671:         $target = qq{target="$target"};
                   3672:     } else {
                   3673:         $target = '';
                   3674:     }
                   3675:     $title = &mt($title);
                   3676:     $linktext = &mt($linktext);
                   3677:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3678: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3679: 
                   3680: }
                   3681: 
1.508     www      3682: # ===================================================== Display a student photo
                   3683: 
                   3684: 
1.509     albertel 3685: sub student_image_tag {
1.508     www      3686:     my ($domain,$user)=@_;
                   3687:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3688:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3689: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3690:     } else {
                   3691: 	return '';
                   3692:     }
                   3693: }
                   3694: 
1.112     bowersj2 3695: =pod
                   3696: 
                   3697: =back
                   3698: 
                   3699: =head1 Access .tab File Data
                   3700: 
                   3701: =over 4
                   3702: 
1.648     raeburn  3703: =item * &languageids() 
1.112     bowersj2 3704: 
                   3705: returns list of all language ids
                   3706: 
                   3707: =cut
                   3708: 
1.14      harris41 3709: sub languageids {
1.16      harris41 3710:     return sort(keys(%language));
1.14      harris41 3711: }
                   3712: 
1.112     bowersj2 3713: =pod
                   3714: 
1.648     raeburn  3715: =item * &languagedescription() 
1.112     bowersj2 3716: 
                   3717: returns description of a specified language id
                   3718: 
                   3719: =cut
                   3720: 
1.14      harris41 3721: sub languagedescription {
1.125     www      3722:     my $code=shift;
                   3723:     return  ($supported_language{$code}?'* ':'').
                   3724:             $language{$code}.
1.126     www      3725: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3726: }
                   3727: 
1.1048    foxr     3728: =pod
                   3729: 
                   3730: =item * &plainlanguagedescription
                   3731: 
                   3732: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3733: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3734: 
                   3735: =cut
                   3736: 
1.145     www      3737: sub plainlanguagedescription {
                   3738:     my $code=shift;
                   3739:     return $language{$code};
                   3740: }
                   3741: 
1.1048    foxr     3742: =pod
                   3743: 
                   3744: =item * &supportedlanguagecode
                   3745: 
                   3746: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3747: code.
                   3748: 
                   3749: =cut
                   3750: 
1.145     www      3751: sub supportedlanguagecode {
                   3752:     my $code=shift;
                   3753:     return $supported_language{$code};
1.97      www      3754: }
                   3755: 
1.112     bowersj2 3756: =pod
                   3757: 
1.1048    foxr     3758: =item * &latexlanguage()
                   3759: 
                   3760: Given a language key code returns the correspondnig language to use
                   3761: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3762: is no supported hyphenation for the language code.
                   3763: 
                   3764: =cut
                   3765: 
                   3766: sub latexlanguage {
                   3767:     my $code = shift;
                   3768:     return $latex_language{$code};
                   3769: }
                   3770: 
                   3771: =pod
                   3772: 
                   3773: =item * &latexhyphenation()
                   3774: 
                   3775: Same as above but what's supplied is the language as it might be stored
                   3776: in the metadata.
                   3777: 
                   3778: =cut
                   3779: 
                   3780: sub latexhyphenation {
                   3781:     my $key = shift;
                   3782:     return $latex_language_bykey{$key};
                   3783: }
                   3784: 
                   3785: =pod
                   3786: 
1.648     raeburn  3787: =item * &copyrightids() 
1.112     bowersj2 3788: 
                   3789: returns list of all copyrights
                   3790: 
                   3791: =cut
                   3792: 
                   3793: sub copyrightids {
                   3794:     return sort(keys(%cprtag));
                   3795: }
                   3796: 
                   3797: =pod
                   3798: 
1.648     raeburn  3799: =item * &copyrightdescription() 
1.112     bowersj2 3800: 
                   3801: returns description of a specified copyright id
                   3802: 
                   3803: =cut
                   3804: 
                   3805: sub copyrightdescription {
1.166     www      3806:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3807: }
1.197     matthew  3808: 
                   3809: =pod
                   3810: 
1.648     raeburn  3811: =item * &source_copyrightids() 
1.192     taceyjo1 3812: 
                   3813: returns list of all source copyrights
                   3814: 
                   3815: =cut
                   3816: 
                   3817: sub source_copyrightids {
                   3818:     return sort(keys(%scprtag));
                   3819: }
                   3820: 
                   3821: =pod
                   3822: 
1.648     raeburn  3823: =item * &source_copyrightdescription() 
1.192     taceyjo1 3824: 
                   3825: returns description of a specified source copyright id
                   3826: 
                   3827: =cut
                   3828: 
                   3829: sub source_copyrightdescription {
                   3830:     return &mt($scprtag{shift(@_)});
                   3831: }
1.112     bowersj2 3832: 
                   3833: =pod
                   3834: 
1.648     raeburn  3835: =item * &filecategories() 
1.112     bowersj2 3836: 
                   3837: returns list of all file categories
                   3838: 
                   3839: =cut
                   3840: 
                   3841: sub filecategories {
                   3842:     return sort(keys(%category_extensions));
                   3843: }
                   3844: 
                   3845: =pod
                   3846: 
1.648     raeburn  3847: =item * &filecategorytypes() 
1.112     bowersj2 3848: 
                   3849: returns list of file types belonging to a given file
                   3850: category
                   3851: 
                   3852: =cut
                   3853: 
                   3854: sub filecategorytypes {
1.356     albertel 3855:     my ($cat) = @_;
                   3856:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3857: }
                   3858: 
                   3859: =pod
                   3860: 
1.648     raeburn  3861: =item * &fileembstyle() 
1.112     bowersj2 3862: 
                   3863: returns embedding style for a specified file type
                   3864: 
                   3865: =cut
                   3866: 
                   3867: sub fileembstyle {
                   3868:     return $fe{lc(shift(@_))};
1.169     www      3869: }
                   3870: 
1.351     www      3871: sub filemimetype {
                   3872:     return $fm{lc(shift(@_))};
                   3873: }
                   3874: 
1.169     www      3875: 
                   3876: sub filecategoryselect {
                   3877:     my ($name,$value)=@_;
1.189     matthew  3878:     return &select_form($value,$name,
1.970     raeburn  3879:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3880: }
                   3881: 
                   3882: =pod
                   3883: 
1.648     raeburn  3884: =item * &filedescription() 
1.112     bowersj2 3885: 
                   3886: returns description for a specified file type
                   3887: 
                   3888: =cut
                   3889: 
                   3890: sub filedescription {
1.188     matthew  3891:     my $file_description = $fd{lc(shift())};
                   3892:     $file_description =~ s:([\[\]]):~$1:g;
                   3893:     return &mt($file_description);
1.112     bowersj2 3894: }
                   3895: 
                   3896: =pod
                   3897: 
1.648     raeburn  3898: =item * &filedescriptionex() 
1.112     bowersj2 3899: 
                   3900: returns description for a specified file type with
                   3901: extra formatting
                   3902: 
                   3903: =cut
                   3904: 
                   3905: sub filedescriptionex {
                   3906:     my $ex=shift;
1.188     matthew  3907:     my $file_description = $fd{lc($ex)};
                   3908:     $file_description =~ s:([\[\]]):~$1:g;
                   3909:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3910: }
                   3911: 
                   3912: # End of .tab access
                   3913: =pod
                   3914: 
                   3915: =back
                   3916: 
                   3917: =cut
                   3918: 
                   3919: # ------------------------------------------------------------------ File Types
                   3920: sub fileextensions {
                   3921:     return sort(keys(%fe));
                   3922: }
                   3923: 
1.97      www      3924: # ----------------------------------------------------------- Display Languages
                   3925: # returns a hash with all desired display languages
                   3926: #
                   3927: 
                   3928: sub display_languages {
                   3929:     my %languages=();
1.695     raeburn  3930:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3931: 	$languages{$lang}=1;
1.97      www      3932:     }
                   3933:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3934:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3935: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3936: 	    $languages{$lang}=1;
1.97      www      3937:         }
                   3938:     }
                   3939:     return %languages;
1.14      harris41 3940: }
                   3941: 
1.582     albertel 3942: sub languages {
                   3943:     my ($possible_langs) = @_;
1.695     raeburn  3944:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3945:     if (!ref($possible_langs)) {
                   3946: 	if( wantarray ) {
                   3947: 	    return @preferred_langs;
                   3948: 	} else {
                   3949: 	    return $preferred_langs[0];
                   3950: 	}
                   3951:     }
                   3952:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3953:     my @preferred_possibilities;
                   3954:     foreach my $preferred_lang (@preferred_langs) {
                   3955: 	if (exists($possibilities{$preferred_lang})) {
                   3956: 	    push(@preferred_possibilities, $preferred_lang);
                   3957: 	}
                   3958:     }
                   3959:     if( wantarray ) {
                   3960: 	return @preferred_possibilities;
                   3961:     }
                   3962:     return $preferred_possibilities[0];
                   3963: }
                   3964: 
1.742     raeburn  3965: sub user_lang {
                   3966:     my ($touname,$toudom,$fromcid) = @_;
                   3967:     my @userlangs;
                   3968:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3969:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3970:                     $env{'course.'.$fromcid.'.languages'}));
                   3971:     } else {
                   3972:         my %langhash = &getlangs($touname,$toudom);
                   3973:         if ($langhash{'languages'} ne '') {
                   3974:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3975:         } else {
                   3976:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3977:             if ($domdefs{'lang_def'} ne '') {
                   3978:                 @userlangs = ($domdefs{'lang_def'});
                   3979:             }
                   3980:         }
                   3981:     }
                   3982:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3983:     my $user_lh = Apache::localize->get_handle(@languages);
                   3984:     return $user_lh;
                   3985: }
                   3986: 
                   3987: 
1.112     bowersj2 3988: ###############################################################
                   3989: ##               Student Answer Attempts                     ##
                   3990: ###############################################################
                   3991: 
                   3992: =pod
                   3993: 
                   3994: =head1 Alternate Problem Views
                   3995: 
                   3996: =over 4
                   3997: 
1.648     raeburn  3998: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1199    raeburn  3999:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 4000: 
                   4001: Return string with previous attempt on problem. Arguments:
                   4002: 
                   4003: =over 4
                   4004: 
                   4005: =item * $symb: Problem, including path
                   4006: 
                   4007: =item * $username: username of the desired student
                   4008: 
                   4009: =item * $domain: domain of the desired student
1.14      harris41 4010: 
1.112     bowersj2 4011: =item * $course: Course ID
1.14      harris41 4012: 
1.112     bowersj2 4013: =item * $getattempt: Leave blank for all attempts, otherwise put
                   4014:     something
1.14      harris41 4015: 
1.112     bowersj2 4016: =item * $regexp: if string matches this regexp, the string will be
                   4017:     sent to $gradesub
1.14      harris41 4018: 
1.112     bowersj2 4019: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 4020: 
1.1199    raeburn  4021: =item * $usec: section of the desired student
                   4022: 
                   4023: =item * $identifier: counter for student (multiple students one problem) or 
                   4024:     problem (one student; whole sequence).
                   4025: 
1.112     bowersj2 4026: =back
1.14      harris41 4027: 
1.112     bowersj2 4028: The output string is a table containing all desired attempts, if any.
1.16      harris41 4029: 
1.112     bowersj2 4030: =cut
1.1       albertel 4031: 
                   4032: sub get_previous_attempt {
1.1199    raeburn  4033:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 4034:   my $prevattempts='';
1.43      ng       4035:   no strict 'refs';
1.1       albertel 4036:   if ($symb) {
1.3       albertel 4037:     my (%returnhash)=
                   4038:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 4039:     if ($returnhash{'version'}) {
                   4040:       my %lasthash=();
                   4041:       my $version;
                   4042:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1212    raeburn  4043:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   4044:             if ($key =~ /\.rawrndseed$/) {
                   4045:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4046:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4047:             } else {
                   4048:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4049:             }
1.19      harris41 4050:         }
1.1       albertel 4051:       }
1.596     albertel 4052:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4053:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1199    raeburn  4054:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4055:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4056:       foreach my $key (sort(keys(%lasthash))) {
                   4057: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4058: 	if ($#parts > 0) {
1.31      albertel 4059: 	  my $data=$parts[-1];
1.989     raeburn  4060:           next if ($data eq 'foilorder');
1.31      albertel 4061: 	  pop(@parts);
1.1010    www      4062:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4063:           if ($data eq 'type') {
                   4064:               unless ($showsurv) {
                   4065:                   my $id = join(',',@parts);
                   4066:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4067:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4068:                       $lasthidden{$ign.'.'.$id} = 1;
                   4069:                   }
1.945     raeburn  4070:               }
1.1199    raeburn  4071:               if ($identifier ne '') {
                   4072:                   my $id = join(',',@parts);
                   4073:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4074:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4075:                       $hidestatus{$ign.'.'.$id} = 1;
                   4076:                   }
                   4077:               }
                   4078:           } elsif ($data eq 'regrader') {
                   4079:               if (($identifier ne '') && (@parts)) {
1.1200    raeburn  4080:                   my $id = join(',',@parts);
                   4081:                   $regraded{$ign.'.'.$id} = 1;
1.1199    raeburn  4082:               }
1.1010    www      4083:           } 
1.31      albertel 4084: 	} else {
1.41      ng       4085: 	  if ($#parts == 0) {
                   4086: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4087: 	  } else {
                   4088: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4089: 	  }
1.31      albertel 4090: 	}
1.16      harris41 4091:       }
1.596     albertel 4092:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4093:       if ($getattempt eq '') {
1.1199    raeburn  4094:         my (%solved,%resets,%probstatus);
1.1200    raeburn  4095:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4096:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4097:                 foreach my $id (keys(%regraded)) {
                   4098:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4099:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4100:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4101:                         push(@{$resets{$id}},$version);
1.1199    raeburn  4102:                     }
                   4103:                 }
                   4104:             }
1.1200    raeburn  4105:         }
                   4106: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1199    raeburn  4107:             my (@hidden,@unsolved);
1.945     raeburn  4108:             if (%typeparts) {
                   4109:                 foreach my $id (keys(%typeparts)) {
1.1199    raeburn  4110:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') || 
                   4111:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4112:                         push(@hidden,$id);
1.1199    raeburn  4113:                     } elsif ($identifier ne '') {
                   4114:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4115:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4116:                                 ($hidestatus{$id})) {
1.1200    raeburn  4117:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
1.1199    raeburn  4118:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4119:                                 push(@{$solved{$id}},$version);
                   4120:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4121:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4122:                                 my $skip;
                   4123:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4124:                                     foreach my $reset (@{$resets{$id}}) {
                   4125:                                         if ($reset > $solved{$id}[-1]) {
                   4126:                                             $skip=1;
                   4127:                                             last;
                   4128:                                         }
                   4129:                                     }
                   4130:                                 }
                   4131:                                 unless ($skip) {
                   4132:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4133:                                     push(@unsolved,$partslist);
                   4134:                                 }
                   4135:                             }
                   4136:                         }
1.945     raeburn  4137:                     }
                   4138:                 }
                   4139:             }
                   4140:             $prevattempts.=&start_data_table_row().
1.1199    raeburn  4141:                            '<td>'.&mt('Transaction [_1]',$version);
                   4142:             if (@unsolved) {
                   4143:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4144:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4145:                                  &mt('Hide').'</label></span>';
                   4146:             }
                   4147:             $prevattempts .= '</td>';
1.945     raeburn  4148:             if (@hidden) {
                   4149:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4150:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4151:                     my $hide;
                   4152:                     foreach my $id (@hidden) {
                   4153:                         if ($key =~ /^\Q$id\E/) {
                   4154:                             $hide = 1;
                   4155:                             last;
                   4156:                         }
                   4157:                     }
                   4158:                     if ($hide) {
                   4159:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4160:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4161:                             my $value = &format_previous_attempt_value($key,
                   4162:                                              $returnhash{$version.':'.$key});
1.1173    kruse    4163:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4164:                         } else {
                   4165:                             $prevattempts.='<td>&nbsp;</td>';
                   4166:                         }
                   4167:                     } else {
                   4168:                         if ($key =~ /\./) {
1.1212    raeburn  4169:                             my $value = $returnhash{$version.':'.$key};
                   4170:                             if ($key =~ /\.rndseed$/) {
                   4171:                                 my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4172:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4173:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4174:                                 }
                   4175:                             }
                   4176:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4177:                                            '&nbsp;</td>';
1.945     raeburn  4178:                         } else {
                   4179:                             $prevattempts.='<td>&nbsp;</td>';
                   4180:                         }
                   4181:                     }
                   4182:                 }
                   4183:             } else {
                   4184: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4185:                     next if ($key =~ /\.foilorder$/);
1.1212    raeburn  4186:                     my $value = $returnhash{$version.':'.$key};
                   4187:                     if ($key =~ /\.rndseed$/) {
                   4188:                         my ($id) = ($key =~ /^(.+)\.[^.]+$/);
                   4189:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4190:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4191:                         }
                   4192:                     }
                   4193:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4194:                                    '&nbsp;</td>';
1.945     raeburn  4195: 	        }
                   4196:             }
                   4197: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4198: 	 }
1.1       albertel 4199:       }
1.945     raeburn  4200:       my @currhidden = keys(%lasthidden);
1.596     albertel 4201:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4202:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4203:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4204:           if (%typeparts) {
                   4205:               my $hidden;
                   4206:               foreach my $id (@currhidden) {
                   4207:                   if ($key =~ /^\Q$id\E/) {
                   4208:                       $hidden = 1;
                   4209:                       last;
                   4210:                   }
                   4211:               }
                   4212:               if ($hidden) {
                   4213:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4214:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4215:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4216:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4217:                           $value = &$gradesub($value);
                   4218:                       }
1.1173    kruse    4219:                       $prevattempts.='<td>'. $value.'&nbsp;</td>';
1.945     raeburn  4220:                   } else {
                   4221:                       $prevattempts.='<td>&nbsp;</td>';
                   4222:                   }
                   4223:               } else {
                   4224:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4225:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4226:                       $value = &$gradesub($value);
                   4227:                   }
1.1173    kruse    4228:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4229:               }
                   4230:           } else {
                   4231: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4232: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4233:                   $value = &$gradesub($value);
                   4234:               }
1.1173    kruse    4235: 	     $prevattempts.='<td>'.$value.'&nbsp;</td>';
1.945     raeburn  4236:           }
1.16      harris41 4237:       }
1.596     albertel 4238:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4239:     } else {
1.596     albertel 4240:       $prevattempts=
                   4241: 	  &start_data_table().&start_data_table_row().
                   4242: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4243: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4244:     }
                   4245:   } else {
1.596     albertel 4246:     $prevattempts=
                   4247: 	  &start_data_table().&start_data_table_row().
                   4248: 	  '<td>'.&mt('No data.').'</td>'.
                   4249: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4250:   }
1.10      albertel 4251: }
                   4252: 
1.581     albertel 4253: sub format_previous_attempt_value {
                   4254:     my ($key,$value) = @_;
1.1011    www      4255:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.1173    kruse    4256:         $value = &Apache::lonlocal::locallocaltime($value);
1.581     albertel 4257:     } elsif (ref($value) eq 'ARRAY') {
1.1173    kruse    4258:         $value = &HTML::Entities::encode('('.join(', ', @{ $value }).')','"<>&');
1.988     raeburn  4259:     } elsif ($key =~ /answerstring$/) {
                   4260:         my %answers = &Apache::lonnet::str2hash($value);
1.1173    kruse    4261:         my @answer = %answers;
                   4262:         %answers = map {&HTML::Entities::encode($_, '"<>&')} @answer;
1.988     raeburn  4263:         my @anskeys = sort(keys(%answers));
                   4264:         if (@anskeys == 1) {
                   4265:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4266:             if ($answer =~ m{\0}) {
                   4267:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4268:             }
                   4269:             my $tag_internal_answer_name = 'INTERNAL';
                   4270:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4271:                 $value = $answer; 
                   4272:             } else {
                   4273:                 $value = $anskeys[0].'='.$answer;
                   4274:             }
                   4275:         } else {
                   4276:             foreach my $ans (@anskeys) {
                   4277:                 my $answer = $answers{$ans};
1.1001    raeburn  4278:                 if ($answer =~ m{\0}) {
                   4279:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4280:                 }
                   4281:                 $value .=  $ans.'='.$answer.'<br />';;
                   4282:             } 
                   4283:         }
1.581     albertel 4284:     } else {
1.1173    kruse    4285:         $value = &HTML::Entities::encode(&unescape($value), '"<>&');
1.581     albertel 4286:     }
                   4287:     return $value;
                   4288: }
                   4289: 
                   4290: 
1.107     albertel 4291: sub relative_to_absolute {
                   4292:     my ($url,$output)=@_;
                   4293:     my $parser=HTML::TokeParser->new(\$output);
                   4294:     my $token;
                   4295:     my $thisdir=$url;
                   4296:     my @rlinks=();
                   4297:     while ($token=$parser->get_token) {
                   4298: 	if ($token->[0] eq 'S') {
                   4299: 	    if ($token->[1] eq 'a') {
                   4300: 		if ($token->[2]->{'href'}) {
                   4301: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4302: 		}
                   4303: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4304: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4305: 	    } elsif ($token->[1] eq 'base') {
                   4306: 		$thisdir=$token->[2]->{'href'};
                   4307: 	    }
                   4308: 	}
                   4309:     }
                   4310:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4311:     foreach my $link (@rlinks) {
1.726     raeburn  4312: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4313: 		($link=~/^\//) ||
                   4314: 		($link=~/^javascript:/i) ||
                   4315: 		($link=~/^mailto:/i) ||
                   4316: 		($link=~/^\#/)) {
                   4317: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4318: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4319: 	}
                   4320:     }
                   4321: # -------------------------------------------------- Deal with Applet codebases
                   4322:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4323:     return $output;
                   4324: }
                   4325: 
1.112     bowersj2 4326: =pod
                   4327: 
1.648     raeburn  4328: =item * &get_student_view()
1.112     bowersj2 4329: 
                   4330: show a snapshot of what student was looking at
                   4331: 
                   4332: =cut
                   4333: 
1.10      albertel 4334: sub get_student_view {
1.186     albertel 4335:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4336:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4337:   my (%form);
1.10      albertel 4338:   my @elements=('symb','courseid','domain','username');
                   4339:   foreach my $element (@elements) {
1.186     albertel 4340:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4341:   }
1.186     albertel 4342:   if (defined($moreenv)) {
                   4343:       %form=(%form,%{$moreenv});
                   4344:   }
1.236     albertel 4345:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4346:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4347:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4348:   $userview=~s/\<body[^\>]*\>//gi;
                   4349:   $userview=~s/\<\/body\>//gi;
                   4350:   $userview=~s/\<html\>//gi;
                   4351:   $userview=~s/\<\/html\>//gi;
                   4352:   $userview=~s/\<head\>//gi;
                   4353:   $userview=~s/\<\/head\>//gi;
                   4354:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4355:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4356:   if (wantarray) {
                   4357:      return ($userview,$response);
                   4358:   } else {
                   4359:      return $userview;
                   4360:   }
                   4361: }
                   4362: 
                   4363: sub get_student_view_with_retries {
                   4364:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4365: 
                   4366:     my $ok = 0;                 # True if we got a good response.
                   4367:     my $content;
                   4368:     my $response;
                   4369: 
                   4370:     # Try to get the student_view done. within the retries count:
                   4371:     
                   4372:     do {
                   4373:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4374:          $ok      = $response->is_success;
                   4375:          if (!$ok) {
                   4376:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4377:          }
                   4378:          $retries--;
                   4379:     } while (!$ok && ($retries > 0));
                   4380:     
                   4381:     if (!$ok) {
                   4382:        $content = '';          # On error return an empty content.
                   4383:     }
1.651     www      4384:     if (wantarray) {
                   4385:        return ($content, $response);
                   4386:     } else {
                   4387:        return $content;
                   4388:     }
1.11      albertel 4389: }
                   4390: 
1.112     bowersj2 4391: =pod
                   4392: 
1.648     raeburn  4393: =item * &get_student_answers() 
1.112     bowersj2 4394: 
                   4395: show a snapshot of how student was answering problem
                   4396: 
                   4397: =cut
                   4398: 
1.11      albertel 4399: sub get_student_answers {
1.100     sakharuk 4400:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4401:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4402:   my (%moreenv);
1.11      albertel 4403:   my @elements=('symb','courseid','domain','username');
                   4404:   foreach my $element (@elements) {
1.186     albertel 4405:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4406:   }
1.186     albertel 4407:   $moreenv{'grade_target'}='answer';
                   4408:   %moreenv=(%form,%moreenv);
1.497     raeburn  4409:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4410:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4411:   return $userview;
1.1       albertel 4412: }
1.116     albertel 4413: 
                   4414: =pod
                   4415: 
                   4416: =item * &submlink()
                   4417: 
1.242     albertel 4418: Inputs: $text $uname $udom $symb $target
1.116     albertel 4419: 
                   4420: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4421: 
                   4422: =cut
                   4423: 
                   4424: ###############################################
                   4425: sub submlink {
1.242     albertel 4426:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4427:     if (!($uname && $udom)) {
                   4428: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4429: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4430: 	if (!$symb) { $symb=$cursymb; }
                   4431:     }
1.254     matthew  4432:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4433:     $symb=&escape($symb);
1.960     bisitz   4434:     if ($target) { $target=" target=\"$target\""; }
                   4435:     return
                   4436:         '<a href="/adm/grades?command=submission'.
                   4437:         '&amp;symb='.$symb.
                   4438:         '&amp;student='.$uname.
                   4439:         '&amp;userdom='.$udom.'"'.
                   4440:         $target.'>'.$text.'</a>';
1.242     albertel 4441: }
                   4442: ##############################################
                   4443: 
                   4444: =pod
                   4445: 
                   4446: =item * &pgrdlink()
                   4447: 
                   4448: Inputs: $text $uname $udom $symb $target
                   4449: 
                   4450: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4451: 
                   4452: =cut
                   4453: 
                   4454: ###############################################
                   4455: sub pgrdlink {
                   4456:     my $link=&submlink(@_);
                   4457:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4458:     return $link;
                   4459: }
                   4460: ##############################################
                   4461: 
                   4462: =pod
                   4463: 
                   4464: =item * &pprmlink()
                   4465: 
                   4466: Inputs: $text $uname $udom $symb $target
                   4467: 
                   4468: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4469: student and a specific resource
1.242     albertel 4470: 
                   4471: =cut
                   4472: 
                   4473: ###############################################
                   4474: sub pprmlink {
                   4475:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4476:     if (!($uname && $udom)) {
                   4477: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4478: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4479: 	if (!$symb) { $symb=$cursymb; }
                   4480:     }
1.254     matthew  4481:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4482:     $symb=&escape($symb);
1.242     albertel 4483:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4484:     return '<a href="/adm/parmset?command=set&amp;'.
                   4485: 	'symb='.$symb.'&amp;uname='.$uname.
                   4486: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4487: }
                   4488: ##############################################
1.37      matthew  4489: 
1.112     bowersj2 4490: =pod
                   4491: 
                   4492: =back
                   4493: 
                   4494: =cut
                   4495: 
1.37      matthew  4496: ###############################################
1.51      www      4497: 
                   4498: 
                   4499: sub timehash {
1.687     raeburn  4500:     my ($thistime) = @_;
                   4501:     my $timezone = &Apache::lonlocal::gettimezone();
                   4502:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4503:                      ->set_time_zone($timezone);
                   4504:     my $wday = $dt->day_of_week();
                   4505:     if ($wday == 7) { $wday = 0; }
                   4506:     return ( 'second' => $dt->second(),
                   4507:              'minute' => $dt->minute(),
                   4508:              'hour'   => $dt->hour(),
                   4509:              'day'     => $dt->day_of_month(),
                   4510:              'month'   => $dt->month(),
                   4511:              'year'    => $dt->year(),
                   4512:              'weekday' => $wday,
                   4513:              'dayyear' => $dt->day_of_year(),
                   4514:              'dlsav'   => $dt->is_dst() );
1.51      www      4515: }
                   4516: 
1.370     www      4517: sub utc_string {
                   4518:     my ($date)=@_;
1.371     www      4519:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4520: }
                   4521: 
1.51      www      4522: sub maketime {
                   4523:     my %th=@_;
1.687     raeburn  4524:     my ($epoch_time,$timezone,$dt);
                   4525:     $timezone = &Apache::lonlocal::gettimezone();
                   4526:     eval {
                   4527:         $dt = DateTime->new( year   => $th{'year'},
                   4528:                              month  => $th{'month'},
                   4529:                              day    => $th{'day'},
                   4530:                              hour   => $th{'hour'},
                   4531:                              minute => $th{'minute'},
                   4532:                              second => $th{'second'},
                   4533:                              time_zone => $timezone,
                   4534:                          );
                   4535:     };
                   4536:     if (!$@) {
                   4537:         $epoch_time = $dt->epoch;
                   4538:         if ($epoch_time) {
                   4539:             return $epoch_time;
                   4540:         }
                   4541:     }
1.51      www      4542:     return POSIX::mktime(
                   4543:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4544:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4545: }
                   4546: 
                   4547: #########################################
1.51      www      4548: 
                   4549: sub findallcourses {
1.482     raeburn  4550:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4551:     my %roles;
                   4552:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4553:     my %courses;
1.51      www      4554:     my $now=time;
1.482     raeburn  4555:     if (!defined($uname)) {
                   4556:         $uname = $env{'user.name'};
                   4557:     }
                   4558:     if (!defined($udom)) {
                   4559:         $udom = $env{'user.domain'};
                   4560:     }
                   4561:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4562:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4563:         if (!%roles) {
                   4564:             %roles = (
                   4565:                        cc => 1,
1.907     raeburn  4566:                        co => 1,
1.482     raeburn  4567:                        in => 1,
                   4568:                        ep => 1,
                   4569:                        ta => 1,
                   4570:                        cr => 1,
                   4571:                        st => 1,
                   4572:              );
                   4573:         }
                   4574:         foreach my $entry (keys(%roleshash)) {
                   4575:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4576:             if ($trole =~ /^cr/) { 
                   4577:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4578:             } else {
                   4579:                 next if (!exists($roles{$trole}));
                   4580:             }
                   4581:             if ($tend) {
                   4582:                 next if ($tend < $now);
                   4583:             }
                   4584:             if ($tstart) {
                   4585:                 next if ($tstart > $now);
                   4586:             }
1.1058    raeburn  4587:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4588:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4589:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4590:             if ($secpart eq '') {
                   4591:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4592:                 $sec = 'none';
1.1058    raeburn  4593:                 $value .= $cnum.'/';
1.482     raeburn  4594:             } else {
                   4595:                 $cnum = $cnumpart;
                   4596:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4597:                 $value .= $cnum.'/'.$sec;
                   4598:             }
                   4599:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4600:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4601:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4602:                 }
                   4603:             } else {
                   4604:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4605:             }
1.482     raeburn  4606:         }
                   4607:     } else {
                   4608:         foreach my $key (keys(%env)) {
1.483     albertel 4609: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4610:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4611: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4612: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4613: 	        next if (%roles && !exists($roles{$role}));
                   4614: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4615:                 my $active=1;
                   4616:                 if ($starttime) {
                   4617: 		    if ($now<$starttime) { $active=0; }
                   4618:                 }
                   4619:                 if ($endtime) {
                   4620:                     if ($now>$endtime) { $active=0; }
                   4621:                 }
                   4622:                 if ($active) {
1.1058    raeburn  4623:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4624:                     if ($sec eq '') {
                   4625:                         $sec = 'none';
1.1058    raeburn  4626:                     } else {
                   4627:                         $value .= $sec;
                   4628:                     }
                   4629:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4630:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4631:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4632:                         }
                   4633:                     } else {
                   4634:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4635:                     }
1.474     raeburn  4636:                 }
                   4637:             }
1.51      www      4638:         }
                   4639:     }
1.474     raeburn  4640:     return %courses;
1.51      www      4641: }
1.37      matthew  4642: 
1.54      www      4643: ###############################################
1.474     raeburn  4644: 
                   4645: sub blockcheck {
1.1189    raeburn  4646:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4647: 
1.1189    raeburn  4648:     if (defined($udom) && defined($uname)) {
                   4649:         # If uname and udom are for a course, check for blocks in the course.
                   4650:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4651:             my ($startblock,$endblock,$triggerblock) =
                   4652:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4653:             return ($startblock,$endblock,$triggerblock);
                   4654:         }
                   4655:     } else {
1.490     raeburn  4656:         $udom = $env{'user.domain'};
                   4657:         $uname = $env{'user.name'};
                   4658:     }
                   4659: 
1.502     raeburn  4660:     my $startblock = 0;
                   4661:     my $endblock = 0;
1.1062    raeburn  4662:     my $triggerblock = '';
1.482     raeburn  4663:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4664: 
1.490     raeburn  4665:     # If uname is for a user, and activity is course-specific, i.e.,
                   4666:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4667: 
1.490     raeburn  4668:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1189    raeburn  4669:          $activity eq 'groups' || $activity eq 'printout') &&
                   4670:         ($env{'request.course.id'})) {
1.490     raeburn  4671:         foreach my $key (keys(%live_courses)) {
                   4672:             if ($key ne $env{'request.course.id'}) {
                   4673:                 delete($live_courses{$key});
                   4674:             }
                   4675:         }
                   4676:     }
                   4677: 
                   4678:     my $otheruser = 0;
                   4679:     my %own_courses;
                   4680:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4681:         # Resource belongs to user other than current user.
                   4682:         $otheruser = 1;
                   4683:         # Gather courses for current user
                   4684:         %own_courses = 
                   4685:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4686:     }
                   4687: 
                   4688:     # Gather active course roles - course coordinator, instructor, 
                   4689:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4690: 
                   4691:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4692:         my ($cdom,$cnum);
                   4693:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4694:             $cdom = $env{'course.'.$course.'.domain'};
                   4695:             $cnum = $env{'course.'.$course.'.num'};
                   4696:         } else {
1.490     raeburn  4697:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4698:         }
                   4699:         my $no_ownblock = 0;
                   4700:         my $no_userblock = 0;
1.533     raeburn  4701:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4702:             # Check if current user has 'evb' priv for this
                   4703:             if (defined($own_courses{$course})) {
                   4704:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4705:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4706:                     if ($sec ne 'none') {
                   4707:                         $checkrole .= '/'.$sec;
                   4708:                     }
                   4709:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4710:                         $no_ownblock = 1;
                   4711:                         last;
                   4712:                     }
                   4713:                 }
                   4714:             }
                   4715:             # if they have 'evb' priv and are currently not playing student
                   4716:             next if (($no_ownblock) &&
                   4717:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4718:         }
1.474     raeburn  4719:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4720:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4721:             if ($sec ne 'none') {
1.482     raeburn  4722:                 $checkrole .= '/'.$sec;
1.474     raeburn  4723:             }
1.490     raeburn  4724:             if ($otheruser) {
                   4725:                 # Resource belongs to user other than current user.
                   4726:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4727:                 my (%allroles,%userroles);
                   4728:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4729:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4730:                         my ($trole,$tdom,$tnum,$tsec);
                   4731:                         if ($entry =~ /^cr/) {
                   4732:                             ($trole,$tdom,$tnum,$tsec) = 
                   4733:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4734:                         } else {
                   4735:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4736:                         }
                   4737:                         my ($spec,$area,$trest);
                   4738:                         $area = '/'.$tdom.'/'.$tnum;
                   4739:                         $trest = $tnum;
                   4740:                         if ($tsec ne '') {
                   4741:                             $area .= '/'.$tsec;
                   4742:                             $trest .= '/'.$tsec;
                   4743:                         }
                   4744:                         $spec = $trole.'.'.$area;
                   4745:                         if ($trole =~ /^cr/) {
                   4746:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4747:                                                               $tdom,$spec,$trest,$area);
                   4748:                         } else {
                   4749:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4750:                                                                 $tdom,$spec,$trest,$area);
                   4751:                         }
                   4752:                     }
                   4753:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4754:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4755:                         if ($1) {
                   4756:                             $no_userblock = 1;
                   4757:                             last;
                   4758:                         }
1.486     raeburn  4759:                     }
                   4760:                 }
1.490     raeburn  4761:             } else {
                   4762:                 # Resource belongs to current user
                   4763:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4764:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4765:                     $no_ownblock = 1;
                   4766:                     last;
                   4767:                 }
1.474     raeburn  4768:             }
                   4769:         }
                   4770:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4771:         next if (($no_ownblock) &&
1.491     albertel 4772:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4773:         next if ($no_userblock);
1.474     raeburn  4774: 
1.866     kalberla 4775:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4776:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4777:         
1.1062    raeburn  4778:         my ($start,$end,$trigger) = 
                   4779:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4780:         if (($start != 0) && 
                   4781:             (($startblock == 0) || ($startblock > $start))) {
                   4782:             $startblock = $start;
1.1062    raeburn  4783:             if ($trigger ne '') {
                   4784:                 $triggerblock = $trigger;
                   4785:             }
1.502     raeburn  4786:         }
                   4787:         if (($end != 0)  &&
                   4788:             (($endblock == 0) || ($endblock < $end))) {
                   4789:             $endblock = $end;
1.1062    raeburn  4790:             if ($trigger ne '') {
                   4791:                 $triggerblock = $trigger;
                   4792:             }
1.502     raeburn  4793:         }
1.490     raeburn  4794:     }
1.1062    raeburn  4795:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4796: }
                   4797: 
                   4798: sub get_blocks {
1.1062    raeburn  4799:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4800:     my $startblock = 0;
                   4801:     my $endblock = 0;
1.1062    raeburn  4802:     my $triggerblock = '';
1.490     raeburn  4803:     my $course = $cdom.'_'.$cnum;
                   4804:     $setters->{$course} = {};
                   4805:     $setters->{$course}{'staff'} = [];
                   4806:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4807:     $setters->{$course}{'triggers'} = [];
                   4808:     my (@blockers,%triggered);
                   4809:     my $now = time;
                   4810:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4811:     if ($activity eq 'docs') {
                   4812:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4813:         foreach my $block (@blockers) {
                   4814:             if ($block =~ /^firstaccess____(.+)$/) {
                   4815:                 my $item = $1;
                   4816:                 my $type = 'map';
                   4817:                 my $timersymb = $item;
                   4818:                 if ($item eq 'course') {
                   4819:                     $type = 'course';
                   4820:                 } elsif ($item =~ /___\d+___/) {
                   4821:                     $type = 'resource';
                   4822:                 } else {
                   4823:                     $timersymb = &Apache::lonnet::symbread($item);
                   4824:                 }
                   4825:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4826:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4827:                 $triggered{$block} = {
                   4828:                                        start => $start,
                   4829:                                        end   => $end,
                   4830:                                        type  => $type,
                   4831:                                      };
                   4832:             }
                   4833:         }
                   4834:     } else {
                   4835:         foreach my $block (keys(%commblocks)) {
                   4836:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4837:                 my ($start,$end) = ($1,$2);
                   4838:                 if ($start <= time && $end >= time) {
                   4839:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4840:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4841:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4842:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4843:                                     push(@blockers,$block);
                   4844:                                 }
                   4845:                             }
                   4846:                         }
                   4847:                     }
                   4848:                 }
                   4849:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4850:                 my $item = $1;
                   4851:                 my $timersymb = $item; 
                   4852:                 my $type = 'map';
                   4853:                 if ($item eq 'course') {
                   4854:                     $type = 'course';
                   4855:                 } elsif ($item =~ /___\d+___/) {
                   4856:                     $type = 'resource';
                   4857:                 } else {
                   4858:                     $timersymb = &Apache::lonnet::symbread($item);
                   4859:                 }
                   4860:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4861:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4862:                 if ($start && $end) {
                   4863:                     if (($start <= time) && ($end >= time)) {
                   4864:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4865:                             push(@blockers,$block);
                   4866:                             $triggered{$block} = {
                   4867:                                                    start => $start,
                   4868:                                                    end   => $end,
                   4869:                                                    type  => $type,
                   4870:                                                  };
                   4871:                         }
                   4872:                     }
1.490     raeburn  4873:                 }
1.1062    raeburn  4874:             }
                   4875:         }
                   4876:     }
                   4877:     foreach my $blocker (@blockers) {
                   4878:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4879:             &parse_block_record($commblocks{$blocker});
                   4880:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4881:         my ($start,$end,$triggertype);
                   4882:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4883:             ($start,$end) = ($1,$2);
                   4884:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4885:             $start = $triggered{$blocker}{'start'};
                   4886:             $end = $triggered{$blocker}{'end'};
                   4887:             $triggertype = $triggered{$blocker}{'type'};
                   4888:         }
                   4889:         if ($start) {
                   4890:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4891:             if ($triggertype) {
                   4892:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4893:             } else {
                   4894:                 push(@{$$setters{$course}{'triggers'}},0);
                   4895:             }
                   4896:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4897:                 $startblock = $start;
                   4898:                 if ($triggertype) {
                   4899:                     $triggerblock = $blocker;
1.474     raeburn  4900:                 }
                   4901:             }
1.1062    raeburn  4902:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4903:                $endblock = $end;
                   4904:                if ($triggertype) {
                   4905:                    $triggerblock = $blocker;
                   4906:                }
                   4907:             }
1.474     raeburn  4908:         }
                   4909:     }
1.1062    raeburn  4910:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4911: }
                   4912: 
                   4913: sub parse_block_record {
                   4914:     my ($record) = @_;
                   4915:     my ($setuname,$setudom,$title,$blocks);
                   4916:     if (ref($record) eq 'HASH') {
                   4917:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4918:         $title = &unescape($record->{'event'});
                   4919:         $blocks = $record->{'blocks'};
                   4920:     } else {
                   4921:         my @data = split(/:/,$record,3);
                   4922:         if (scalar(@data) eq 2) {
                   4923:             $title = $data[1];
                   4924:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4925:         } else {
                   4926:             ($setuname,$setudom,$title) = @data;
                   4927:         }
                   4928:         $blocks = { 'com' => 'on' };
                   4929:     }
                   4930:     return ($setuname,$setudom,$title,$blocks);
                   4931: }
                   4932: 
1.854     kalberla 4933: sub blocking_status {
1.1189    raeburn  4934:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4935:     my %setters;
1.890     droeschl 4936: 
1.1061    raeburn  4937: # check for active blocking
1.1062    raeburn  4938:     my ($startblock,$endblock,$triggerblock) = 
1.1189    raeburn  4939:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4940:     my $blocked = 0;
                   4941:     if ($startblock && $endblock) {
                   4942:         $blocked = 1;
                   4943:     }
1.890     droeschl 4944: 
1.1061    raeburn  4945: # caller just wants to know whether a block is active
                   4946:     if (!wantarray) { return $blocked; }
                   4947: 
                   4948: # build a link to a popup window containing the details
                   4949:     my $querystring  = "?activity=$activity";
                   4950: # $uname and $udom decide whose portfolio the user is trying to look at
1.1062    raeburn  4951:     if ($activity eq 'port') {
                   4952:         $querystring .= "&amp;udom=$udom"      if $udom;
                   4953:         $querystring .= "&amp;uname=$uname"    if $uname;
                   4954:     } elsif ($activity eq 'docs') {
                   4955:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4956:     }
1.1061    raeburn  4957: 
                   4958:     my $output .= <<'END_MYBLOCK';
                   4959: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4960:     var options = "width=" + w + ",height=" + h + ",";
                   4961:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4962:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4963:     var newWin = window.open(url, wdwName, options);
                   4964:     newWin.focus();
                   4965: }
1.890     droeschl 4966: END_MYBLOCK
1.854     kalberla 4967: 
1.1061    raeburn  4968:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4969:   
1.1061    raeburn  4970:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4971:     my $text = &mt('Communication Blocked');
1.1217  ! raeburn  4972:     my $class = 'LC_comblock';
1.1062    raeburn  4973:     if ($activity eq 'docs') {
                   4974:         $text = &mt('Content Access Blocked');
1.1217  ! raeburn  4975:         $class = '';
1.1063    raeburn  4976:     } elsif ($activity eq 'printout') {
                   4977:         $text = &mt('Printing Blocked');
1.1062    raeburn  4978:     }
1.1061    raeburn  4979:     $output .= <<"END_BLOCK";
1.1217  ! raeburn  4980: <div class='$class'>
1.869     kalberla 4981:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4982:   title='$text'>
                   4983:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4984:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4985:   title='$text'>$text</a>
1.867     kalberla 4986: </div>
                   4987: 
                   4988: END_BLOCK
1.474     raeburn  4989: 
1.1061    raeburn  4990:     return ($blocked, $output);
1.854     kalberla 4991: }
1.490     raeburn  4992: 
1.60      matthew  4993: ###############################################
                   4994: 
1.682     raeburn  4995: sub check_ip_acc {
1.1201    raeburn  4996:     my ($acc,$clientip)=@_;
1.682     raeburn  4997:     &Apache::lonxml::debug("acc is $acc");
                   4998:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4999:         return 1;
                   5000:     }
                   5001:     my $allowed=0;
1.1201    raeburn  5002:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'} || $clientip;
1.682     raeburn  5003: 
                   5004:     my $name;
                   5005:     foreach my $pattern (split(',',$acc)) {
                   5006:         $pattern =~ s/^\s*//;
                   5007:         $pattern =~ s/\s*$//;
                   5008:         if ($pattern =~ /\*$/) {
                   5009:             #35.8.*
                   5010:             $pattern=~s/\*//;
                   5011:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5012:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   5013:             #35.8.3.[34-56]
                   5014:             my $low=$2;
                   5015:             my $high=$3;
                   5016:             $pattern=$1;
                   5017:             if ($ip =~ /^\Q$pattern\E/) {
                   5018:                 my $last=(split(/\./,$ip))[3];
                   5019:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   5020:             }
                   5021:         } elsif ($pattern =~ /^\*/) {
                   5022:             #*.msu.edu
                   5023:             $pattern=~s/\*//;
                   5024:             if (!defined($name)) {
                   5025:                 use Socket;
                   5026:                 my $netaddr=inet_aton($ip);
                   5027:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5028:             }
                   5029:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5030:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   5031:             #127.0.0.1
                   5032:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   5033:         } else {
                   5034:             #some.name.com
                   5035:             if (!defined($name)) {
                   5036:                 use Socket;
                   5037:                 my $netaddr=inet_aton($ip);
                   5038:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   5039:             }
                   5040:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   5041:         }
                   5042:         if ($allowed) { last; }
                   5043:     }
                   5044:     return $allowed;
                   5045: }
                   5046: 
                   5047: ###############################################
                   5048: 
1.60      matthew  5049: =pod
                   5050: 
1.112     bowersj2 5051: =head1 Domain Template Functions
                   5052: 
                   5053: =over 4
                   5054: 
                   5055: =item * &determinedomain()
1.60      matthew  5056: 
                   5057: Inputs: $domain (usually will be undef)
                   5058: 
1.63      www      5059: Returns: Determines which domain should be used for designs
1.60      matthew  5060: 
                   5061: =cut
1.54      www      5062: 
1.60      matthew  5063: ###############################################
1.63      www      5064: sub determinedomain {
                   5065:     my $domain=shift;
1.531     albertel 5066:     if (! $domain) {
1.60      matthew  5067:         # Determine domain if we have not been given one
1.893     raeburn  5068:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5069:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5070:         if ($env{'request.role.domain'}) { 
                   5071:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5072:         }
                   5073:     }
1.63      www      5074:     return $domain;
                   5075: }
                   5076: ###############################################
1.517     raeburn  5077: 
1.518     albertel 5078: sub devalidate_domconfig_cache {
                   5079:     my ($udom)=@_;
                   5080:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5081: }
                   5082: 
                   5083: # ---------------------- Get domain configuration for a domain
                   5084: sub get_domainconf {
                   5085:     my ($udom) = @_;
                   5086:     my $cachetime=1800;
                   5087:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5088:     if (defined($cached)) { return %{$result}; }
                   5089: 
                   5090:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5091: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5092:     my (%designhash,%legacy);
1.518     albertel 5093:     if (keys(%domconfig) > 0) {
                   5094:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5095:             if (keys(%{$domconfig{'login'}})) {
                   5096:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5097:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1208    raeburn  5098:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5099:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5100:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5101:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5102:                                         if ($key eq 'loginvia') {
                   5103:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5104:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5105:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5106:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5107: 
                   5108:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5109:                                                 } else {
                   5110:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5111:                                                 }
1.948     raeburn  5112:                                             }
1.1208    raeburn  5113:                                         } elsif ($key eq 'headtag') {
                   5114:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5115:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5116:                                             }
1.946     raeburn  5117:                                         }
1.1208    raeburn  5118:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5119:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5120:                                         }
1.946     raeburn  5121:                                     }
                   5122:                                 }
                   5123:                             }
                   5124:                         } else {
                   5125:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5126:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5127:                                     $domconfig{'login'}{$key}{$img};
                   5128:                             }
1.699     raeburn  5129:                         }
                   5130:                     } else {
                   5131:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5132:                     }
1.632     raeburn  5133:                 }
                   5134:             } else {
                   5135:                 $legacy{'login'} = 1;
1.518     albertel 5136:             }
1.632     raeburn  5137:         } else {
                   5138:             $legacy{'login'} = 1;
1.518     albertel 5139:         }
                   5140:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5141:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5142:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5143:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5144:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5145:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5146:                         }
1.518     albertel 5147:                     }
                   5148:                 }
1.632     raeburn  5149:             } else {
                   5150:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5151:             }
1.632     raeburn  5152:         } else {
                   5153:             $legacy{'rolecolors'} = 1;
1.518     albertel 5154:         }
1.948     raeburn  5155:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5156:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5157:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5158:             }
                   5159:         }
1.632     raeburn  5160:         if (keys(%legacy) > 0) {
                   5161:             my %legacyhash = &get_legacy_domconf($udom);
                   5162:             foreach my $item (keys(%legacyhash)) {
                   5163:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5164:                     if ($legacy{'login'}) { 
                   5165:                         $designhash{$item} = $legacyhash{$item};
                   5166:                     }
                   5167:                 } else {
                   5168:                     if ($legacy{'rolecolors'}) {
                   5169:                         $designhash{$item} = $legacyhash{$item};
                   5170:                     }
1.518     albertel 5171:                 }
                   5172:             }
                   5173:         }
1.632     raeburn  5174:     } else {
                   5175:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5176:     }
                   5177:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5178: 				  $cachetime);
                   5179:     return %designhash;
                   5180: }
                   5181: 
1.632     raeburn  5182: sub get_legacy_domconf {
                   5183:     my ($udom) = @_;
                   5184:     my %legacyhash;
                   5185:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5186:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5187:     if (-e $designfile) {
                   5188:         if ( open (my $fh,"<$designfile") ) {
                   5189:             while (my $line = <$fh>) {
                   5190:                 next if ($line =~ /^\#/);
                   5191:                 chomp($line);
                   5192:                 my ($key,$val)=(split(/\=/,$line));
                   5193:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5194:             }
                   5195:             close($fh);
                   5196:         }
                   5197:     }
1.1026    raeburn  5198:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5199:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5200:     }
                   5201:     return %legacyhash;
                   5202: }
                   5203: 
1.63      www      5204: =pod
                   5205: 
1.112     bowersj2 5206: =item * &domainlogo()
1.63      www      5207: 
                   5208: Inputs: $domain (usually will be undef)
                   5209: 
                   5210: Returns: A link to a domain logo, if the domain logo exists.
                   5211: If the domain logo does not exist, a description of the domain.
                   5212: 
                   5213: =cut
1.112     bowersj2 5214: 
1.63      www      5215: ###############################################
                   5216: sub domainlogo {
1.517     raeburn  5217:     my $domain = &determinedomain(shift);
1.518     albertel 5218:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5219:     # See if there is a logo
                   5220:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5221:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5222:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5223: 	    if ($imgsrc =~ m{^/res/}) {
                   5224: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5225: 		&Apache::lonnet::repcopy($local_name);
                   5226: 	    }
                   5227: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5228:         } 
                   5229:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5230:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5231:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5232:     } else {
1.60      matthew  5233:         return '';
1.59      www      5234:     }
                   5235: }
1.63      www      5236: ##############################################
                   5237: 
                   5238: =pod
                   5239: 
1.112     bowersj2 5240: =item * &designparm()
1.63      www      5241: 
                   5242: Inputs: $which parameter; $domain (usually will be undef)
                   5243: 
                   5244: Returns: value of designparamter $which
                   5245: 
                   5246: =cut
1.112     bowersj2 5247: 
1.397     albertel 5248: 
1.400     albertel 5249: ##############################################
1.397     albertel 5250: sub designparm {
                   5251:     my ($which,$domain)=@_;
                   5252:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5253:         return $env{'environment.color.'.$which};
1.96      www      5254:     }
1.63      www      5255:     $domain=&determinedomain($domain);
1.1016    raeburn  5256:     my %domdesign;
                   5257:     unless ($domain eq 'public') {
                   5258:         %domdesign = &get_domainconf($domain);
                   5259:     }
1.520     raeburn  5260:     my $output;
1.517     raeburn  5261:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5262:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5263:     } else {
1.520     raeburn  5264:         $output = $defaultdesign{$which};
                   5265:     }
                   5266:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5267:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5268:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5269:             if ($output =~ m{^/res/}) {
                   5270:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5271:                 &Apache::lonnet::repcopy($local_name);
                   5272:             }
1.520     raeburn  5273:             $output = &lonhttpdurl($output);
                   5274:         }
1.63      www      5275:     }
1.520     raeburn  5276:     return $output;
1.63      www      5277: }
1.59      www      5278: 
1.822     bisitz   5279: ##############################################
                   5280: =pod
                   5281: 
1.832     bisitz   5282: =item * &authorspace()
                   5283: 
1.1028    raeburn  5284: Inputs: $url (usually will be undef).
1.832     bisitz   5285: 
1.1132    raeburn  5286: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5287:          directory being viewed (or for which action is being taken). 
                   5288:          If $url is provided, and begins /priv/<domain>/<uname>
                   5289:          the path will be that portion of the $context argument.
                   5290:          Otherwise the path will be for the author space of the current
                   5291:          user when the current role is author, or for that of the 
                   5292:          co-author/assistant co-author space when the current role 
                   5293:          is co-author or assistant co-author.
1.832     bisitz   5294: 
                   5295: =cut
                   5296: 
                   5297: sub authorspace {
1.1028    raeburn  5298:     my ($url) = @_;
                   5299:     if ($url ne '') {
                   5300:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5301:            return $1;
                   5302:         }
                   5303:     }
1.832     bisitz   5304:     my $caname = '';
1.1024    www      5305:     my $cadom = '';
1.1028    raeburn  5306:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5307:         ($cadom,$caname) =
1.832     bisitz   5308:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5309:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5310:         $caname = $env{'user.name'};
1.1024    www      5311:         $cadom = $env{'user.domain'};
1.832     bisitz   5312:     }
1.1028    raeburn  5313:     if (($caname ne '') && ($cadom ne '')) {
                   5314:         return "/priv/$cadom/$caname/";
                   5315:     }
                   5316:     return;
1.832     bisitz   5317: }
                   5318: 
                   5319: ##############################################
                   5320: =pod
                   5321: 
1.822     bisitz   5322: =item * &head_subbox()
                   5323: 
                   5324: Inputs: $content (contains HTML code with page functions, etc.)
                   5325: 
                   5326: Returns: HTML div with $content
                   5327:          To be included in page header
                   5328: 
                   5329: =cut
                   5330: 
                   5331: sub head_subbox {
                   5332:     my ($content)=@_;
                   5333:     my $output =
1.993     raeburn  5334:         '<div class="LC_head_subbox">'
1.822     bisitz   5335:        .$content
                   5336:        .'</div>'
                   5337: }
                   5338: 
                   5339: ##############################################
                   5340: =pod
                   5341: 
                   5342: =item * &CSTR_pageheader()
                   5343: 
1.1026    raeburn  5344: Input: (optional) filename from which breadcrumb trail is built.
                   5345:        In most cases no input as needed, as $env{'request.filename'}
                   5346:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5347: 
                   5348: Returns: HTML div with CSTR path and recent box
1.1132    raeburn  5349:          To be included on Authoring Space pages
1.822     bisitz   5350: 
                   5351: =cut
                   5352: 
                   5353: sub CSTR_pageheader {
1.1026    raeburn  5354:     my ($trailfile) = @_;
                   5355:     if ($trailfile eq '') {
                   5356:         $trailfile = $env{'request.filename'};
                   5357:     }
                   5358: 
                   5359: # this is for resources; directories have customtitle, and crumbs
                   5360: # and select recent are created in lonpubdir.pm
                   5361: 
                   5362:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5363:     my ($udom,$uname,$thisdisfn)=
1.1113    raeburn  5364:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5365:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5366:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5367: 
                   5368:     my $parentpath = '';
                   5369:     my $lastitem = '';
                   5370:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5371:         $parentpath = $1;
                   5372:         $lastitem = $2;
                   5373:     } else {
                   5374:         $lastitem = $thisdisfn;
                   5375:     }
1.921     bisitz   5376: 
                   5377:     my $output =
1.822     bisitz   5378:          '<div>'
                   5379:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1132    raeburn  5380:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5381:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5382:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5383:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5384: 
                   5385:     if ($lastitem) {
                   5386:         $output .=
                   5387:              '<span class="LC_filename">'
                   5388:             .$lastitem
                   5389:             .'</span>';
                   5390:     }
                   5391:     $output .=
                   5392:          '<br />'
1.822     bisitz   5393:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5394:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5395:         .'</form>'
                   5396:         .&Apache::lonmenu::constspaceform()
                   5397:         .'</div>';
1.921     bisitz   5398: 
                   5399:     return $output;
1.822     bisitz   5400: }
                   5401: 
1.60      matthew  5402: ###############################################
                   5403: ###############################################
                   5404: 
                   5405: =pod
                   5406: 
1.112     bowersj2 5407: =back
                   5408: 
1.549     albertel 5409: =head1 HTML Helpers
1.112     bowersj2 5410: 
                   5411: =over 4
                   5412: 
                   5413: =item * &bodytag()
1.60      matthew  5414: 
                   5415: Returns a uniform header for LON-CAPA web pages.
                   5416: 
                   5417: Inputs: 
                   5418: 
1.112     bowersj2 5419: =over 4
                   5420: 
                   5421: =item * $title, A title to be displayed on the page.
                   5422: 
                   5423: =item * $function, the current role (can be undef).
                   5424: 
                   5425: =item * $addentries, extra parameters for the <body> tag.
                   5426: 
                   5427: =item * $bodyonly, if defined, only return the <body> tag.
                   5428: 
                   5429: =item * $domain, if defined, force a given domain.
                   5430: 
                   5431: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5432:             text interface only)
1.60      matthew  5433: 
1.814     bisitz   5434: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5435:                      navigational links
1.317     albertel 5436: 
1.338     albertel 5437: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5438: 
1.460     albertel 5439: =item * $args, optional argument valid values are
                   5440:             no_auto_mt_title -> prevents &mt()ing the title arg
1.562     albertel 5441:             inherit_jsmath -> when creating popup window in a page,
                   5442:                               should it have jsmath forced on by the
                   5443:                               current page
1.460     albertel 5444: 
1.1096    raeburn  5445: =item * $advtoolsref, optional argument, ref to an array containing
                   5446:             inlineremote items to be added in "Functions" menu below
                   5447:             breadcrumbs.
                   5448: 
1.112     bowersj2 5449: =back
                   5450: 
1.60      matthew  5451: Returns: A uniform header for LON-CAPA web pages.  
                   5452: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5453: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5454: other decorations will be returned.
                   5455: 
                   5456: =cut
                   5457: 
1.54      www      5458: sub bodytag {
1.831     bisitz   5459:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1096    raeburn  5460:         $no_nav_bar,$bgcolor,$args,$advtoolsref)=@_;
1.339     albertel 5461: 
1.954     raeburn  5462:     my $public;
                   5463:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5464:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5465:         $public = 1;
                   5466:     }
1.460     albertel 5467:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1154    raeburn  5468:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5469: 
1.183     matthew  5470:     $function = &get_users_function() if (!$function);
1.339     albertel 5471:     my $img =    &designparm($function.'.img',$domain);
                   5472:     my $font =   &designparm($function.'.font',$domain);
                   5473:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5474: 
1.803     bisitz   5475:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5476: 		   'bgcolor' => $pgbg,
1.339     albertel 5477: 		   'text'    => $font,
                   5478:                    'alink'   => &designparm($function.'.alink',$domain),
                   5479: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5480: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5481:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5482: 
1.63      www      5483:  # role and realm
1.1178    raeburn  5484:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5485:     if ($realm) {
                   5486:         $realm = '/'.$realm;
                   5487:     }
1.378     raeburn  5488:     if ($role  eq 'ca') {
1.479     albertel 5489:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5490:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5491:     } 
1.55      www      5492: # realm
1.258     albertel 5493:     if ($env{'request.course.id'}) {
1.378     raeburn  5494:         if ($env{'request.role'} !~ /^cr/) {
                   5495:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5496:         }
1.898     raeburn  5497:         if ($env{'request.course.sec'}) {
                   5498:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5499:         }   
1.359     albertel 5500: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5501:     } else {
                   5502:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5503:     }
1.433     albertel 5504: 
1.359     albertel 5505:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5506: 
1.438     albertel 5507:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5508: 
1.101     www      5509: # construct main body tag
1.359     albertel 5510:     my $bodytag = "<body $extra_body_attr>".
1.562     albertel 5511: 	&Apache::lontexconvert::init_math_support($args->{'inherit_jsmath'});
1.252     albertel 5512: 
1.1131    raeburn  5513:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5514: 
1.1130    raeburn  5515:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5516:         return $bodytag;
1.1130    raeburn  5517:     }
1.359     albertel 5518: 
1.954     raeburn  5519:     if ($public) {
1.433     albertel 5520: 	undef($role);
                   5521:     }
1.359     albertel 5522:     
1.762     bisitz   5523:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5524:     #
                   5525:     # Extra info if you are the DC
                   5526:     my $dc_info = '';
                   5527:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5528:                         $env{'course.'.$env{'request.course.id'}.
                   5529:                                  '.domain'}.'/'})) {
                   5530:         my $cid = $env{'request.course.id'};
1.917     raeburn  5531:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5532:         $dc_info =~ s/\s+$//;
1.359     albertel 5533:     }
                   5534: 
1.898     raeburn  5535:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.853     droeschl 5536: 
1.903     droeschl 5537:         if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5538: 
                   5539:         #    if ($env{'request.state'} eq 'construct') {
                   5540:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5541:         #    }
                   5542: 
1.1130    raeburn  5543:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1154    raeburn  5544:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5545: 
1.1130    raeburn  5546:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.359     albertel 5547: 
1.916     droeschl 5548:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.917     raeburn  5549:              if ($dc_info) {
                   5550:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
                   5551:              }
1.1130    raeburn  5552:              $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.916     droeschl 5553:                 <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5554:             return $bodytag;
                   5555:         }
1.894     droeschl 5556: 
1.927     raeburn  5557:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1130    raeburn  5558:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5559:         }
1.916     droeschl 5560: 
1.1130    raeburn  5561:         $bodytag .= $right;
1.852     droeschl 5562: 
1.917     raeburn  5563:         if ($dc_info) {
                   5564:             $dc_info = &dc_courseid_toggle($dc_info);
                   5565:         }
                   5566:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5567: 
1.1169    raeburn  5568:         #if directed to not display the secondary menu, don't.  
1.1168    raeburn  5569:         if ($args->{'no_secondary_menu'}) {
                   5570:             return $bodytag;
                   5571:         }
1.1169    raeburn  5572:         #don't show menus for public users
1.954     raeburn  5573:         if (!$public){
1.1154    raeburn  5574:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5575:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5576:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5577:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5578:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5579:                                 $args->{'bread_crumbs'});
1.1096    raeburn  5580:             } elsif ($forcereg) {
                   5581:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5582:                                                             $args->{'group'});
                   5583:             } else {
                   5584:                 $bodytag .= 
                   5585:                     &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5586:                                                         $forcereg,$args->{'group'},
                   5587:                                                         $args->{'bread_crumbs'},
                   5588:                                                         $advtoolsref);
1.920     raeburn  5589:             }
1.903     droeschl 5590:         }else{
                   5591:             # this is to seperate menu from content when there's no secondary
                   5592:             # menu. Especially needed for public accessible ressources.
                   5593:             $bodytag .= '<hr style="clear:both" />';
                   5594:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5595:         }
1.903     droeschl 5596: 
1.235     raeburn  5597:         return $bodytag;
1.182     matthew  5598: }
                   5599: 
1.917     raeburn  5600: sub dc_courseid_toggle {
                   5601:     my ($dc_info) = @_;
1.980     raeburn  5602:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5603:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5604:            &mt('(More ...)').'</a></span>'.
                   5605:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5606: }
                   5607: 
1.330     albertel 5608: sub make_attr_string {
                   5609:     my ($register,$attr_ref) = @_;
                   5610: 
                   5611:     if ($attr_ref && !ref($attr_ref)) {
                   5612: 	die("addentries Must be a hash ref ".
                   5613: 	    join(':',caller(1))." ".
                   5614: 	    join(':',caller(0))." ");
                   5615:     }
                   5616: 
                   5617:     if ($register) {
1.339     albertel 5618: 	my ($on_load,$on_unload);
                   5619: 	foreach my $key (keys(%{$attr_ref})) {
                   5620: 	    if      (lc($key) eq 'onload') {
                   5621: 		$on_load.=$attr_ref->{$key}.';';
                   5622: 		delete($attr_ref->{$key});
                   5623: 
                   5624: 	    } elsif (lc($key) eq 'onunload') {
                   5625: 		$on_unload.=$attr_ref->{$key}.';';
                   5626: 		delete($attr_ref->{$key});
                   5627: 	    }
                   5628: 	}
1.953     droeschl 5629: 	$attr_ref->{'onload'}  = $on_load;
                   5630: 	$attr_ref->{'onunload'}= $on_unload;
1.330     albertel 5631:     }
1.339     albertel 5632: 
1.330     albertel 5633:     my $attr_string;
1.1159    raeburn  5634:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5635: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5636:     }
                   5637:     return $attr_string;
                   5638: }
                   5639: 
                   5640: 
1.182     matthew  5641: ###############################################
1.251     albertel 5642: ###############################################
                   5643: 
                   5644: =pod
                   5645: 
                   5646: =item * &endbodytag()
                   5647: 
                   5648: Returns a uniform footer for LON-CAPA web pages.
                   5649: 
1.635     raeburn  5650: Inputs: 1 - optional reference to an args hash
                   5651: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5652: a 'Continue' link is not displayed if the page contains an
                   5653: internal redirect in the <head></head> section,
                   5654: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5655: 
                   5656: =cut
                   5657: 
                   5658: sub endbodytag {
1.635     raeburn  5659:     my ($args) = @_;
1.1080    raeburn  5660:     my $endbodytag;
                   5661:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5662:         $endbodytag='</body>';
                   5663:     }
1.269     albertel 5664:     $endbodytag=&Apache::lontexconvert::jsMath_process()."\n".$endbodytag;
1.315     albertel 5665:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5666:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5667: 	    $endbodytag=
                   5668: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5669: 	        &mt('Continue').'</a>'.
                   5670: 	        $endbodytag;
                   5671:         }
1.315     albertel 5672:     }
1.251     albertel 5673:     return $endbodytag;
                   5674: }
                   5675: 
1.352     albertel 5676: =pod
                   5677: 
                   5678: =item * &standard_css()
                   5679: 
                   5680: Returns a style sheet
                   5681: 
                   5682: Inputs: (all optional)
                   5683:             domain         -> force to color decorate a page for a specific
                   5684:                                domain
                   5685:             function       -> force usage of a specific rolish color scheme
                   5686:             bgcolor        -> override the default page bgcolor
                   5687: 
                   5688: =cut
                   5689: 
1.343     albertel 5690: sub standard_css {
1.345     albertel 5691:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5692:     $function  = &get_users_function() if (!$function);
                   5693:     my $img    = &designparm($function.'.img',   $domain);
                   5694:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5695:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5696:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5697: #second colour for later usage
1.345     albertel 5698:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5699:     my $pgbg_or_bgcolor =
                   5700: 	         $bgcolor ||
1.352     albertel 5701: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5702:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5703:     my $alink  = &designparm($function.'.alink', $domain);
                   5704:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5705:     my $link   = &designparm($function.'.link',  $domain);
                   5706: 
1.602     albertel 5707:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5708:     my $mono                 = 'monospace';
1.850     bisitz   5709:     my $data_table_head      = $sidebg;
                   5710:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5711:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5712:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5713:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5714:     my $mail_new             = '#FFBB77';
                   5715:     my $mail_new_hover       = '#DD9955';
                   5716:     my $mail_read            = '#BBBB77';
                   5717:     my $mail_read_hover      = '#999944';
                   5718:     my $mail_replied         = '#AAAA88';
                   5719:     my $mail_replied_hover   = '#888855';
                   5720:     my $mail_other           = '#99BBBB';
                   5721:     my $mail_other_hover     = '#669999';
1.391     albertel 5722:     my $table_header         = '#DDDDDD';
1.489     raeburn  5723:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5724:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5725:     my $button_hover         = '#BF2317';
1.392     albertel 5726: 
1.608     albertel 5727:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5728:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5729:                                              : '0 3px 0 4px';
1.448     albertel 5730: 
1.523     albertel 5731: 
1.343     albertel 5732:     return <<END;
1.947     droeschl 5733: 
                   5734: /* needed for iframe to allow 100% height in FF */
                   5735: body, html { 
                   5736:     margin: 0;
                   5737:     padding: 0 0.5%;
                   5738:     height: 99%; /* to avoid scrollbars */
                   5739: }
                   5740: 
1.795     www      5741: body {
1.911     bisitz   5742:   font-family: $sans;
                   5743:   line-height:130%;
                   5744:   font-size:0.83em;
                   5745:   color:$font;
1.795     www      5746: }
                   5747: 
1.959     onken    5748: a:focus,
                   5749: a:focus img {
1.795     www      5750:   color: red;
                   5751: }
1.698     harmsja  5752: 
1.911     bisitz   5753: form, .inline {
                   5754:   display: inline;
1.795     www      5755: }
1.721     harmsja  5756: 
1.795     www      5757: .LC_right {
1.911     bisitz   5758:   text-align:right;
1.795     www      5759: }
                   5760: 
                   5761: .LC_middle {
1.911     bisitz   5762:   vertical-align:middle;
1.795     www      5763: }
1.721     harmsja  5764: 
1.1130    raeburn  5765: .LC_floatleft {
                   5766:   float: left;
                   5767: }
                   5768: 
                   5769: .LC_floatright {
                   5770:   float: right;
                   5771: }
                   5772: 
1.911     bisitz   5773: .LC_400Box {
                   5774:   width:400px;
                   5775: }
1.721     harmsja  5776: 
1.947     droeschl 5777: .LC_iframecontainer {
                   5778:     width: 98%;
                   5779:     margin: 0;
                   5780:     position: fixed;
                   5781:     top: 8.5em;
                   5782:     bottom: 0;
                   5783: }
                   5784: 
                   5785: .LC_iframecontainer iframe{
                   5786:     border: none;
                   5787:     width: 100%;
                   5788:     height: 100%;
                   5789: }
                   5790: 
1.778     bisitz   5791: .LC_filename {
                   5792:   font-family: $mono;
                   5793:   white-space:pre;
1.921     bisitz   5794:   font-size: 120%;
1.778     bisitz   5795: }
                   5796: 
                   5797: .LC_fileicon {
                   5798:   border: none;
                   5799:   height: 1.3em;
                   5800:   vertical-align: text-bottom;
                   5801:   margin-right: 0.3em;
                   5802:   text-decoration:none;
                   5803: }
                   5804: 
1.1008    www      5805: .LC_setting {
                   5806:   text-decoration:underline;
                   5807: }
                   5808: 
1.350     albertel 5809: .LC_error {
                   5810:   color: red;
                   5811: }
1.795     www      5812: 
1.1097    bisitz   5813: .LC_warning {
                   5814:   color: darkorange;
                   5815: }
                   5816: 
1.457     albertel 5817: .LC_diff_removed {
1.733     bisitz   5818:   color: red;
1.394     albertel 5819: }
1.532     albertel 5820: 
                   5821: .LC_info,
1.457     albertel 5822: .LC_success,
                   5823: .LC_diff_added {
1.350     albertel 5824:   color: green;
                   5825: }
1.795     www      5826: 
1.802     bisitz   5827: div.LC_confirm_box {
                   5828:   background-color: #FAFAFA;
                   5829:   border: 1px solid $lg_border_color;
                   5830:   margin-right: 0;
                   5831:   padding: 5px;
                   5832: }
                   5833: 
                   5834: div.LC_confirm_box .LC_error img,
                   5835: div.LC_confirm_box .LC_success img {
                   5836:   vertical-align: middle;
                   5837: }
                   5838: 
1.440     albertel 5839: .LC_icon {
1.771     droeschl 5840:   border: none;
1.790     droeschl 5841:   vertical-align: middle;
1.771     droeschl 5842: }
                   5843: 
1.543     albertel 5844: .LC_docs_spacer {
                   5845:   width: 25px;
                   5846:   height: 1px;
1.771     droeschl 5847:   border: none;
1.543     albertel 5848: }
1.346     albertel 5849: 
1.532     albertel 5850: .LC_internal_info {
1.735     bisitz   5851:   color: #999999;
1.532     albertel 5852: }
                   5853: 
1.794     www      5854: .LC_discussion {
1.1050    www      5855:   background: $data_table_dark;
1.911     bisitz   5856:   border: 1px solid black;
                   5857:   margin: 2px;
1.794     www      5858: }
                   5859: 
                   5860: .LC_disc_action_left {
1.1050    www      5861:   background: $sidebg;
1.911     bisitz   5862:   text-align: left;
1.1050    www      5863:   padding: 4px;
                   5864:   margin: 2px;
1.794     www      5865: }
                   5866: 
                   5867: .LC_disc_action_right {
1.1050    www      5868:   background: $sidebg;
1.911     bisitz   5869:   text-align: right;
1.1050    www      5870:   padding: 4px;
                   5871:   margin: 2px;
1.794     www      5872: }
                   5873: 
                   5874: .LC_disc_new_item {
1.911     bisitz   5875:   background: white;
                   5876:   border: 2px solid red;
1.1050    www      5877:   margin: 4px;
                   5878:   padding: 4px;
1.794     www      5879: }
                   5880: 
                   5881: .LC_disc_old_item {
1.911     bisitz   5882:   background: white;
1.1050    www      5883:   margin: 4px;
                   5884:   padding: 4px;
1.794     www      5885: }
                   5886: 
1.458     albertel 5887: table.LC_pastsubmission {
                   5888:   border: 1px solid black;
                   5889:   margin: 2px;
                   5890: }
                   5891: 
1.924     bisitz   5892: table#LC_menubuttons {
1.345     albertel 5893:   width: 100%;
                   5894:   background: $pgbg;
1.392     albertel 5895:   border: 2px;
1.402     albertel 5896:   border-collapse: separate;
1.803     bisitz   5897:   padding: 0;
1.345     albertel 5898: }
1.392     albertel 5899: 
1.801     tempelho 5900: table#LC_title_bar a {
                   5901:   color: $fontmenu;
                   5902: }
1.836     bisitz   5903: 
1.807     droeschl 5904: table#LC_title_bar {
1.819     tempelho 5905:   clear: both;
1.836     bisitz   5906:   display: none;
1.807     droeschl 5907: }
                   5908: 
1.795     www      5909: table#LC_title_bar,
1.933     droeschl 5910: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5911: table#LC_title_bar.LC_with_remote {
1.359     albertel 5912:   width: 100%;
1.392     albertel 5913:   border-color: $pgbg;
                   5914:   border-style: solid;
                   5915:   border-width: $border;
1.379     albertel 5916:   background: $pgbg;
1.801     tempelho 5917:   color: $fontmenu;
1.392     albertel 5918:   border-collapse: collapse;
1.803     bisitz   5919:   padding: 0;
1.819     tempelho 5920:   margin: 0;
1.359     albertel 5921: }
1.795     www      5922: 
1.933     droeschl 5923: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5924:     margin: 0;
                   5925:     padding: 0;
1.933     droeschl 5926:     position: relative;
                   5927:     list-style: none;
1.913     droeschl 5928: }
1.933     droeschl 5929: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5930:     display: inline;
                   5931: }
1.933     droeschl 5932: 
                   5933: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5934:     padding: 0;
1.933     droeschl 5935:     margin: 0;
                   5936:     float: left;
1.913     droeschl 5937: }
1.933     droeschl 5938: .LC_breadcrumb_tools_tools {
                   5939:     padding: 0;
                   5940:     margin: 0;
1.913     droeschl 5941:     float: right;
                   5942: }
                   5943: 
1.359     albertel 5944: table#LC_title_bar td {
                   5945:   background: $tabbg;
                   5946: }
1.795     www      5947: 
1.911     bisitz   5948: table#LC_menubuttons img {
1.803     bisitz   5949:   border: none;
1.346     albertel 5950: }
1.795     www      5951: 
1.842     droeschl 5952: .LC_breadcrumbs_component {
1.911     bisitz   5953:   float: right;
                   5954:   margin: 0 1em;
1.357     albertel 5955: }
1.842     droeschl 5956: .LC_breadcrumbs_component img {
1.911     bisitz   5957:   vertical-align: middle;
1.777     tempelho 5958: }
1.795     www      5959: 
1.383     albertel 5960: td.LC_table_cell_checkbox {
                   5961:   text-align: center;
                   5962: }
1.795     www      5963: 
                   5964: .LC_fontsize_small {
1.911     bisitz   5965:   font-size: 70%;
1.705     tempelho 5966: }
                   5967: 
1.844     bisitz   5968: #LC_breadcrumbs {
1.911     bisitz   5969:   clear:both;
                   5970:   background: $sidebg;
                   5971:   border-bottom: 1px solid $lg_border_color;
                   5972:   line-height: 2.5em;
1.933     droeschl 5973:   overflow: hidden;
1.911     bisitz   5974:   margin: 0;
                   5975:   padding: 0;
1.995     raeburn  5976:   text-align: left;
1.819     tempelho 5977: }
1.862     bisitz   5978: 
1.1098    bisitz   5979: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5980:   clear:both;
                   5981:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5982:   border: 1px solid $sidebg;
1.1098    bisitz   5983:   margin: 0 0 10px 0;
1.966     bisitz   5984:   padding: 3px;
1.995     raeburn  5985:   text-align: left;
1.822     bisitz   5986: }
                   5987: 
1.795     www      5988: .LC_fontsize_medium {
1.911     bisitz   5989:   font-size: 85%;
1.705     tempelho 5990: }
                   5991: 
1.795     www      5992: .LC_fontsize_large {
1.911     bisitz   5993:   font-size: 120%;
1.705     tempelho 5994: }
                   5995: 
1.346     albertel 5996: .LC_menubuttons_inline_text {
                   5997:   color: $font;
1.698     harmsja  5998:   font-size: 90%;
1.701     harmsja  5999:   padding-left:3px;
1.346     albertel 6000: }
                   6001: 
1.934     droeschl 6002: .LC_menubuttons_inline_text img{
                   6003:   vertical-align: middle;
                   6004: }
                   6005: 
1.1051    www      6006: li.LC_menubuttons_inline_text img {
1.951     onken    6007:   cursor:pointer;
1.1002    droeschl 6008:   text-decoration: none;
1.951     onken    6009: }
                   6010: 
1.526     www      6011: .LC_menubuttons_link {
                   6012:   text-decoration: none;
                   6013: }
1.795     www      6014: 
1.522     albertel 6015: .LC_menubuttons_category {
1.521     www      6016:   color: $font;
1.526     www      6017:   background: $pgbg;
1.521     www      6018:   font-size: larger;
                   6019:   font-weight: bold;
                   6020: }
                   6021: 
1.346     albertel 6022: td.LC_menubuttons_text {
1.911     bisitz   6023:   color: $font;
1.346     albertel 6024: }
1.706     harmsja  6025: 
1.346     albertel 6026: .LC_current_location {
                   6027:   background: $tabbg;
                   6028: }
1.795     www      6029: 
1.938     bisitz   6030: table.LC_data_table {
1.347     albertel 6031:   border: 1px solid #000000;
1.402     albertel 6032:   border-collapse: separate;
1.426     albertel 6033:   border-spacing: 1px;
1.610     albertel 6034:   background: $pgbg;
1.347     albertel 6035: }
1.795     www      6036: 
1.422     albertel 6037: .LC_data_table_dense {
                   6038:   font-size: small;
                   6039: }
1.795     www      6040: 
1.507     raeburn  6041: table.LC_nested_outer {
                   6042:   border: 1px solid #000000;
1.589     raeburn  6043:   border-collapse: collapse;
1.803     bisitz   6044:   border-spacing: 0;
1.507     raeburn  6045:   width: 100%;
                   6046: }
1.795     www      6047: 
1.879     raeburn  6048: table.LC_innerpickbox,
1.507     raeburn  6049: table.LC_nested {
1.803     bisitz   6050:   border: none;
1.589     raeburn  6051:   border-collapse: collapse;
1.803     bisitz   6052:   border-spacing: 0;
1.507     raeburn  6053:   width: 100%;
                   6054: }
1.795     www      6055: 
1.911     bisitz   6056: table.LC_data_table tr th,
                   6057: table.LC_calendar tr th,
1.879     raeburn  6058: table.LC_prior_tries tr th,
                   6059: table.LC_innerpickbox tr th {
1.349     albertel 6060:   font-weight: bold;
                   6061:   background-color: $data_table_head;
1.801     tempelho 6062:   color:$fontmenu;
1.701     harmsja  6063:   font-size:90%;
1.347     albertel 6064: }
1.795     www      6065: 
1.879     raeburn  6066: table.LC_innerpickbox tr th,
                   6067: table.LC_innerpickbox tr td {
                   6068:   vertical-align: top;
                   6069: }
                   6070: 
1.711     raeburn  6071: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6072:   background-color: #CCCCCC;
1.711     raeburn  6073:   font-weight: bold;
                   6074:   text-align: left;
                   6075: }
1.795     www      6076: 
1.912     bisitz   6077: table.LC_data_table tr.LC_odd_row > td {
                   6078:   background-color: $data_table_light;
                   6079:   padding: 2px;
                   6080:   vertical-align: top;
                   6081: }
                   6082: 
1.809     bisitz   6083: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6084:   background-color: $data_table_light;
1.912     bisitz   6085:   vertical-align: top;
                   6086: }
                   6087: 
                   6088: table.LC_data_table tr.LC_even_row > td {
                   6089:   background-color: $data_table_dark;
1.425     albertel 6090:   padding: 2px;
1.900     bisitz   6091:   vertical-align: top;
1.347     albertel 6092: }
1.795     www      6093: 
1.809     bisitz   6094: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6095:   background-color: $data_table_dark;
1.900     bisitz   6096:   vertical-align: top;
1.347     albertel 6097: }
1.795     www      6098: 
1.425     albertel 6099: table.LC_data_table tr.LC_data_table_highlight td {
                   6100:   background-color: $data_table_darker;
                   6101: }
1.795     www      6102: 
1.639     raeburn  6103: table.LC_data_table tr td.LC_leftcol_header {
                   6104:   background-color: $data_table_head;
                   6105:   font-weight: bold;
                   6106: }
1.795     www      6107: 
1.451     albertel 6108: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6109: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6110:   font-weight: bold;
                   6111:   font-style: italic;
                   6112:   text-align: center;
                   6113:   padding: 8px;
1.347     albertel 6114: }
1.795     www      6115: 
1.1114    raeburn  6116: table.LC_data_table tr.LC_empty_row td,
                   6117: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6118:   background-color: $sidebg;
                   6119: }
                   6120: 
                   6121: table.LC_nested tr.LC_empty_row td {
                   6122:   background-color: #FFFFFF;
                   6123: }
                   6124: 
1.890     droeschl 6125: table.LC_caption {
                   6126: }
                   6127: 
1.507     raeburn  6128: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6129:   padding: 4ex
                   6130: }
1.795     www      6131: 
1.507     raeburn  6132: table.LC_nested_outer tr th {
                   6133:   font-weight: bold;
1.801     tempelho 6134:   color:$fontmenu;
1.507     raeburn  6135:   background-color: $data_table_head;
1.701     harmsja  6136:   font-size: small;
1.507     raeburn  6137:   border-bottom: 1px solid #000000;
                   6138: }
1.795     www      6139: 
1.507     raeburn  6140: table.LC_nested_outer tr td.LC_subheader {
                   6141:   background-color: $data_table_head;
                   6142:   font-weight: bold;
                   6143:   font-size: small;
                   6144:   border-bottom: 1px solid #000000;
                   6145:   text-align: right;
1.451     albertel 6146: }
1.795     www      6147: 
1.507     raeburn  6148: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6149:   background-color: #CCCCCC;
1.451     albertel 6150:   font-weight: bold;
                   6151:   font-size: small;
1.507     raeburn  6152:   text-align: center;
                   6153: }
1.795     www      6154: 
1.589     raeburn  6155: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6156: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6157:   text-align: left;
1.451     albertel 6158: }
1.795     www      6159: 
1.507     raeburn  6160: table.LC_nested td {
1.735     bisitz   6161:   background-color: #FFFFFF;
1.451     albertel 6162:   font-size: small;
1.507     raeburn  6163: }
1.795     www      6164: 
1.507     raeburn  6165: table.LC_nested_outer tr th.LC_right_item,
                   6166: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6167: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6168: table.LC_nested tr td.LC_right_item {
1.451     albertel 6169:   text-align: right;
                   6170: }
                   6171: 
1.507     raeburn  6172: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6173:   background-color: #EEEEEE;
1.451     albertel 6174: }
                   6175: 
1.473     raeburn  6176: table.LC_createuser {
                   6177: }
                   6178: 
                   6179: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6180:   font-size: small;
1.473     raeburn  6181: }
                   6182: 
                   6183: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6184:   background-color: #CCCCCC;
1.473     raeburn  6185:   font-weight: bold;
                   6186:   text-align: center;
                   6187: }
                   6188: 
1.349     albertel 6189: table.LC_calendar {
                   6190:   border: 1px solid #000000;
                   6191:   border-collapse: collapse;
1.917     raeburn  6192:   width: 98%;
1.349     albertel 6193: }
1.795     www      6194: 
1.349     albertel 6195: table.LC_calendar_pickdate {
                   6196:   font-size: xx-small;
                   6197: }
1.795     www      6198: 
1.349     albertel 6199: table.LC_calendar tr td {
                   6200:   border: 1px solid #000000;
                   6201:   vertical-align: top;
1.917     raeburn  6202:   width: 14%;
1.349     albertel 6203: }
1.795     www      6204: 
1.349     albertel 6205: table.LC_calendar tr td.LC_calendar_day_empty {
                   6206:   background-color: $data_table_dark;
                   6207: }
1.795     www      6208: 
1.779     bisitz   6209: table.LC_calendar tr td.LC_calendar_day_current {
                   6210:   background-color: $data_table_highlight;
1.777     tempelho 6211: }
1.795     www      6212: 
1.938     bisitz   6213: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6214:   background-color: $mail_new;
                   6215: }
1.795     www      6216: 
1.938     bisitz   6217: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6218:   background-color: $mail_new_hover;
                   6219: }
1.795     www      6220: 
1.938     bisitz   6221: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6222:   background-color: $mail_read;
                   6223: }
1.795     www      6224: 
1.938     bisitz   6225: /*
                   6226: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6227:   background-color: $mail_read_hover;
                   6228: }
1.938     bisitz   6229: */
1.795     www      6230: 
1.938     bisitz   6231: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6232:   background-color: $mail_replied;
                   6233: }
1.795     www      6234: 
1.938     bisitz   6235: /*
                   6236: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6237:   background-color: $mail_replied_hover;
                   6238: }
1.938     bisitz   6239: */
1.795     www      6240: 
1.938     bisitz   6241: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6242:   background-color: $mail_other;
                   6243: }
1.795     www      6244: 
1.938     bisitz   6245: /*
                   6246: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6247:   background-color: $mail_other_hover;
                   6248: }
1.938     bisitz   6249: */
1.494     raeburn  6250: 
1.777     tempelho 6251: table.LC_data_table tr > td.LC_browser_file,
                   6252: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6253:   background: #AAEE77;
1.389     albertel 6254: }
1.795     www      6255: 
1.777     tempelho 6256: table.LC_data_table tr > td.LC_browser_file_locked,
                   6257: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6258:   background: #FFAA99;
1.387     albertel 6259: }
1.795     www      6260: 
1.777     tempelho 6261: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6262:   background: #888888;
1.779     bisitz   6263: }
1.795     www      6264: 
1.777     tempelho 6265: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6266: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6267:   background: #F8F866;
1.777     tempelho 6268: }
1.795     www      6269: 
1.696     bisitz   6270: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6271:   background: #E0E8FF;
1.387     albertel 6272: }
1.696     bisitz   6273: 
1.707     bisitz   6274: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6275:   /* background: #77FF77; */
1.707     bisitz   6276: }
1.795     www      6277: 
1.707     bisitz   6278: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6279:   border-right: 8px solid #FFFF77;
1.707     bisitz   6280: }
1.795     www      6281: 
1.707     bisitz   6282: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6283:   border-right: 8px solid #FFAA77;
1.707     bisitz   6284: }
1.795     www      6285: 
1.707     bisitz   6286: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6287:   border-right: 8px solid #FF7777;
1.707     bisitz   6288: }
1.795     www      6289: 
1.707     bisitz   6290: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6291:   border-right: 8px solid #AAFF77;
1.707     bisitz   6292: }
1.795     www      6293: 
1.707     bisitz   6294: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6295:   border-right: 8px solid #11CC55;
1.707     bisitz   6296: }
                   6297: 
1.388     albertel 6298: span.LC_current_location {
1.701     harmsja  6299:   font-size:larger;
1.388     albertel 6300:   background: $pgbg;
                   6301: }
1.387     albertel 6302: 
1.1029    www      6303: span.LC_current_nav_location {
                   6304:   font-weight:bold;
                   6305:   background: $sidebg;
                   6306: }
                   6307: 
1.395     albertel 6308: span.LC_parm_menu_item {
                   6309:   font-size: larger;
                   6310: }
1.795     www      6311: 
1.395     albertel 6312: span.LC_parm_scope_all {
                   6313:   color: red;
                   6314: }
1.795     www      6315: 
1.395     albertel 6316: span.LC_parm_scope_folder {
                   6317:   color: green;
                   6318: }
1.795     www      6319: 
1.395     albertel 6320: span.LC_parm_scope_resource {
                   6321:   color: orange;
                   6322: }
1.795     www      6323: 
1.395     albertel 6324: span.LC_parm_part {
                   6325:   color: blue;
                   6326: }
1.795     www      6327: 
1.911     bisitz   6328: span.LC_parm_folder,
                   6329: span.LC_parm_symb {
1.395     albertel 6330:   font-size: x-small;
                   6331:   font-family: $mono;
                   6332:   color: #AAAAAA;
                   6333: }
                   6334: 
1.977     bisitz   6335: ul.LC_parm_parmlist li {
                   6336:   display: inline-block;
                   6337:   padding: 0.3em 0.8em;
                   6338:   vertical-align: top;
                   6339:   width: 150px;
                   6340:   border-top:1px solid $lg_border_color;
                   6341: }
                   6342: 
1.795     www      6343: td.LC_parm_overview_level_menu,
                   6344: td.LC_parm_overview_map_menu,
                   6345: td.LC_parm_overview_parm_selectors,
                   6346: td.LC_parm_overview_restrictions  {
1.396     albertel 6347:   border: 1px solid black;
                   6348:   border-collapse: collapse;
                   6349: }
1.795     www      6350: 
1.396     albertel 6351: table.LC_parm_overview_restrictions td {
                   6352:   border-width: 1px 4px 1px 4px;
                   6353:   border-style: solid;
                   6354:   border-color: $pgbg;
                   6355:   text-align: center;
                   6356: }
1.795     www      6357: 
1.396     albertel 6358: table.LC_parm_overview_restrictions th {
                   6359:   background: $tabbg;
                   6360:   border-width: 1px 4px 1px 4px;
                   6361:   border-style: solid;
                   6362:   border-color: $pgbg;
                   6363: }
1.795     www      6364: 
1.398     albertel 6365: table#LC_helpmenu {
1.803     bisitz   6366:   border: none;
1.398     albertel 6367:   height: 55px;
1.803     bisitz   6368:   border-spacing: 0;
1.398     albertel 6369: }
                   6370: 
                   6371: table#LC_helpmenu fieldset legend {
                   6372:   font-size: larger;
                   6373: }
1.795     www      6374: 
1.397     albertel 6375: table#LC_helpmenu_links {
                   6376:   width: 100%;
                   6377:   border: 1px solid black;
                   6378:   background: $pgbg;
1.803     bisitz   6379:   padding: 0;
1.397     albertel 6380:   border-spacing: 1px;
                   6381: }
1.795     www      6382: 
1.397     albertel 6383: table#LC_helpmenu_links tr td {
                   6384:   padding: 1px;
                   6385:   background: $tabbg;
1.399     albertel 6386:   text-align: center;
                   6387:   font-weight: bold;
1.397     albertel 6388: }
1.396     albertel 6389: 
1.795     www      6390: table#LC_helpmenu_links a:link,
                   6391: table#LC_helpmenu_links a:visited,
1.397     albertel 6392: table#LC_helpmenu_links a:active {
                   6393:   text-decoration: none;
                   6394:   color: $font;
                   6395: }
1.795     www      6396: 
1.397     albertel 6397: table#LC_helpmenu_links a:hover {
                   6398:   text-decoration: underline;
                   6399:   color: $vlink;
                   6400: }
1.396     albertel 6401: 
1.417     albertel 6402: .LC_chrt_popup_exists {
                   6403:   border: 1px solid #339933;
                   6404:   margin: -1px;
                   6405: }
1.795     www      6406: 
1.417     albertel 6407: .LC_chrt_popup_up {
                   6408:   border: 1px solid yellow;
                   6409:   margin: -1px;
                   6410: }
1.795     www      6411: 
1.417     albertel 6412: .LC_chrt_popup {
                   6413:   border: 1px solid #8888FF;
                   6414:   background: #CCCCFF;
                   6415: }
1.795     www      6416: 
1.421     albertel 6417: table.LC_pick_box {
                   6418:   border-collapse: separate;
                   6419:   background: white;
                   6420:   border: 1px solid black;
                   6421:   border-spacing: 1px;
                   6422: }
1.795     www      6423: 
1.421     albertel 6424: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6425:   background: $sidebg;
1.421     albertel 6426:   font-weight: bold;
1.900     bisitz   6427:   text-align: left;
1.740     bisitz   6428:   vertical-align: top;
1.421     albertel 6429:   width: 184px;
                   6430:   padding: 8px;
                   6431: }
1.795     www      6432: 
1.579     raeburn  6433: table.LC_pick_box td.LC_pick_box_value {
                   6434:   text-align: left;
                   6435:   padding: 8px;
                   6436: }
1.795     www      6437: 
1.579     raeburn  6438: table.LC_pick_box td.LC_pick_box_select {
                   6439:   text-align: left;
                   6440:   padding: 8px;
                   6441: }
1.795     www      6442: 
1.424     albertel 6443: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6444:   padding: 0;
1.421     albertel 6445:   height: 1px;
                   6446:   background: black;
                   6447: }
1.795     www      6448: 
1.421     albertel 6449: table.LC_pick_box td.LC_pick_box_submit {
                   6450:   text-align: right;
                   6451: }
1.795     www      6452: 
1.579     raeburn  6453: table.LC_pick_box td.LC_evenrow_value {
                   6454:   text-align: left;
                   6455:   padding: 8px;
                   6456:   background-color: $data_table_light;
                   6457: }
1.795     www      6458: 
1.579     raeburn  6459: table.LC_pick_box td.LC_oddrow_value {
                   6460:   text-align: left;
                   6461:   padding: 8px;
                   6462:   background-color: $data_table_light;
                   6463: }
1.795     www      6464: 
1.579     raeburn  6465: span.LC_helpform_receipt_cat {
                   6466:   font-weight: bold;
                   6467: }
1.795     www      6468: 
1.424     albertel 6469: table.LC_group_priv_box {
                   6470:   background: white;
                   6471:   border: 1px solid black;
                   6472:   border-spacing: 1px;
                   6473: }
1.795     www      6474: 
1.424     albertel 6475: table.LC_group_priv_box td.LC_pick_box_title {
                   6476:   background: $tabbg;
                   6477:   font-weight: bold;
                   6478:   text-align: right;
                   6479:   width: 184px;
                   6480: }
1.795     www      6481: 
1.424     albertel 6482: table.LC_group_priv_box td.LC_groups_fixed {
                   6483:   background: $data_table_light;
                   6484:   text-align: center;
                   6485: }
1.795     www      6486: 
1.424     albertel 6487: table.LC_group_priv_box td.LC_groups_optional {
                   6488:   background: $data_table_dark;
                   6489:   text-align: center;
                   6490: }
1.795     www      6491: 
1.424     albertel 6492: table.LC_group_priv_box td.LC_groups_functionality {
                   6493:   background: $data_table_darker;
                   6494:   text-align: center;
                   6495:   font-weight: bold;
                   6496: }
1.795     www      6497: 
1.424     albertel 6498: table.LC_group_priv td {
                   6499:   text-align: left;
1.803     bisitz   6500:   padding: 0;
1.424     albertel 6501: }
                   6502: 
                   6503: .LC_navbuttons {
                   6504:   margin: 2ex 0ex 2ex 0ex;
                   6505: }
1.795     www      6506: 
1.423     albertel 6507: .LC_topic_bar {
                   6508:   font-weight: bold;
                   6509:   background: $tabbg;
1.918     wenzelju 6510:   margin: 1em 0em 1em 2em;
1.805     bisitz   6511:   padding: 3px;
1.918     wenzelju 6512:   font-size: 1.2em;
1.423     albertel 6513: }
1.795     www      6514: 
1.423     albertel 6515: .LC_topic_bar span {
1.918     wenzelju 6516:   left: 0.5em;
                   6517:   position: absolute;
1.423     albertel 6518:   vertical-align: middle;
1.918     wenzelju 6519:   font-size: 1.2em;
1.423     albertel 6520: }
1.795     www      6521: 
1.423     albertel 6522: table.LC_course_group_status {
                   6523:   margin: 20px;
                   6524: }
1.795     www      6525: 
1.423     albertel 6526: table.LC_status_selector td {
                   6527:   vertical-align: top;
                   6528:   text-align: center;
1.424     albertel 6529:   padding: 4px;
                   6530: }
1.795     www      6531: 
1.599     albertel 6532: div.LC_feedback_link {
1.616     albertel 6533:   clear: both;
1.829     kalberla 6534:   background: $sidebg;
1.779     bisitz   6535:   width: 100%;
1.829     kalberla 6536:   padding-bottom: 10px;
                   6537:   border: 1px $tabbg solid;
1.833     kalberla 6538:   height: 22px;
                   6539:   line-height: 22px;
                   6540:   padding-top: 5px;
                   6541: }
                   6542: 
                   6543: div.LC_feedback_link img {
                   6544:   height: 22px;
1.867     kalberla 6545:   vertical-align:middle;
1.829     kalberla 6546: }
                   6547: 
1.911     bisitz   6548: div.LC_feedback_link a {
1.829     kalberla 6549:   text-decoration: none;
1.489     raeburn  6550: }
1.795     www      6551: 
1.867     kalberla 6552: div.LC_comblock {
1.911     bisitz   6553:   display:inline;
1.867     kalberla 6554:   color:$font;
                   6555:   font-size:90%;
                   6556: }
                   6557: 
                   6558: div.LC_feedback_link div.LC_comblock {
                   6559:   padding-left:5px;
                   6560: }
                   6561: 
                   6562: div.LC_feedback_link div.LC_comblock a {
                   6563:   color:$font;
                   6564: }
                   6565: 
1.489     raeburn  6566: span.LC_feedback_link {
1.858     bisitz   6567:   /* background: $feedback_link_bg; */
1.599     albertel 6568:   font-size: larger;
                   6569: }
1.795     www      6570: 
1.599     albertel 6571: span.LC_message_link {
1.858     bisitz   6572:   /* background: $feedback_link_bg; */
1.599     albertel 6573:   font-size: larger;
                   6574:   position: absolute;
                   6575:   right: 1em;
1.489     raeburn  6576: }
1.421     albertel 6577: 
1.515     albertel 6578: table.LC_prior_tries {
1.524     albertel 6579:   border: 1px solid #000000;
                   6580:   border-collapse: separate;
                   6581:   border-spacing: 1px;
1.515     albertel 6582: }
1.523     albertel 6583: 
1.515     albertel 6584: table.LC_prior_tries td {
1.524     albertel 6585:   padding: 2px;
1.515     albertel 6586: }
1.523     albertel 6587: 
                   6588: .LC_answer_correct {
1.795     www      6589:   background: lightgreen;
                   6590:   color: darkgreen;
                   6591:   padding: 6px;
1.523     albertel 6592: }
1.795     www      6593: 
1.523     albertel 6594: .LC_answer_charged_try {
1.797     www      6595:   background: #FFAAAA;
1.795     www      6596:   color: darkred;
                   6597:   padding: 6px;
1.523     albertel 6598: }
1.795     www      6599: 
1.779     bisitz   6600: .LC_answer_not_charged_try,
1.523     albertel 6601: .LC_answer_no_grade,
                   6602: .LC_answer_late {
1.795     www      6603:   background: lightyellow;
1.523     albertel 6604:   color: black;
1.795     www      6605:   padding: 6px;
1.523     albertel 6606: }
1.795     www      6607: 
1.523     albertel 6608: .LC_answer_previous {
1.795     www      6609:   background: lightblue;
                   6610:   color: darkblue;
                   6611:   padding: 6px;
1.523     albertel 6612: }
1.795     www      6613: 
1.779     bisitz   6614: .LC_answer_no_message {
1.777     tempelho 6615:   background: #FFFFFF;
                   6616:   color: black;
1.795     www      6617:   padding: 6px;
1.779     bisitz   6618: }
1.795     www      6619: 
1.779     bisitz   6620: .LC_answer_unknown {
                   6621:   background: orange;
                   6622:   color: black;
1.795     www      6623:   padding: 6px;
1.777     tempelho 6624: }
1.795     www      6625: 
1.529     albertel 6626: span.LC_prior_numerical,
                   6627: span.LC_prior_string,
                   6628: span.LC_prior_custom,
                   6629: span.LC_prior_reaction,
                   6630: span.LC_prior_math {
1.925     bisitz   6631:   font-family: $mono;
1.523     albertel 6632:   white-space: pre;
                   6633: }
                   6634: 
1.525     albertel 6635: span.LC_prior_string {
1.925     bisitz   6636:   font-family: $mono;
1.525     albertel 6637:   white-space: pre;
                   6638: }
                   6639: 
1.523     albertel 6640: table.LC_prior_option {
                   6641:   width: 100%;
                   6642:   border-collapse: collapse;
                   6643: }
1.795     www      6644: 
1.911     bisitz   6645: table.LC_prior_rank,
1.795     www      6646: table.LC_prior_match {
1.528     albertel 6647:   border-collapse: collapse;
                   6648: }
1.795     www      6649: 
1.528     albertel 6650: table.LC_prior_option tr td,
                   6651: table.LC_prior_rank tr td,
                   6652: table.LC_prior_match tr td {
1.524     albertel 6653:   border: 1px solid #000000;
1.515     albertel 6654: }
                   6655: 
1.855     bisitz   6656: .LC_nobreak {
1.544     albertel 6657:   white-space: nowrap;
1.519     raeburn  6658: }
                   6659: 
1.576     raeburn  6660: span.LC_cusr_emph {
                   6661:   font-style: italic;
                   6662: }
                   6663: 
1.633     raeburn  6664: span.LC_cusr_subheading {
                   6665:   font-weight: normal;
                   6666:   font-size: 85%;
                   6667: }
                   6668: 
1.861     bisitz   6669: div.LC_docs_entry_move {
1.859     bisitz   6670:   border: 1px solid #BBBBBB;
1.545     albertel 6671:   background: #DDDDDD;
1.861     bisitz   6672:   width: 22px;
1.859     bisitz   6673:   padding: 1px;
                   6674:   margin: 0;
1.545     albertel 6675: }
                   6676: 
1.861     bisitz   6677: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6678: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6679:   font-size: x-small;
                   6680: }
1.795     www      6681: 
1.861     bisitz   6682: .LC_docs_entry_parameter {
                   6683:   white-space: nowrap;
                   6684: }
                   6685: 
1.544     albertel 6686: .LC_docs_copy {
1.545     albertel 6687:   color: #000099;
1.544     albertel 6688: }
1.795     www      6689: 
1.544     albertel 6690: .LC_docs_cut {
1.545     albertel 6691:   color: #550044;
1.544     albertel 6692: }
1.795     www      6693: 
1.544     albertel 6694: .LC_docs_rename {
1.545     albertel 6695:   color: #009900;
1.544     albertel 6696: }
1.795     www      6697: 
1.544     albertel 6698: .LC_docs_remove {
1.545     albertel 6699:   color: #990000;
                   6700: }
                   6701: 
1.547     albertel 6702: .LC_docs_reinit_warn,
                   6703: .LC_docs_ext_edit {
                   6704:   font-size: x-small;
                   6705: }
                   6706: 
1.545     albertel 6707: table.LC_docs_adddocs td,
                   6708: table.LC_docs_adddocs th {
                   6709:   border: 1px solid #BBBBBB;
                   6710:   padding: 4px;
                   6711:   background: #DDDDDD;
1.543     albertel 6712: }
                   6713: 
1.584     albertel 6714: table.LC_sty_begin {
                   6715:   background: #BBFFBB;
                   6716: }
1.795     www      6717: 
1.584     albertel 6718: table.LC_sty_end {
                   6719:   background: #FFBBBB;
                   6720: }
                   6721: 
1.589     raeburn  6722: table.LC_double_column {
1.803     bisitz   6723:   border-width: 0;
1.589     raeburn  6724:   border-collapse: collapse;
                   6725:   width: 100%;
                   6726:   padding: 2px;
                   6727: }
                   6728: 
                   6729: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6730:   top: 2px;
1.589     raeburn  6731:   left: 2px;
                   6732:   width: 47%;
                   6733:   vertical-align: top;
                   6734: }
                   6735: 
                   6736: table.LC_double_column tr td.LC_right_col {
                   6737:   top: 2px;
1.779     bisitz   6738:   right: 2px;
1.589     raeburn  6739:   width: 47%;
                   6740:   vertical-align: top;
                   6741: }
                   6742: 
1.591     raeburn  6743: div.LC_left_float {
                   6744:   float: left;
                   6745:   padding-right: 5%;
1.597     albertel 6746:   padding-bottom: 4px;
1.591     raeburn  6747: }
                   6748: 
                   6749: div.LC_clear_float_header {
1.597     albertel 6750:   padding-bottom: 2px;
1.591     raeburn  6751: }
                   6752: 
                   6753: div.LC_clear_float_footer {
1.597     albertel 6754:   padding-top: 10px;
1.591     raeburn  6755:   clear: both;
                   6756: }
                   6757: 
1.597     albertel 6758: div.LC_grade_show_user {
1.941     bisitz   6759: /*  border-left: 5px solid $sidebg; */
                   6760:   border-top: 5px solid #000000;
                   6761:   margin: 50px 0 0 0;
1.936     bisitz   6762:   padding: 15px 0 5px 10px;
1.597     albertel 6763: }
1.795     www      6764: 
1.936     bisitz   6765: div.LC_grade_show_user_odd_row {
1.941     bisitz   6766: /*  border-left: 5px solid #000000; */
                   6767: }
                   6768: 
                   6769: div.LC_grade_show_user div.LC_Box {
                   6770:   margin-right: 50px;
1.597     albertel 6771: }
                   6772: 
                   6773: div.LC_grade_submissions,
                   6774: div.LC_grade_message_center,
1.936     bisitz   6775: div.LC_grade_info_links {
1.597     albertel 6776:   margin: 5px;
                   6777:   width: 99%;
                   6778:   background: #FFFFFF;
                   6779: }
1.795     www      6780: 
1.597     albertel 6781: div.LC_grade_submissions_header,
1.936     bisitz   6782: div.LC_grade_message_center_header {
1.705     tempelho 6783:   font-weight: bold;
                   6784:   font-size: large;
1.597     albertel 6785: }
1.795     www      6786: 
1.597     albertel 6787: div.LC_grade_submissions_body,
1.936     bisitz   6788: div.LC_grade_message_center_body {
1.597     albertel 6789:   border: 1px solid black;
                   6790:   width: 99%;
                   6791:   background: #FFFFFF;
                   6792: }
1.795     www      6793: 
1.613     albertel 6794: table.LC_scantron_action {
                   6795:   width: 100%;
                   6796: }
1.795     www      6797: 
1.613     albertel 6798: table.LC_scantron_action tr th {
1.698     harmsja  6799:   font-weight:bold;
                   6800:   font-style:normal;
1.613     albertel 6801: }
1.795     www      6802: 
1.779     bisitz   6803: .LC_edit_problem_header,
1.614     albertel 6804: div.LC_edit_problem_footer {
1.705     tempelho 6805:   font-weight: normal;
                   6806:   font-size:  medium;
1.602     albertel 6807:   margin: 2px;
1.1060    bisitz   6808:   background-color: $sidebg;
1.600     albertel 6809: }
1.795     www      6810: 
1.600     albertel 6811: div.LC_edit_problem_header,
1.602     albertel 6812: div.LC_edit_problem_header div,
1.614     albertel 6813: div.LC_edit_problem_footer,
                   6814: div.LC_edit_problem_footer div,
1.602     albertel 6815: div.LC_edit_problem_editxml_header,
                   6816: div.LC_edit_problem_editxml_header div {
1.600     albertel 6817:   margin-top: 5px;
1.1205    golterma 6818:   z-index: 100;
1.600     albertel 6819: }
1.795     www      6820: 
1.600     albertel 6821: div.LC_edit_problem_header_title {
1.705     tempelho 6822:   font-weight: bold;
                   6823:   font-size: larger;
1.602     albertel 6824:   background: $tabbg;
                   6825:   padding: 3px;
1.1060    bisitz   6826:   margin: 0 0 5px 0;
1.602     albertel 6827: }
1.795     www      6828: 
1.602     albertel 6829: table.LC_edit_problem_header_title {
                   6830:   width: 100%;
1.600     albertel 6831:   background: $tabbg;
1.602     albertel 6832: }
                   6833: 
                   6834: div.LC_edit_problem_discards {
                   6835:   float: left;
1.1205    golterma 6836: }
                   6837: 
                   6838: div.LC_edit_actionbar {
                   6839:     margin: -5px 0px 0px 0px !important;
                   6840:     background-color: $sidebg;
1.1216    droeschl 6841:     height: 35px;
1.602     albertel 6842: }
1.795     www      6843: 
1.602     albertel 6844: div.LC_edit_problem_saves {
                   6845:   float: right;
                   6846:   padding-bottom: 5px;
1.600     albertel 6847: }
1.795     www      6848: 
1.1124    bisitz   6849: .LC_edit_opt {
                   6850:   padding-left: 1em;
                   6851:   white-space: nowrap;
                   6852: }
                   6853: 
1.1152    golterma 6854: .LC_edit_problem_latexhelper{
                   6855:     text-align: right;
                   6856: }
                   6857: 
                   6858: #LC_edit_problem_colorful div{
                   6859:     margin-left: 40px;
                   6860: }
                   6861: 
1.1205    golterma 6862: #LC_edit_problem_codemirror div{
                   6863:     margin-left: 0px;
                   6864: }
                   6865: 
1.911     bisitz   6866: img.stift {
1.803     bisitz   6867:   border-width: 0;
                   6868:   vertical-align: middle;
1.677     riegler  6869: }
1.680     riegler  6870: 
1.923     bisitz   6871: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6872:   vertical-align: top;
1.777     tempelho 6873: }
1.795     www      6874: 
1.716     raeburn  6875: div.LC_createcourse {
1.911     bisitz   6876:   margin: 10px 10px 10px 10px;
1.716     raeburn  6877: }
                   6878: 
1.917     raeburn  6879: .LC_dccid {
1.1130    raeburn  6880:   float: right;
1.917     raeburn  6881:   margin: 0.2em 0 0 0;
                   6882:   padding: 0;
                   6883:   font-size: 90%;
                   6884:   display:none;
                   6885: }
                   6886: 
1.897     wenzelju 6887: ol.LC_primary_menu a:hover,
1.721     harmsja  6888: ol#LC_MenuBreadcrumbs a:hover,
                   6889: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6890: ul#LC_secondary_menu a:hover,
1.721     harmsja  6891: .LC_FormSectionClearButton input:hover
1.795     www      6892: ul.LC_TabContent   li:hover a {
1.952     onken    6893:   color:$button_hover;
1.911     bisitz   6894:   text-decoration:none;
1.693     droeschl 6895: }
                   6896: 
1.779     bisitz   6897: h1 {
1.911     bisitz   6898:   padding: 0;
                   6899:   line-height:130%;
1.693     droeschl 6900: }
1.698     harmsja  6901: 
1.911     bisitz   6902: h2,
                   6903: h3,
                   6904: h4,
                   6905: h5,
                   6906: h6 {
                   6907:   margin: 5px 0 5px 0;
                   6908:   padding: 0;
                   6909:   line-height:130%;
1.693     droeschl 6910: }
1.795     www      6911: 
                   6912: .LC_hcell {
1.911     bisitz   6913:   padding:3px 15px 3px 15px;
                   6914:   margin: 0;
                   6915:   background-color:$tabbg;
                   6916:   color:$fontmenu;
                   6917:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6918: }
1.795     www      6919: 
1.840     bisitz   6920: .LC_Box > .LC_hcell {
1.911     bisitz   6921:   margin: 0 -10px 10px -10px;
1.835     bisitz   6922: }
                   6923: 
1.721     harmsja  6924: .LC_noBorder {
1.911     bisitz   6925:   border: 0;
1.698     harmsja  6926: }
1.693     droeschl 6927: 
1.721     harmsja  6928: .LC_FormSectionClearButton input {
1.911     bisitz   6929:   background-color:transparent;
                   6930:   border: none;
                   6931:   cursor:pointer;
                   6932:   text-decoration:underline;
1.693     droeschl 6933: }
1.763     bisitz   6934: 
                   6935: .LC_help_open_topic {
1.911     bisitz   6936:   color: #FFFFFF;
                   6937:   background-color: #EEEEFF;
                   6938:   margin: 1px;
                   6939:   padding: 4px;
                   6940:   border: 1px solid #000033;
                   6941:   white-space: nowrap;
                   6942:   /* vertical-align: middle; */
1.759     neumanie 6943: }
1.693     droeschl 6944: 
1.911     bisitz   6945: dl,
                   6946: ul,
                   6947: div,
                   6948: fieldset {
                   6949:   margin: 10px 10px 10px 0;
                   6950:   /* overflow: hidden; */
1.693     droeschl 6951: }
1.795     www      6952: 
1.1211    raeburn  6953: article.geogebraweb div {
                   6954:     margin: 0;
                   6955: }
                   6956: 
1.838     bisitz   6957: fieldset > legend {
1.911     bisitz   6958:   font-weight: bold;
                   6959:   padding: 0 5px 0 5px;
1.838     bisitz   6960: }
                   6961: 
1.813     bisitz   6962: #LC_nav_bar {
1.911     bisitz   6963:   float: left;
1.995     raeburn  6964:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6965:   margin: 0 0 2px 0;
1.807     droeschl 6966: }
                   6967: 
1.916     droeschl 6968: #LC_realm {
                   6969:   margin: 0.2em 0 0 0;
                   6970:   padding: 0;
                   6971:   font-weight: bold;
                   6972:   text-align: center;
1.995     raeburn  6973:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6974: }
                   6975: 
1.911     bisitz   6976: #LC_nav_bar em {
                   6977:   font-weight: bold;
                   6978:   font-style: normal;
1.807     droeschl 6979: }
                   6980: 
1.897     wenzelju 6981: ol.LC_primary_menu {
1.934     droeschl 6982:   margin: 0;
1.1076    raeburn  6983:   padding: 0;
1.807     droeschl 6984: }
                   6985: 
1.852     droeschl 6986: ol#LC_PathBreadcrumbs {
1.911     bisitz   6987:   margin: 0;
1.693     droeschl 6988: }
                   6989: 
1.897     wenzelju 6990: ol.LC_primary_menu li {
1.1076    raeburn  6991:   color: RGB(80, 80, 80);
                   6992:   vertical-align: middle;
                   6993:   text-align: left;
                   6994:   list-style: none;
1.1205    golterma 6995:   position: relative;
1.1076    raeburn  6996:   float: left;
1.1205    golterma 6997:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   6998:   line-height: 1.5em;
1.1076    raeburn  6999: }
                   7000: 
1.1205    golterma 7001: ol.LC_primary_menu li a,
                   7002: ol.LC_primary_menu li p {
1.1076    raeburn  7003:   display: block;
                   7004:   margin: 0;
                   7005:   padding: 0 5px 0 10px;
                   7006:   text-decoration: none;
                   7007: }
                   7008: 
1.1205    golterma 7009: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7010:   display: inline-block;
                   7011:   width: 95%;
                   7012:   text-align: left;
                   7013: }
                   7014: 
                   7015: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7016:   display: inline-block;	
                   7017:   width: 5%;
                   7018:   float: right;
                   7019:   text-align: right;
                   7020:   font-size: 70%;
                   7021: }
                   7022: 
                   7023: ol.LC_primary_menu ul {
1.1076    raeburn  7024:   display: none;
1.1205    golterma 7025:   width: 15em;
1.1076    raeburn  7026:   background-color: $data_table_light;
1.1205    golterma 7027:   position: absolute;
                   7028:   top: 100%;
1.1076    raeburn  7029: }
                   7030: 
1.1205    golterma 7031: ol.LC_primary_menu ul ul {
                   7032:   left: 100%;
                   7033:   top: 0;
                   7034: }
                   7035: 
                   7036: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7037:   display: block;
                   7038:   position: absolute;
                   7039:   margin: 0;
                   7040:   padding: 0;
1.1078    raeburn  7041:   z-index: 2;
1.1076    raeburn  7042: }
                   7043: 
                   7044: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7045: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7046:   font-size: 90%;
1.911     bisitz   7047:   vertical-align: top;
1.1076    raeburn  7048:   float: none;
1.1079    raeburn  7049:   border-left: 1px solid black;
                   7050:   border-right: 1px solid black;
1.1205    golterma 7051: /* A dark bottom border to visualize different menu options; 
                   7052: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7053:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7054: }
                   7055: 
1.1205    golterma 7056: ol.LC_primary_menu li li p:hover {
                   7057:   color:$button_hover;
                   7058:   text-decoration:none;
                   7059:   background-color:$data_table_dark;
1.1076    raeburn  7060: }
                   7061: 
                   7062: ol.LC_primary_menu li li a:hover {
                   7063:    color:$button_hover;
                   7064:    background-color:$data_table_dark;
1.693     droeschl 7065: }
                   7066: 
1.1205    golterma 7067: /* Font-size equal to the size of the predecessors*/
                   7068: ol.LC_primary_menu li:hover li li {
                   7069:   font-size: 100%;
                   7070: }
                   7071: 
1.897     wenzelju 7072: ol.LC_primary_menu li img {
1.911     bisitz   7073:   vertical-align: bottom;
1.934     droeschl 7074:   height: 1.1em;
1.1077    raeburn  7075:   margin: 0.2em 0 0 0;
1.693     droeschl 7076: }
                   7077: 
1.897     wenzelju 7078: ol.LC_primary_menu a {
1.911     bisitz   7079:   color: RGB(80, 80, 80);
                   7080:   text-decoration: none;
1.693     droeschl 7081: }
1.795     www      7082: 
1.949     droeschl 7083: ol.LC_primary_menu a.LC_new_message {
                   7084:   font-weight:bold;
                   7085:   color: darkred;
                   7086: }
                   7087: 
1.975     raeburn  7088: ol.LC_docs_parameters {
                   7089:   margin-left: 0;
                   7090:   padding: 0;
                   7091:   list-style: none;
                   7092: }
                   7093: 
                   7094: ol.LC_docs_parameters li {
                   7095:   margin: 0;
                   7096:   padding-right: 20px;
                   7097:   display: inline;
                   7098: }
                   7099: 
1.976     raeburn  7100: ol.LC_docs_parameters li:before {
                   7101:   content: "\\002022 \\0020";
                   7102: }
                   7103: 
                   7104: li.LC_docs_parameters_title {
                   7105:   font-weight: bold;
                   7106: }
                   7107: 
                   7108: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7109:   content: "";
                   7110: }
                   7111: 
1.897     wenzelju 7112: ul#LC_secondary_menu {
1.1107    raeburn  7113:   clear: right;
1.911     bisitz   7114:   color: $fontmenu;
                   7115:   background: $tabbg;
                   7116:   list-style: none;
                   7117:   padding: 0;
                   7118:   margin: 0;
                   7119:   width: 100%;
1.995     raeburn  7120:   text-align: left;
1.1107    raeburn  7121:   float: left;
1.808     droeschl 7122: }
                   7123: 
1.897     wenzelju 7124: ul#LC_secondary_menu li {
1.911     bisitz   7125:   font-weight: bold;
                   7126:   line-height: 1.8em;
1.1107    raeburn  7127:   border-right: 1px solid black;
                   7128:   float: left;
                   7129: }
                   7130: 
                   7131: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7132:   background-color: $data_table_light;
                   7133: }
                   7134: 
                   7135: ul#LC_secondary_menu li a {
1.911     bisitz   7136:   padding: 0 0.8em;
1.1107    raeburn  7137: }
                   7138: 
                   7139: ul#LC_secondary_menu li ul {
                   7140:   display: none;
                   7141: }
                   7142: 
                   7143: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7144:   display: block;
                   7145:   position: absolute;
                   7146:   margin: 0;
                   7147:   padding: 0;
                   7148:   list-style:none;
                   7149:   float: none;
                   7150:   background-color: $data_table_light;
                   7151:   z-index: 2;
                   7152:   margin-left: -1px;
                   7153: }
                   7154: 
                   7155: ul#LC_secondary_menu li ul li {
                   7156:   font-size: 90%;
                   7157:   vertical-align: top;
                   7158:   border-left: 1px solid black;
1.911     bisitz   7159:   border-right: 1px solid black;
1.1119    raeburn  7160:   background-color: $data_table_light;
1.1107    raeburn  7161:   list-style:none;
                   7162:   float: none;
                   7163: }
                   7164: 
                   7165: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7166:   background-color: $data_table_dark;
1.807     droeschl 7167: }
                   7168: 
1.847     tempelho 7169: ul.LC_TabContent {
1.911     bisitz   7170:   display:block;
                   7171:   background: $sidebg;
                   7172:   border-bottom: solid 1px $lg_border_color;
                   7173:   list-style:none;
1.1020    raeburn  7174:   margin: -1px -10px 0 -10px;
1.911     bisitz   7175:   padding: 0;
1.693     droeschl 7176: }
                   7177: 
1.795     www      7178: ul.LC_TabContent li,
                   7179: ul.LC_TabContentBigger li {
1.911     bisitz   7180:   float:left;
1.741     harmsja  7181: }
1.795     www      7182: 
1.897     wenzelju 7183: ul#LC_secondary_menu li a {
1.911     bisitz   7184:   color: $fontmenu;
                   7185:   text-decoration: none;
1.693     droeschl 7186: }
1.795     www      7187: 
1.721     harmsja  7188: ul.LC_TabContent {
1.952     onken    7189:   min-height:20px;
1.721     harmsja  7190: }
1.795     www      7191: 
                   7192: ul.LC_TabContent li {
1.911     bisitz   7193:   vertical-align:middle;
1.959     onken    7194:   padding: 0 16px 0 10px;
1.911     bisitz   7195:   background-color:$tabbg;
                   7196:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7197:   border-left: solid 1px $font;
1.721     harmsja  7198: }
1.795     www      7199: 
1.847     tempelho 7200: ul.LC_TabContent .right {
1.911     bisitz   7201:   float:right;
1.847     tempelho 7202: }
                   7203: 
1.911     bisitz   7204: ul.LC_TabContent li a,
                   7205: ul.LC_TabContent li {
                   7206:   color:rgb(47,47,47);
                   7207:   text-decoration:none;
                   7208:   font-size:95%;
                   7209:   font-weight:bold;
1.952     onken    7210:   min-height:20px;
                   7211: }
                   7212: 
1.959     onken    7213: ul.LC_TabContent li a:hover,
                   7214: ul.LC_TabContent li a:focus {
1.952     onken    7215:   color: $button_hover;
1.959     onken    7216:   background:none;
                   7217:   outline:none;
1.952     onken    7218: }
                   7219: 
                   7220: ul.LC_TabContent li:hover {
                   7221:   color: $button_hover;
                   7222:   cursor:pointer;
1.721     harmsja  7223: }
1.795     www      7224: 
1.911     bisitz   7225: ul.LC_TabContent li.active {
1.952     onken    7226:   color: $font;
1.911     bisitz   7227:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7228:   border-bottom:solid 1px #FFFFFF;
                   7229:   cursor: default;
1.744     ehlerst  7230: }
1.795     www      7231: 
1.959     onken    7232: ul.LC_TabContent li.active a {
                   7233:   color:$font;
                   7234:   background:#FFFFFF;
                   7235:   outline: none;
                   7236: }
1.1047    raeburn  7237: 
                   7238: ul.LC_TabContent li.goback {
                   7239:   float: left;
                   7240:   border-left: none;
                   7241: }
                   7242: 
1.870     tempelho 7243: #maincoursedoc {
1.911     bisitz   7244:   clear:both;
1.870     tempelho 7245: }
                   7246: 
                   7247: ul.LC_TabContentBigger {
1.911     bisitz   7248:   display:block;
                   7249:   list-style:none;
                   7250:   padding: 0;
1.870     tempelho 7251: }
                   7252: 
1.795     www      7253: ul.LC_TabContentBigger li {
1.911     bisitz   7254:   vertical-align:bottom;
                   7255:   height: 30px;
                   7256:   font-size:110%;
                   7257:   font-weight:bold;
                   7258:   color: #737373;
1.841     tempelho 7259: }
                   7260: 
1.957     onken    7261: ul.LC_TabContentBigger li.active {
                   7262:   position: relative;
                   7263:   top: 1px;
                   7264: }
                   7265: 
1.870     tempelho 7266: ul.LC_TabContentBigger li a {
1.911     bisitz   7267:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7268:   height: 30px;
                   7269:   line-height: 30px;
                   7270:   text-align: center;
                   7271:   display: block;
                   7272:   text-decoration: none;
1.958     onken    7273:   outline: none;  
1.741     harmsja  7274: }
1.795     www      7275: 
1.870     tempelho 7276: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7277:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7278:   color:$font;
1.744     ehlerst  7279: }
1.795     www      7280: 
1.870     tempelho 7281: ul.LC_TabContentBigger li b {
1.911     bisitz   7282:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7283:   display: block;
                   7284:   float: left;
                   7285:   padding: 0 30px;
1.957     onken    7286:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7287: }
                   7288: 
1.956     onken    7289: ul.LC_TabContentBigger li:hover b {
                   7290:   color:$button_hover;
                   7291: }
                   7292: 
1.870     tempelho 7293: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7294:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7295:   color:$font;
1.957     onken    7296:   border: 0;
1.741     harmsja  7297: }
1.693     droeschl 7298: 
1.870     tempelho 7299: 
1.862     bisitz   7300: ul.LC_CourseBreadcrumbs {
                   7301:   background: $sidebg;
1.1020    raeburn  7302:   height: 2em;
1.862     bisitz   7303:   padding-left: 10px;
1.1020    raeburn  7304:   margin: 0;
1.862     bisitz   7305:   list-style-position: inside;
                   7306: }
                   7307: 
1.911     bisitz   7308: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7309: ol#LC_PathBreadcrumbs {
1.911     bisitz   7310:   padding-left: 10px;
                   7311:   margin: 0;
1.933     droeschl 7312:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7313: }
                   7314: 
1.911     bisitz   7315: ol#LC_MenuBreadcrumbs li,
                   7316: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7317: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7318:   display: inline;
1.933     droeschl 7319:   white-space: normal;  
1.693     droeschl 7320: }
                   7321: 
1.823     bisitz   7322: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7323: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7324:   text-decoration: none;
                   7325:   font-size:90%;
1.693     droeschl 7326: }
1.795     www      7327: 
1.969     droeschl 7328: ol#LC_MenuBreadcrumbs h1 {
                   7329:   display: inline;
                   7330:   font-size: 90%;
                   7331:   line-height: 2.5em;
                   7332:   margin: 0;
                   7333:   padding: 0;
                   7334: }
                   7335: 
1.795     www      7336: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7337:   text-decoration:none;
                   7338:   font-size:100%;
                   7339:   font-weight:bold;
1.693     droeschl 7340: }
1.795     www      7341: 
1.840     bisitz   7342: .LC_Box {
1.911     bisitz   7343:   border: solid 1px $lg_border_color;
                   7344:   padding: 0 10px 10px 10px;
1.746     neumanie 7345: }
1.795     www      7346: 
1.1020    raeburn  7347: .LC_DocsBox {
                   7348:   border: solid 1px $lg_border_color;
                   7349:   padding: 0 0 10px 10px;
                   7350: }
                   7351: 
1.795     www      7352: .LC_AboutMe_Image {
1.911     bisitz   7353:   float:left;
                   7354:   margin-right:10px;
1.747     neumanie 7355: }
1.795     www      7356: 
                   7357: .LC_Clear_AboutMe_Image {
1.911     bisitz   7358:   clear:left;
1.747     neumanie 7359: }
1.795     www      7360: 
1.721     harmsja  7361: dl.LC_ListStyleClean dt {
1.911     bisitz   7362:   padding-right: 5px;
                   7363:   display: table-header-group;
1.693     droeschl 7364: }
                   7365: 
1.721     harmsja  7366: dl.LC_ListStyleClean dd {
1.911     bisitz   7367:   display: table-row;
1.693     droeschl 7368: }
                   7369: 
1.721     harmsja  7370: .LC_ListStyleClean,
                   7371: .LC_ListStyleSimple,
                   7372: .LC_ListStyleNormal,
1.795     www      7373: .LC_ListStyleSpecial {
1.911     bisitz   7374:   /* display:block; */
                   7375:   list-style-position: inside;
                   7376:   list-style-type: none;
                   7377:   overflow: hidden;
                   7378:   padding: 0;
1.693     droeschl 7379: }
                   7380: 
1.721     harmsja  7381: .LC_ListStyleSimple li,
                   7382: .LC_ListStyleSimple dd,
                   7383: .LC_ListStyleNormal li,
                   7384: .LC_ListStyleNormal dd,
                   7385: .LC_ListStyleSpecial li,
1.795     www      7386: .LC_ListStyleSpecial dd {
1.911     bisitz   7387:   margin: 0;
                   7388:   padding: 5px 5px 5px 10px;
                   7389:   clear: both;
1.693     droeschl 7390: }
                   7391: 
1.721     harmsja  7392: .LC_ListStyleClean li,
                   7393: .LC_ListStyleClean dd {
1.911     bisitz   7394:   padding-top: 0;
                   7395:   padding-bottom: 0;
1.693     droeschl 7396: }
                   7397: 
1.721     harmsja  7398: .LC_ListStyleSimple dd,
1.795     www      7399: .LC_ListStyleSimple li {
1.911     bisitz   7400:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7401: }
                   7402: 
1.721     harmsja  7403: .LC_ListStyleSpecial li,
                   7404: .LC_ListStyleSpecial dd {
1.911     bisitz   7405:   list-style-type: none;
                   7406:   background-color: RGB(220, 220, 220);
                   7407:   margin-bottom: 4px;
1.693     droeschl 7408: }
                   7409: 
1.721     harmsja  7410: table.LC_SimpleTable {
1.911     bisitz   7411:   margin:5px;
                   7412:   border:solid 1px $lg_border_color;
1.795     www      7413: }
1.693     droeschl 7414: 
1.721     harmsja  7415: table.LC_SimpleTable tr {
1.911     bisitz   7416:   padding: 0;
                   7417:   border:solid 1px $lg_border_color;
1.693     droeschl 7418: }
1.795     www      7419: 
                   7420: table.LC_SimpleTable thead {
1.911     bisitz   7421:   background:rgb(220,220,220);
1.693     droeschl 7422: }
                   7423: 
1.721     harmsja  7424: div.LC_columnSection {
1.911     bisitz   7425:   display: block;
                   7426:   clear: both;
                   7427:   overflow: hidden;
                   7428:   margin: 0;
1.693     droeschl 7429: }
                   7430: 
1.721     harmsja  7431: div.LC_columnSection>* {
1.911     bisitz   7432:   float: left;
                   7433:   margin: 10px 20px 10px 0;
                   7434:   overflow:hidden;
1.693     droeschl 7435: }
1.721     harmsja  7436: 
1.795     www      7437: table em {
1.911     bisitz   7438:   font-weight: bold;
                   7439:   font-style: normal;
1.748     schulted 7440: }
1.795     www      7441: 
1.779     bisitz   7442: table.LC_tableBrowseRes,
1.795     www      7443: table.LC_tableOfContent {
1.911     bisitz   7444:   border:none;
                   7445:   border-spacing: 1px;
                   7446:   padding: 3px;
                   7447:   background-color: #FFFFFF;
                   7448:   font-size: 90%;
1.753     droeschl 7449: }
1.789     droeschl 7450: 
1.911     bisitz   7451: table.LC_tableOfContent {
                   7452:   border-collapse: collapse;
1.789     droeschl 7453: }
                   7454: 
1.771     droeschl 7455: table.LC_tableBrowseRes a,
1.768     schulted 7456: table.LC_tableOfContent a {
1.911     bisitz   7457:   background-color: transparent;
                   7458:   text-decoration: none;
1.753     droeschl 7459: }
                   7460: 
1.795     www      7461: table.LC_tableOfContent img {
1.911     bisitz   7462:   border: none;
                   7463:   height: 1.3em;
                   7464:   vertical-align: text-bottom;
                   7465:   margin-right: 0.3em;
1.753     droeschl 7466: }
1.757     schulted 7467: 
1.795     www      7468: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7469:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7470: }
                   7471: 
1.795     www      7472: a#LC_content_toolbar_everything {
1.911     bisitz   7473:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7474: }
                   7475: 
1.795     www      7476: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7477:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7478: }
                   7479: 
1.795     www      7480: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7481:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7482: }
                   7483: 
1.795     www      7484: a#LC_content_toolbar_changefolder {
1.911     bisitz   7485:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7486: }
                   7487: 
1.795     www      7488: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7489:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7490: }
                   7491: 
1.1043    raeburn  7492: a#LC_content_toolbar_edittoplevel {
                   7493:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7494: }
                   7495: 
1.795     www      7496: ul#LC_toolbar li a:hover {
1.911     bisitz   7497:   background-position: bottom center;
1.757     schulted 7498: }
                   7499: 
1.795     www      7500: ul#LC_toolbar {
1.911     bisitz   7501:   padding: 0;
                   7502:   margin: 2px;
                   7503:   list-style:none;
                   7504:   position:relative;
                   7505:   background-color:white;
1.1082    raeburn  7506:   overflow: auto;
1.757     schulted 7507: }
                   7508: 
1.795     www      7509: ul#LC_toolbar li {
1.911     bisitz   7510:   border:1px solid white;
                   7511:   padding: 0;
                   7512:   margin: 0;
                   7513:   float: left;
                   7514:   display:inline;
                   7515:   vertical-align:middle;
1.1082    raeburn  7516:   white-space: nowrap;
1.911     bisitz   7517: }
1.757     schulted 7518: 
1.783     amueller 7519: 
1.795     www      7520: a.LC_toolbarItem {
1.911     bisitz   7521:   display:block;
                   7522:   padding: 0;
                   7523:   margin: 0;
                   7524:   height: 32px;
                   7525:   width: 32px;
                   7526:   color:white;
                   7527:   border: none;
                   7528:   background-repeat:no-repeat;
                   7529:   background-color:transparent;
1.757     schulted 7530: }
                   7531: 
1.915     droeschl 7532: ul.LC_funclist {
                   7533:     margin: 0;
                   7534:     padding: 0.5em 1em 0.5em 0;
                   7535: }
                   7536: 
1.933     droeschl 7537: ul.LC_funclist > li:first-child {
                   7538:     font-weight:bold; 
                   7539:     margin-left:0.8em;
                   7540: }
                   7541: 
1.915     droeschl 7542: ul.LC_funclist + ul.LC_funclist {
                   7543:     /* 
                   7544:        left border as a seperator if we have more than
                   7545:        one list 
                   7546:     */
                   7547:     border-left: 1px solid $sidebg;
                   7548:     /* 
                   7549:        this hides the left border behind the border of the 
                   7550:        outer box if element is wrapped to the next 'line' 
                   7551:     */
                   7552:     margin-left: -1px;
                   7553: }
                   7554: 
1.843     bisitz   7555: ul.LC_funclist li {
1.915     droeschl 7556:   display: inline;
1.782     bisitz   7557:   white-space: nowrap;
1.915     droeschl 7558:   margin: 0 0 0 25px;
                   7559:   line-height: 150%;
1.782     bisitz   7560: }
                   7561: 
1.974     wenzelju 7562: .LC_hidden {
                   7563:   display: none;
                   7564: }
                   7565: 
1.1030    www      7566: .LCmodal-overlay {
                   7567: 		position:fixed;
                   7568: 		top:0;
                   7569: 		right:0;
                   7570: 		bottom:0;
                   7571: 		left:0;
                   7572: 		height:100%;
                   7573: 		width:100%;
                   7574: 		margin:0;
                   7575: 		padding:0;
                   7576: 		background:#999;
                   7577: 		opacity:.75;
                   7578: 		filter: alpha(opacity=75);
                   7579: 		-moz-opacity: 0.75;
                   7580: 		z-index:101;
                   7581: }
                   7582: 
                   7583: * html .LCmodal-overlay {   
                   7584: 		position: absolute;
                   7585: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7586: }
                   7587: 
                   7588: .LCmodal-window {
                   7589: 		position:fixed;
                   7590: 		top:50%;
                   7591: 		left:50%;
                   7592: 		margin:0;
                   7593: 		padding:0;
                   7594: 		z-index:102;
                   7595: 	}
                   7596: 
                   7597: * html .LCmodal-window {
                   7598: 		position:absolute;
                   7599: }
                   7600: 
                   7601: .LCclose-window {
                   7602: 		position:absolute;
                   7603: 		width:32px;
                   7604: 		height:32px;
                   7605: 		right:8px;
                   7606: 		top:8px;
                   7607: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7608: 		text-indent:-99999px;
                   7609: 		overflow:hidden;
                   7610: 		cursor:pointer;
                   7611: }
                   7612: 
1.1100    raeburn  7613: /*
                   7614:   styles used by TTH when "Default set of options to pass to tth/m
                   7615:   when converting TeX" in course settings has been set
                   7616: 
                   7617:   option passed: -t
                   7618: 
                   7619: */
                   7620: 
                   7621: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7622: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7623: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7624: td div.norm {line-height:normal;}
                   7625: 
                   7626: /*
                   7627:   option passed -y3
                   7628: */
                   7629: 
                   7630: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7631: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7632: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7633: 
1.343     albertel 7634: END
                   7635: }
                   7636: 
1.306     albertel 7637: =pod
                   7638: 
                   7639: =item * &headtag()
                   7640: 
                   7641: Returns a uniform footer for LON-CAPA web pages.
                   7642: 
1.307     albertel 7643: Inputs: $title - optional title for the head
                   7644:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7645:         $args - optional arguments
1.319     albertel 7646:             force_register - if is true call registerurl so the remote is 
                   7647:                              informed
1.415     albertel 7648:             redirect       -> array ref of
                   7649:                                    1- seconds before redirect occurs
                   7650:                                    2- url to redirect to
                   7651:                                    3- whether the side effect should occur
1.315     albertel 7652:                            (side effect of setting 
                   7653:                                $env{'internal.head.redirect'} to the url 
                   7654:                                redirected too)
1.352     albertel 7655:             domain         -> force to color decorate a page for a specific
                   7656:                                domain
                   7657:             function       -> force usage of a specific rolish color scheme
                   7658:             bgcolor        -> override the default page bgcolor
1.460     albertel 7659:             no_auto_mt_title
                   7660:                            -> prevent &mt()ing the title arg
1.464     albertel 7661: 
1.306     albertel 7662: =cut
                   7663: 
                   7664: sub headtag {
1.313     albertel 7665:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7666:     
1.363     albertel 7667:     my $function = $args->{'function'} || &get_users_function();
                   7668:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7669:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7670:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7671:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7672: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7673: 		   #time(),
1.418     albertel 7674: 		   $env{'environment.color.timestamp'},
1.363     albertel 7675: 		   $function,$domain,$bgcolor);
                   7676: 
1.369     www      7677:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7678: 
1.308     albertel 7679:     my $result =
                   7680: 	'<head>'.
1.1160    raeburn  7681: 	&font_settings($args);
1.319     albertel 7682: 
1.1188    raeburn  7683:     my $inhibitprint;
                   7684:     if ($args->{'print_suppress'}) {
                   7685:         $inhibitprint = &print_suppression();
                   7686:     }
1.1064    raeburn  7687: 
1.461     albertel 7688:     if (!$args->{'frameset'}) {
                   7689: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7690:     }
1.962     droeschl 7691:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7692:         $result .= Apache::lonxml::display_title();
1.319     albertel 7693:     }
1.436     albertel 7694:     if (!$args->{'no_nav_bar'} 
                   7695: 	&& !$args->{'only_body'}
                   7696: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7697: 	$result .= &help_menu_js($httphost);
1.1032    www      7698:         $result.=&modal_window();
1.1038    www      7699:         $result.=&togglebox_script();
1.1034    www      7700:         $result.=&wishlist_window();
1.1041    www      7701:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7702:     } else {
                   7703:         if ($args->{'add_modal'}) {
                   7704:            $result.=&modal_window();
                   7705:         }
                   7706:         if ($args->{'add_wishlist'}) {
                   7707:            $result.=&wishlist_window();
                   7708:         }
1.1038    www      7709:         if ($args->{'add_togglebox'}) {
                   7710:            $result.=&togglebox_script();
                   7711:         }
1.1041    www      7712:         if ($args->{'add_progressbar'}) {
                   7713:            $result.=&LCprogressbarUpdate_script();
                   7714:         }
1.436     albertel 7715:     }
1.314     albertel 7716:     if (ref($args->{'redirect'})) {
1.414     albertel 7717: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7718: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7719: 	if (!$inhibit_continue) {
                   7720: 	    $env{'internal.head.redirect'} = $url;
                   7721: 	}
1.313     albertel 7722: 	$result.=<<ADDMETA
                   7723: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7724: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7725: ADDMETA
1.1210    raeburn  7726:     } else {
                   7727:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7728:             my $requrl = $env{'request.uri'};
                   7729:             if ($requrl eq '') {
                   7730:                 $requrl = $ENV{'REQUEST_URI'};
                   7731:                 $requrl =~ s/\?.+$//;
                   7732:             }
                   7733:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7734:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7735:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7736:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7737:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7738:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7739:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7740:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7741:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7742:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7743:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7744:                                 my $numsec = 5;
                   7745:                                 my $timeout = $numsec * 1000;
                   7746:                                 my ($newurl,$locknum,%locks,$msg);
                   7747:                                 if ($env{'request.role.adv'}) {
                   7748:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7749:                                 }
                   7750:                                 my $disable_submit = 0;
                   7751:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7752:                                     $disable_submit = 1;
                   7753:                                 }
                   7754:                                 if ($locknum) {
                   7755:                                     my @lockinfo = sort(values(%locks));
                   7756:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7757:                                            join(", ",sort(values(%locks)))."\\n".
                   7758:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7759:                                 } else {
                   7760:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7761:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7762:                                     }
                   7763:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7764:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7765:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7766:                                         $newurl .= '&role='.$env{'request.role'};
                   7767:                                     }
                   7768:                                     if ($env{'request.symb'}) {
                   7769:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7770:                                     } else {
                   7771:                                         $newurl .= '&origurl='.$requrl;
                   7772:                                     }
                   7773:                                 }
                   7774:                                 $result.=<<OFFLOAD
                   7775: <meta http-equiv="pragma" content="no-cache" />
                   7776: <script type="text/javascript">
1.1215    raeburn  7777: // <![CDATA[
1.1210    raeburn  7778: function LC_Offload_Now() {
                   7779:     var dest = "$newurl";
                   7780:     if (dest != '') {
                   7781:         window.location.href="$newurl";
                   7782:     }
                   7783: }
1.1214    raeburn  7784: \$(document).ready(function () {
                   7785:     window.alert('$msg');
                   7786:     if ($disable_submit) {
1.1210    raeburn  7787:         \$(".LC_hwk_submit").prop("disabled", true);
                   7788:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  7789:     }
                   7790:     setTimeout('LC_Offload_Now()', $timeout);
                   7791: });
1.1215    raeburn  7792: // ]]>
1.1210    raeburn  7793: </script>
                   7794: OFFLOAD
                   7795:                             }
                   7796:                         }
                   7797:                     }
                   7798:                 }
                   7799:             }
                   7800:         }
1.313     albertel 7801:     }
1.306     albertel 7802:     if (!defined($title)) {
                   7803: 	$title = 'The LearningOnline Network with CAPA';
                   7804:     }
1.460     albertel 7805:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7806:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7807: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7808:     if (!$args->{'frameset'}) {
                   7809:         $result .= ' /';
                   7810:     }
                   7811:     $result .= '>' 
1.1064    raeburn  7812:         .$inhibitprint
1.414     albertel 7813: 	.$head_extra;
1.1137    raeburn  7814:     if ($env{'browser.mobile'}) {
                   7815:         $result .= '
                   7816: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7817: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7818:     }
1.962     droeschl 7819:     return $result.'</head>';
1.306     albertel 7820: }
                   7821: 
                   7822: =pod
                   7823: 
1.340     albertel 7824: =item * &font_settings()
                   7825: 
                   7826: Returns neccessary <meta> to set the proper encoding
                   7827: 
1.1160    raeburn  7828: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7829: 
                   7830: =cut
                   7831: 
                   7832: sub font_settings {
1.1160    raeburn  7833:     my ($args) = @_;
1.340     albertel 7834:     my $headerstring='';
1.1160    raeburn  7835:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7836:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7837:         $headerstring.=
                   7838:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7839:         if (!$args->{'frameset'}) {
                   7840: 	    $headerstring.= ' /';
                   7841:         }
                   7842: 	$headerstring .= '>'."\n";
1.340     albertel 7843:     }
                   7844:     return $headerstring;
                   7845: }
                   7846: 
1.341     albertel 7847: =pod
                   7848: 
1.1064    raeburn  7849: =item * &print_suppression()
                   7850: 
                   7851: In course context returns css which causes the body to be blank when media="print",
                   7852: if printout generation is unavailable for the current resource.
                   7853: 
                   7854: This could be because:
                   7855: 
                   7856: (a) printstartdate is in the future
                   7857: 
                   7858: (b) printenddate is in the past
                   7859: 
                   7860: (c) there is an active exam block with "printout"
                   7861: functionality blocked
                   7862: 
                   7863: Users with pav, pfo or evb privileges are exempt.
                   7864: 
                   7865: Inputs: none
                   7866: 
                   7867: =cut
                   7868: 
                   7869: 
                   7870: sub print_suppression {
                   7871:     my $noprint;
                   7872:     if ($env{'request.course.id'}) {
                   7873:         my $scope = $env{'request.course.id'};
                   7874:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7875:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7876:             return;
                   7877:         }
                   7878:         if ($env{'request.course.sec'} ne '') {
                   7879:             $scope .= "/$env{'request.course.sec'}";
                   7880:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7881:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7882:                 return;
1.1064    raeburn  7883:             }
                   7884:         }
                   7885:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7886:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  7887:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7888:         if ($blocked) {
                   7889:             my $checkrole = "cm./$cdom/$cnum";
                   7890:             if ($env{'request.course.sec'} ne '') {
                   7891:                 $checkrole .= "/$env{'request.course.sec'}";
                   7892:             }
                   7893:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7894:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7895:                 $noprint = 1;
                   7896:             }
                   7897:         }
                   7898:         unless ($noprint) {
                   7899:             my $symb = &Apache::lonnet::symbread();
                   7900:             if ($symb ne '') {
                   7901:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7902:                 if (ref($navmap)) {
                   7903:                     my $res = $navmap->getBySymb($symb);
                   7904:                     if (ref($res)) {
                   7905:                         if (!$res->resprintable()) {
                   7906:                             $noprint = 1;
                   7907:                         }
                   7908:                     }
                   7909:                 }
                   7910:             }
                   7911:         }
                   7912:         if ($noprint) {
                   7913:             return <<"ENDSTYLE";
                   7914: <style type="text/css" media="print">
                   7915:     body { display:none }
                   7916: </style>
                   7917: ENDSTYLE
                   7918:         }
                   7919:     }
                   7920:     return;
                   7921: }
                   7922: 
                   7923: =pod
                   7924: 
1.341     albertel 7925: =item * &xml_begin()
                   7926: 
                   7927: Returns the needed doctype and <html>
                   7928: 
                   7929: Inputs: none
                   7930: 
                   7931: =cut
                   7932: 
                   7933: sub xml_begin {
1.1168    raeburn  7934:     my ($is_frameset) = @_;
1.341     albertel 7935:     my $output='';
                   7936: 
                   7937:     if ($env{'browser.mathml'}) {
                   7938: 	$output='<?xml version="1.0"?>'
                   7939:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7940: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7941:             
                   7942: #	    .'<!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">] >'
                   7943: 	    .'<!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">'
                   7944:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7945: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  7946:     } elsif ($is_frameset) {
                   7947:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7948:                 '<html>'."\n";
1.341     albertel 7949:     } else {
1.1168    raeburn  7950: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7951:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7952:     }
                   7953:     return $output;
                   7954: }
1.340     albertel 7955: 
                   7956: =pod
                   7957: 
1.306     albertel 7958: =item * &start_page()
                   7959: 
                   7960: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7961: 
1.648     raeburn  7962: Inputs:
                   7963: 
                   7964: =over 4
                   7965: 
                   7966: $title - optional title for the page
                   7967: 
                   7968: $head_extra - optional extra HTML to incude inside the <head>
                   7969: 
                   7970: $args - additional optional args supported are:
                   7971: 
                   7972: =over 8
                   7973: 
                   7974:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7975:                                     arg on
1.814     bisitz   7976:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7977:              add_entries    -> additional attributes to add to the  <body>
                   7978:              domain         -> force to color decorate a page for a 
1.317     albertel 7979:                                     specific domain
1.648     raeburn  7980:              function       -> force usage of a specific rolish color
1.317     albertel 7981:                                     scheme
1.648     raeburn  7982:              redirect       -> see &headtag()
                   7983:              bgcolor        -> override the default page bg color
                   7984:              js_ready       -> return a string ready for being used in 
1.317     albertel 7985:                                     a javascript writeln
1.648     raeburn  7986:              html_encode    -> return a string ready for being used in 
1.320     albertel 7987:                                     a html attribute
1.648     raeburn  7988:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7989:                                     $forcereg arg
1.648     raeburn  7990:              frameset       -> if true will start with a <frameset>
1.330     albertel 7991:                                     rather than <body>
1.648     raeburn  7992:              skip_phases    -> hash ref of 
1.338     albertel 7993:                                     head -> skip the <html><head> generation
                   7994:                                     body -> skip all <body> generation
1.648     raeburn  7995:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7996:              inherit_jsmath -> when creating popup window in a page,
                   7997:                                     should it have jsmath forced on by the
                   7998:                                     current page
1.867     kalberla 7999:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8000:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  8001:              group          -> includes the current group, if page is for a 
                   8002:                                specific group  
1.361     albertel 8003: 
1.648     raeburn  8004: =back
1.460     albertel 8005: 
1.648     raeburn  8006: =back
1.562     albertel 8007: 
1.306     albertel 8008: =cut
                   8009: 
                   8010: sub start_page {
1.309     albertel 8011:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8012:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8013: 
1.315     albertel 8014:     $env{'internal.start_page'}++;
1.1096    raeburn  8015:     my ($result,@advtools);
1.964     droeschl 8016: 
1.338     albertel 8017:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8018:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8019:     }
                   8020:     
                   8021:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8022: 	if ($args->{'frameset'}) {
                   8023: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8024: 						$args->{'add_entries'});
                   8025: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8026:         } else {
                   8027:             $result .=
                   8028:                 &bodytag($title, 
                   8029:                          $args->{'function'},       $args->{'add_entries'},
                   8030:                          $args->{'only_body'},      $args->{'domain'},
                   8031:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8032:                          $args->{'bgcolor'},        $args,
                   8033:                          \@advtools);
1.831     bisitz   8034:         }
1.330     albertel 8035:     }
1.338     albertel 8036: 
1.315     albertel 8037:     if ($args->{'js_ready'}) {
1.713     kaisler  8038: 		$result = &js_ready($result);
1.315     albertel 8039:     }
1.320     albertel 8040:     if ($args->{'html_encode'}) {
1.713     kaisler  8041: 		$result = &html_encode($result);
                   8042:     }
                   8043: 
1.813     bisitz   8044:     # Preparation for new and consistent functionlist at top of screen
                   8045:     # if ($args->{'functionlist'}) {
                   8046:     #            $result .= &build_functionlist();
                   8047:     #}
                   8048: 
1.964     droeschl 8049:     # Don't add anything more if only_body wanted or in const space
                   8050:     return $result if    $args->{'only_body'} 
                   8051:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8052: 
                   8053:     #Breadcrumbs
1.758     kaisler  8054:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8055: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8056: 		#if any br links exists, add them to the breadcrumbs
                   8057: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8058: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8059: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8060: 			}
                   8061: 		}
1.1096    raeburn  8062:                 # if @advtools array contains items add then to the breadcrumbs
                   8063:                 if (@advtools > 0) {
                   8064:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8065:                 }
1.758     kaisler  8066: 
                   8067: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8068: 		if(exists($args->{'bread_crumbs_component'})){
                   8069: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8070: 		}else{
                   8071: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8072: 		}
1.320     albertel 8073:     }
1.315     albertel 8074:     return $result;
1.306     albertel 8075: }
                   8076: 
                   8077: sub end_page {
1.315     albertel 8078:     my ($args) = @_;
                   8079:     $env{'internal.end_page'}++;
1.330     albertel 8080:     my $result;
1.335     albertel 8081:     if ($args->{'discussion'}) {
                   8082: 	my ($target,$parser);
                   8083: 	if (ref($args->{'discussion'})) {
                   8084: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8085: 				$args->{'discussion'}{'parser'});
                   8086: 	}
                   8087: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8088:     }
1.330     albertel 8089:     if ($args->{'frameset'}) {
                   8090: 	$result .= '</frameset>';
                   8091:     } else {
1.635     raeburn  8092: 	$result .= &endbodytag($args);
1.330     albertel 8093:     }
1.1080    raeburn  8094:     unless ($args->{'notbody'}) {
                   8095:         $result .= "\n</html>";
                   8096:     }
1.330     albertel 8097: 
1.315     albertel 8098:     if ($args->{'js_ready'}) {
1.317     albertel 8099: 	$result = &js_ready($result);
1.315     albertel 8100:     }
1.335     albertel 8101: 
1.320     albertel 8102:     if ($args->{'html_encode'}) {
                   8103: 	$result = &html_encode($result);
                   8104:     }
1.335     albertel 8105: 
1.315     albertel 8106:     return $result;
                   8107: }
                   8108: 
1.1034    www      8109: sub wishlist_window {
                   8110:     return(<<'ENDWISHLIST');
1.1046    raeburn  8111: <script type="text/javascript">
1.1034    www      8112: // <![CDATA[
                   8113: // <!-- BEGIN LON-CAPA Internal
                   8114: function set_wishlistlink(title, path) {
                   8115:     if (!title) {
                   8116:         title = document.title;
                   8117:         title = title.replace(/^LON-CAPA /,'');
                   8118:     }
1.1175    raeburn  8119:     title = encodeURIComponent(title);
1.1203    raeburn  8120:     title = title.replace("'","\\\'");
1.1034    www      8121:     if (!path) {
                   8122:         path = location.pathname;
                   8123:     }
1.1175    raeburn  8124:     path = encodeURIComponent(path);
1.1203    raeburn  8125:     path = path.replace("'","\\\'");
1.1034    www      8126:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8127:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8128: }
                   8129: // END LON-CAPA Internal -->
                   8130: // ]]>
                   8131: </script>
                   8132: ENDWISHLIST
                   8133: }
                   8134: 
1.1030    www      8135: sub modal_window {
                   8136:     return(<<'ENDMODAL');
1.1046    raeburn  8137: <script type="text/javascript">
1.1030    www      8138: // <![CDATA[
                   8139: // <!-- BEGIN LON-CAPA Internal
                   8140: var modalWindow = {
                   8141: 	parent:"body",
                   8142: 	windowId:null,
                   8143: 	content:null,
                   8144: 	width:null,
                   8145: 	height:null,
                   8146: 	close:function()
                   8147: 	{
                   8148: 	        $(".LCmodal-window").remove();
                   8149: 	        $(".LCmodal-overlay").remove();
                   8150: 	},
                   8151: 	open:function()
                   8152: 	{
                   8153: 		var modal = "";
                   8154: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8155: 		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;\">";
                   8156: 		modal += this.content;
                   8157: 		modal += "</div>";	
                   8158: 
                   8159: 		$(this.parent).append(modal);
                   8160: 
                   8161: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8162: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8163: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8164: 	}
                   8165: };
1.1140    raeburn  8166: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8167: 	{
1.1203    raeburn  8168:                 source = source.replace("'","&#39;");
1.1030    www      8169: 		modalWindow.windowId = "myModal";
                   8170: 		modalWindow.width = width;
                   8171: 		modalWindow.height = height;
1.1196    raeburn  8172: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8173: 		modalWindow.open();
1.1208    raeburn  8174: 	};
1.1030    www      8175: // END LON-CAPA Internal -->
                   8176: // ]]>
                   8177: </script>
                   8178: ENDMODAL
                   8179: }
                   8180: 
                   8181: sub modal_link {
1.1140    raeburn  8182:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8183:     unless ($width) { $width=480; }
                   8184:     unless ($height) { $height=400; }
1.1031    www      8185:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8186:     unless ($transparency) { $transparency='true'; }
                   8187: 
1.1074    raeburn  8188:     my $target_attr;
                   8189:     if (defined($target)) {
                   8190:         $target_attr = 'target="'.$target.'"';
                   8191:     }
                   8192:     return <<"ENDLINK";
1.1140    raeburn  8193: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8194:            $linktext</a>
                   8195: ENDLINK
1.1030    www      8196: }
                   8197: 
1.1032    www      8198: sub modal_adhoc_script {
                   8199:     my ($funcname,$width,$height,$content)=@_;
                   8200:     return (<<ENDADHOC);
1.1046    raeburn  8201: <script type="text/javascript">
1.1032    www      8202: // <![CDATA[
                   8203:         var $funcname = function()
                   8204:         {
                   8205:                 modalWindow.windowId = "myModal";
                   8206:                 modalWindow.width = $width;
                   8207:                 modalWindow.height = $height;
                   8208:                 modalWindow.content = '$content';
                   8209:                 modalWindow.open();
                   8210:         };  
                   8211: // ]]>
                   8212: </script>
                   8213: ENDADHOC
                   8214: }
                   8215: 
1.1041    www      8216: sub modal_adhoc_inner {
                   8217:     my ($funcname,$width,$height,$content)=@_;
                   8218:     my $innerwidth=$width-20;
                   8219:     $content=&js_ready(
1.1140    raeburn  8220:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8221:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8222:                  $content.
1.1041    www      8223:                  &end_scrollbox().
1.1140    raeburn  8224:                  &end_page()
1.1041    www      8225:              );
                   8226:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8227: }
                   8228: 
                   8229: sub modal_adhoc_window {
                   8230:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8231:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8232:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8233: }
                   8234: 
                   8235: sub modal_adhoc_launch {
                   8236:     my ($funcname,$width,$height,$content)=@_;
                   8237:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8238: <script type="text/javascript">
                   8239: // <![CDATA[
                   8240: $funcname();
                   8241: // ]]>
                   8242: </script>
                   8243: ENDLAUNCH
                   8244: }
                   8245: 
                   8246: sub modal_adhoc_close {
                   8247:     return (<<ENDCLOSE);
                   8248: <script type="text/javascript">
                   8249: // <![CDATA[
                   8250: modalWindow.close();
                   8251: // ]]>
                   8252: </script>
                   8253: ENDCLOSE
                   8254: }
                   8255: 
1.1038    www      8256: sub togglebox_script {
                   8257:    return(<<ENDTOGGLE);
                   8258: <script type="text/javascript"> 
                   8259: // <![CDATA[
                   8260: function LCtoggleDisplay(id,hidetext,showtext) {
                   8261:    link = document.getElementById(id + "link").childNodes[0];
                   8262:    with (document.getElementById(id).style) {
                   8263:       if (display == "none" ) {
                   8264:           display = "inline";
                   8265:           link.nodeValue = hidetext;
                   8266:         } else {
                   8267:           display = "none";
                   8268:           link.nodeValue = showtext;
                   8269:        }
                   8270:    }
                   8271: }
                   8272: // ]]>
                   8273: </script>
                   8274: ENDTOGGLE
                   8275: }
                   8276: 
1.1039    www      8277: sub start_togglebox {
                   8278:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8279:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8280:     unless ($showtext) { $showtext=&mt('show'); }
                   8281:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8282:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8283:     return &start_data_table().
                   8284:            &start_data_table_header_row().
                   8285:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8286:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8287:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8288:            &end_data_table_header_row().
                   8289:            '<tr id="'.$id.'" style="display:none""><td>';
                   8290: }
                   8291: 
                   8292: sub end_togglebox {
                   8293:     return '</td></tr>'.&end_data_table();
                   8294: }
                   8295: 
1.1041    www      8296: sub LCprogressbar_script {
1.1045    www      8297:    my ($id)=@_;
1.1041    www      8298:    return(<<ENDPROGRESS);
                   8299: <script type="text/javascript">
                   8300: // <![CDATA[
1.1045    www      8301: \$('#progressbar$id').progressbar({
1.1041    www      8302:   value: 0,
                   8303:   change: function(event, ui) {
                   8304:     var newVal = \$(this).progressbar('option', 'value');
                   8305:     \$('.pblabel', this).text(LCprogressTxt);
                   8306:   }
                   8307: });
                   8308: // ]]>
                   8309: </script>
                   8310: ENDPROGRESS
                   8311: }
                   8312: 
                   8313: sub LCprogressbarUpdate_script {
                   8314:    return(<<ENDPROGRESSUPDATE);
                   8315: <style type="text/css">
                   8316: .ui-progressbar { position:relative; }
                   8317: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8318: </style>
                   8319: <script type="text/javascript">
                   8320: // <![CDATA[
1.1045    www      8321: var LCprogressTxt='---';
                   8322: 
                   8323: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8324:    LCprogressTxt=progresstext;
1.1045    www      8325:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8326: }
                   8327: // ]]>
                   8328: </script>
                   8329: ENDPROGRESSUPDATE
                   8330: }
                   8331: 
1.1042    www      8332: my $LClastpercent;
1.1045    www      8333: my $LCidcnt;
                   8334: my $LCcurrentid;
1.1042    www      8335: 
1.1041    www      8336: sub LCprogressbar {
1.1042    www      8337:     my ($r)=(@_);
                   8338:     $LClastpercent=0;
1.1045    www      8339:     $LCidcnt++;
                   8340:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8341:     my $starting=&mt('Starting');
                   8342:     my $content=(<<ENDPROGBAR);
1.1045    www      8343:   <div id="progressbar$LCcurrentid">
1.1041    www      8344:     <span class="pblabel">$starting</span>
                   8345:   </div>
                   8346: ENDPROGBAR
1.1045    www      8347:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8348: }
                   8349: 
                   8350: sub LCprogressbarUpdate {
1.1042    www      8351:     my ($r,$val,$text)=@_;
                   8352:     unless ($val) { 
                   8353:        if ($LClastpercent) {
                   8354:            $val=$LClastpercent;
                   8355:        } else {
                   8356:            $val=0;
                   8357:        }
                   8358:     }
1.1041    www      8359:     if ($val<0) { $val=0; }
                   8360:     if ($val>100) { $val=0; }
1.1042    www      8361:     $LClastpercent=$val;
1.1041    www      8362:     unless ($text) { $text=$val.'%'; }
                   8363:     $text=&js_ready($text);
1.1044    www      8364:     &r_print($r,<<ENDUPDATE);
1.1041    www      8365: <script type="text/javascript">
                   8366: // <![CDATA[
1.1045    www      8367: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8368: // ]]>
                   8369: </script>
                   8370: ENDUPDATE
1.1035    www      8371: }
                   8372: 
1.1042    www      8373: sub LCprogressbarClose {
                   8374:     my ($r)=@_;
                   8375:     $LClastpercent=0;
1.1044    www      8376:     &r_print($r,<<ENDCLOSE);
1.1042    www      8377: <script type="text/javascript">
                   8378: // <![CDATA[
1.1045    www      8379: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8380: // ]]>
                   8381: </script>
                   8382: ENDCLOSE
1.1044    www      8383: }
                   8384: 
                   8385: sub r_print {
                   8386:     my ($r,$to_print)=@_;
                   8387:     if ($r) {
                   8388:       $r->print($to_print);
                   8389:       $r->rflush();
                   8390:     } else {
                   8391:       print($to_print);
                   8392:     }
1.1042    www      8393: }
                   8394: 
1.320     albertel 8395: sub html_encode {
                   8396:     my ($result) = @_;
                   8397: 
1.322     albertel 8398:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8399:     
                   8400:     return $result;
                   8401: }
1.1044    www      8402: 
1.317     albertel 8403: sub js_ready {
                   8404:     my ($result) = @_;
                   8405: 
1.323     albertel 8406:     $result =~ s/[\n\r]/ /xmsg;
                   8407:     $result =~ s/\\/\\\\/xmsg;
                   8408:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8409:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8410:     
                   8411:     return $result;
                   8412: }
                   8413: 
1.315     albertel 8414: sub validate_page {
                   8415:     if (  exists($env{'internal.start_page'})
1.316     albertel 8416: 	  &&     $env{'internal.start_page'} > 1) {
                   8417: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8418: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8419: 				 $ENV{'request.filename'});
1.315     albertel 8420:     }
                   8421:     if (  exists($env{'internal.end_page'})
1.316     albertel 8422: 	  &&     $env{'internal.end_page'} > 1) {
                   8423: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8424: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8425: 				 $env{'request.filename'});
1.315     albertel 8426:     }
                   8427:     if (     exists($env{'internal.start_page'})
                   8428: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8429: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8430: 				 $env{'request.filename'});
1.315     albertel 8431:     }
                   8432:     if (   ! exists($env{'internal.start_page'})
                   8433: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8434: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8435: 				 $env{'request.filename'});
1.315     albertel 8436:     }
1.306     albertel 8437: }
1.315     albertel 8438: 
1.996     www      8439: 
                   8440: sub start_scrollbox {
1.1140    raeburn  8441:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8442:     unless ($outerwidth) { $outerwidth='520px'; }
                   8443:     unless ($width) { $width='500px'; }
                   8444:     unless ($height) { $height='200px'; }
1.1075    raeburn  8445:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8446:     if ($id ne '') {
1.1140    raeburn  8447:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8448:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8449:     }
1.1075    raeburn  8450:     if ($bgcolor ne '') {
                   8451:         $tdcol = "background-color: $bgcolor;";
                   8452:     }
1.1137    raeburn  8453:     my $nicescroll_js;
                   8454:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8455:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8456:     }
                   8457:     return <<"END";
                   8458: $nicescroll_js
                   8459: 
                   8460: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8461: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8462: END
                   8463: }
                   8464: 
                   8465: sub end_scrollbox {
                   8466:     return '</div></td></tr></table>';
                   8467: }
                   8468: 
                   8469: sub nicescroll_javascript {
                   8470:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8471:     my %options;
                   8472:     if (ref($cursor) eq 'HASH') {
                   8473:         %options = %{$cursor};
                   8474:     }
                   8475:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8476:         $options{'railalign'} = 'left';
                   8477:     }
                   8478:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8479:         my $function  = &get_users_function();
                   8480:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8481:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8482:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8483:         }
1.1140    raeburn  8484:     }
                   8485:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8486:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8487:             $options{'cursoropacity'}='1.0';
                   8488:         }
1.1140    raeburn  8489:     } else {
                   8490:         $options{'cursoropacity'}='1.0';
                   8491:     }
                   8492:     if ($options{'cursorfixedheight'} eq 'none') {
                   8493:         delete($options{'cursorfixedheight'});
                   8494:     } else {
                   8495:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8496:     }
                   8497:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8498:         delete($options{'railoffset'});
                   8499:     }
                   8500:     my @niceoptions;
                   8501:     while (my($key,$value) = each(%options)) {
                   8502:         if ($value =~ /^\{.+\}$/) {
                   8503:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8504:         } else {
1.1140    raeburn  8505:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8506:         }
1.1140    raeburn  8507:     }
                   8508:     my $nicescroll_js = '
1.1137    raeburn  8509: $(document).ready(
1.1140    raeburn  8510:       function() {
                   8511:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8512:       }
1.1137    raeburn  8513: );
                   8514: ';
1.1140    raeburn  8515:     if ($framecheck) {
                   8516:         $nicescroll_js .= '
                   8517: function expand_div(caller) {
                   8518:     if (top === self) {
                   8519:         document.getElementById("'.$id.'").style.width = "auto";
                   8520:         document.getElementById("'.$id.'").style.height = "auto";
                   8521:     } else {
                   8522:         try {
                   8523:             if (parent.frames) {
                   8524:                 if (parent.frames.length > 1) {
                   8525:                     var framesrc = parent.frames[1].location.href;
                   8526:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8527:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8528:                         document.getElementById("'.$id.'").style.width = "auto";
                   8529:                         document.getElementById("'.$id.'").style.height = "auto";
                   8530:                     }
                   8531:                 }
                   8532:             }
                   8533:         } catch (e) {
                   8534:             return;
                   8535:         }
1.1137    raeburn  8536:     }
1.1140    raeburn  8537:     return;
1.996     www      8538: }
1.1140    raeburn  8539: ';
                   8540:     }
                   8541:     if ($needjsready) {
                   8542:         $nicescroll_js = '
                   8543: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8544:     } else {
                   8545:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8546:     }
                   8547:     return $nicescroll_js;
1.996     www      8548: }
                   8549: 
1.318     albertel 8550: sub simple_error_page {
1.1150    bisitz   8551:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8552:     if (ref($args) eq 'HASH') {
                   8553:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8554:     } else {
                   8555:         $msg = &mt($msg);
                   8556:     }
1.1150    bisitz   8557: 
1.318     albertel 8558:     my $page =
                   8559: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8560: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8561: 	&Apache::loncommon::end_page();
                   8562:     if (ref($r)) {
                   8563: 	$r->print($page);
1.327     albertel 8564: 	return;
1.318     albertel 8565:     }
                   8566:     return $page;
                   8567: }
1.347     albertel 8568: 
                   8569: {
1.610     albertel 8570:     my @row_count;
1.961     onken    8571: 
                   8572:     sub start_data_table_count {
                   8573:         unshift(@row_count, 0);
                   8574:         return;
                   8575:     }
                   8576: 
                   8577:     sub end_data_table_count {
                   8578:         shift(@row_count);
                   8579:         return;
                   8580:     }
                   8581: 
1.347     albertel 8582:     sub start_data_table {
1.1018    raeburn  8583: 	my ($add_class,$id) = @_;
1.422     albertel 8584: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8585:         my $table_id;
                   8586:         if (defined($id)) {
                   8587:             $table_id = ' id="'.$id.'"';
                   8588:         }
1.961     onken    8589: 	&start_data_table_count();
1.1018    raeburn  8590: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8591:     }
                   8592: 
                   8593:     sub end_data_table {
1.961     onken    8594: 	&end_data_table_count();
1.389     albertel 8595: 	return '</table>'."\n";;
1.347     albertel 8596:     }
                   8597: 
                   8598:     sub start_data_table_row {
1.974     wenzelju 8599: 	my ($add_class, $id) = @_;
1.610     albertel 8600: 	$row_count[0]++;
                   8601: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8602: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8603:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8604:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8605:     }
1.471     banghart 8606:     
                   8607:     sub continue_data_table_row {
1.974     wenzelju 8608: 	my ($add_class, $id) = @_;
1.610     albertel 8609: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8610: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8611:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8612:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8613:     }
1.347     albertel 8614: 
                   8615:     sub end_data_table_row {
1.389     albertel 8616: 	return '</tr>'."\n";;
1.347     albertel 8617:     }
1.367     www      8618: 
1.421     albertel 8619:     sub start_data_table_empty_row {
1.707     bisitz   8620: #	$row_count[0]++;
1.421     albertel 8621: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8622:     }
                   8623: 
                   8624:     sub end_data_table_empty_row {
                   8625: 	return '</tr>'."\n";;
                   8626:     }
                   8627: 
1.367     www      8628:     sub start_data_table_header_row {
1.389     albertel 8629: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8630:     }
                   8631: 
                   8632:     sub end_data_table_header_row {
1.389     albertel 8633: 	return '</tr>'."\n";;
1.367     www      8634:     }
1.890     droeschl 8635: 
                   8636:     sub data_table_caption {
                   8637:         my $caption = shift;
                   8638:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8639:     }
1.347     albertel 8640: }
                   8641: 
1.548     albertel 8642: =pod
                   8643: 
                   8644: =item * &inhibit_menu_check($arg)
                   8645: 
                   8646: Checks for a inhibitmenu state and generates output to preserve it
                   8647: 
                   8648: Inputs:         $arg - can be any of
                   8649:                      - undef - in which case the return value is a string 
                   8650:                                to add  into arguments list of a uri
                   8651:                      - 'input' - in which case the return value is a HTML
                   8652:                                  <form> <input> field of type hidden to
                   8653:                                  preserve the value
                   8654:                      - a url - in which case the return value is the url with
                   8655:                                the neccesary cgi args added to preserve the
                   8656:                                inhibitmenu state
                   8657:                      - a ref to a url - no return value, but the string is
                   8658:                                         updated to include the neccessary cgi
                   8659:                                         args to preserve the inhibitmenu state
                   8660: 
                   8661: =cut
                   8662: 
                   8663: sub inhibit_menu_check {
                   8664:     my ($arg) = @_;
                   8665:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8666:     if ($arg eq 'input') {
                   8667: 	if ($env{'form.inhibitmenu'}) {
                   8668: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8669: 	} else {
                   8670: 	    return
                   8671: 	}
                   8672:     }
                   8673:     if ($env{'form.inhibitmenu'}) {
                   8674: 	if (ref($arg)) {
                   8675: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8676: 	} elsif ($arg eq '') {
                   8677: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8678: 	} else {
                   8679: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8680: 	}
                   8681:     }
                   8682:     if (!ref($arg)) {
                   8683: 	return $arg;
                   8684:     }
                   8685: }
                   8686: 
1.251     albertel 8687: ###############################################
1.182     matthew  8688: 
                   8689: =pod
                   8690: 
1.549     albertel 8691: =back
                   8692: 
                   8693: =head1 User Information Routines
                   8694: 
                   8695: =over 4
                   8696: 
1.405     albertel 8697: =item * &get_users_function()
1.182     matthew  8698: 
                   8699: Used by &bodytag to determine the current users primary role.
                   8700: Returns either 'student','coordinator','admin', or 'author'.
                   8701: 
                   8702: =cut
                   8703: 
                   8704: ###############################################
                   8705: sub get_users_function {
1.815     tempelho 8706:     my $function = 'norole';
1.818     tempelho 8707:     if ($env{'request.role'}=~/^(st)/) {
                   8708:         $function='student';
                   8709:     }
1.907     raeburn  8710:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8711:         $function='coordinator';
                   8712:     }
1.258     albertel 8713:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8714:         $function='admin';
                   8715:     }
1.826     bisitz   8716:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8717:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8718:         $function='author';
                   8719:     }
                   8720:     return $function;
1.54      www      8721: }
1.99      www      8722: 
                   8723: ###############################################
                   8724: 
1.233     raeburn  8725: =pod
                   8726: 
1.821     raeburn  8727: =item * &show_course()
                   8728: 
                   8729: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8730: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8731: 
                   8732: Inputs:
                   8733: None
                   8734: 
                   8735: Outputs:
                   8736: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8737: 
                   8738: =cut
                   8739: 
                   8740: ###############################################
                   8741: sub show_course {
                   8742:     my $course = !$env{'user.adv'};
                   8743:     if (!$env{'user.adv'}) {
                   8744:         foreach my $env (keys(%env)) {
                   8745:             next if ($env !~ m/^user\.priv\./);
                   8746:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8747:                 $course = 0;
                   8748:                 last;
                   8749:             }
                   8750:         }
                   8751:     }
                   8752:     return $course;
                   8753: }
                   8754: 
                   8755: ###############################################
                   8756: 
                   8757: =pod
                   8758: 
1.542     raeburn  8759: =item * &check_user_status()
1.274     raeburn  8760: 
                   8761: Determines current status of supplied role for a
                   8762: specific user. Roles can be active, previous or future.
                   8763: 
                   8764: Inputs: 
                   8765: user's domain, user's username, course's domain,
1.375     raeburn  8766: course's number, optional section ID.
1.274     raeburn  8767: 
                   8768: Outputs:
                   8769: role status: active, previous or future. 
                   8770: 
                   8771: =cut
                   8772: 
                   8773: sub check_user_status {
1.412     raeburn  8774:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8775:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8776:     my @uroles = keys(%userinfo);
1.274     raeburn  8777:     my $srchstr;
                   8778:     my $active_chk = 'none';
1.412     raeburn  8779:     my $now = time;
1.274     raeburn  8780:     if (@uroles > 0) {
1.908     raeburn  8781:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8782:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8783:         } else {
1.412     raeburn  8784:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8785:         }
                   8786:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8787:             my $role_end = 0;
                   8788:             my $role_start = 0;
                   8789:             $active_chk = 'active';
1.412     raeburn  8790:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8791:                 $role_end = $1;
                   8792:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8793:                     $role_start = $1;
1.274     raeburn  8794:                 }
                   8795:             }
                   8796:             if ($role_start > 0) {
1.412     raeburn  8797:                 if ($now < $role_start) {
1.274     raeburn  8798:                     $active_chk = 'future';
                   8799:                 }
                   8800:             }
                   8801:             if ($role_end > 0) {
1.412     raeburn  8802:                 if ($now > $role_end) {
1.274     raeburn  8803:                     $active_chk = 'previous';
                   8804:                 }
                   8805:             }
                   8806:         }
                   8807:     }
                   8808:     return $active_chk;
                   8809: }
                   8810: 
                   8811: ###############################################
                   8812: 
                   8813: =pod
                   8814: 
1.405     albertel 8815: =item * &get_sections()
1.233     raeburn  8816: 
                   8817: Determines all the sections for a course including
                   8818: sections with students and sections containing other roles.
1.419     raeburn  8819: Incoming parameters: 
                   8820: 
                   8821: 1. domain
                   8822: 2. course number 
                   8823: 3. reference to array containing roles for which sections should 
                   8824: be gathered (optional).
                   8825: 4. reference to array containing status types for which sections 
                   8826: should be gathered (optional).
                   8827: 
                   8828: If the third argument is undefined, sections are gathered for any role. 
                   8829: If the fourth argument is undefined, sections are gathered for any status.
                   8830: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8831:  
1.374     raeburn  8832: Returns section hash (keys are section IDs, values are
                   8833: number of users in each section), subject to the
1.419     raeburn  8834: optional roles filter, optional status filter 
1.233     raeburn  8835: 
                   8836: =cut
                   8837: 
                   8838: ###############################################
                   8839: sub get_sections {
1.419     raeburn  8840:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8841:     if (!defined($cdom) || !defined($cnum)) {
                   8842:         my $cid =  $env{'request.course.id'};
                   8843: 
                   8844: 	return if (!defined($cid));
                   8845: 
                   8846:         $cdom = $env{'course.'.$cid.'.domain'};
                   8847:         $cnum = $env{'course.'.$cid.'.num'};
                   8848:     }
                   8849: 
                   8850:     my %sectioncount;
1.419     raeburn  8851:     my $now = time;
1.240     albertel 8852: 
1.1118    raeburn  8853:     my $check_students = 1;
                   8854:     my $only_students = 0;
                   8855:     if (ref($possible_roles) eq 'ARRAY') {
                   8856:         if (grep(/^st$/,@{$possible_roles})) {
                   8857:             if (@{$possible_roles} == 1) {
                   8858:                 $only_students = 1;
                   8859:             }
                   8860:         } else {
                   8861:             $check_students = 0;
                   8862:         }
                   8863:     }
                   8864: 
                   8865:     if ($check_students) { 
1.276     albertel 8866: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8867: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8868: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8869:         my $start_index = &Apache::loncoursedata::CL_START();
                   8870:         my $end_index = &Apache::loncoursedata::CL_END();
                   8871:         my $status;
1.366     albertel 8872: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8873: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8874: 				                     $data->[$status_index],
                   8875:                                                      $data->[$start_index],
                   8876:                                                      $data->[$end_index]);
                   8877:             if ($stu_status eq 'Active') {
                   8878:                 $status = 'active';
                   8879:             } elsif ($end < $now) {
                   8880:                 $status = 'previous';
                   8881:             } elsif ($start > $now) {
                   8882:                 $status = 'future';
                   8883:             } 
                   8884: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8885:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8886:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8887: 		    $sectioncount{$section}++;
                   8888:                 }
1.240     albertel 8889: 	    }
                   8890: 	}
                   8891:     }
1.1118    raeburn  8892:     if ($only_students) {
                   8893:         return %sectioncount;
                   8894:     }
1.240     albertel 8895:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8896:     foreach my $user (sort(keys(%courseroles))) {
                   8897: 	if ($user !~ /^(\w{2})/) { next; }
                   8898: 	my ($role) = ($user =~ /^(\w{2})/);
                   8899: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8900: 	my ($section,$status);
1.240     albertel 8901: 	if ($role eq 'cr' &&
                   8902: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8903: 	    $section=$1;
                   8904: 	}
                   8905: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8906: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8907:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8908:         if ($end == -1 && $start == -1) {
                   8909:             next; #deleted role
                   8910:         }
                   8911:         if (!defined($possible_status)) { 
                   8912:             $sectioncount{$section}++;
                   8913:         } else {
                   8914:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8915:                 $status = 'active';
                   8916:             } elsif ($end < $now) {
                   8917:                 $status = 'future';
                   8918:             } elsif ($start > $now) {
                   8919:                 $status = 'previous';
                   8920:             }
                   8921:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8922:                 $sectioncount{$section}++;
                   8923:             }
                   8924:         }
1.233     raeburn  8925:     }
1.366     albertel 8926:     return %sectioncount;
1.233     raeburn  8927: }
                   8928: 
1.274     raeburn  8929: ###############################################
1.294     raeburn  8930: 
                   8931: =pod
1.405     albertel 8932: 
                   8933: =item * &get_course_users()
                   8934: 
1.275     raeburn  8935: Retrieves usernames:domains for users in the specified course
                   8936: with specific role(s), and access status. 
                   8937: 
                   8938: Incoming parameters:
1.277     albertel 8939: 1. course domain
                   8940: 2. course number
                   8941: 3. access status: users must have - either active, 
1.275     raeburn  8942: previous, future, or all.
1.277     albertel 8943: 4. reference to array of permissible roles
1.288     raeburn  8944: 5. reference to array of section restrictions (optional)
                   8945: 6. reference to results object (hash of hashes).
                   8946: 7. reference to optional userdata hash
1.609     raeburn  8947: 8. reference to optional statushash
1.630     raeburn  8948: 9. flag if privileged users (except those set to unhide in
                   8949:    course settings) should be excluded    
1.609     raeburn  8950: Keys of top level results hash are roles.
1.275     raeburn  8951: Keys of inner hashes are username:domain, with 
                   8952: values set to access type.
1.288     raeburn  8953: Optional userdata hash returns an array with arguments in the 
                   8954: same order as loncoursedata::get_classlist() for student data.
                   8955: 
1.609     raeburn  8956: Optional statushash returns
                   8957: 
1.288     raeburn  8958: Entries for end, start, section and status are blank because
                   8959: of the possibility of multiple values for non-student roles.
                   8960: 
1.275     raeburn  8961: =cut
1.405     albertel 8962: 
1.275     raeburn  8963: ###############################################
1.405     albertel 8964: 
1.275     raeburn  8965: sub get_course_users {
1.630     raeburn  8966:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8967:     my %idx = ();
1.419     raeburn  8968:     my %seclists;
1.288     raeburn  8969: 
                   8970:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8971:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8972:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8973:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8974:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8975:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8976:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8977:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8978: 
1.290     albertel 8979:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8980:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8981:         my $now = time;
1.277     albertel 8982:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8983:             my $match = 0;
1.412     raeburn  8984:             my $secmatch = 0;
1.419     raeburn  8985:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8986:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8987:             if ($section eq '') {
                   8988:                 $section = 'none';
                   8989:             }
1.291     albertel 8990:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8991:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8992:                     $secmatch = 1;
                   8993:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8994:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8995:                         $secmatch = 1;
                   8996:                     }
                   8997:                 } else {  
1.419     raeburn  8998: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8999: 		        $secmatch = 1;
                   9000:                     }
1.290     albertel 9001: 		}
1.412     raeburn  9002:                 if (!$secmatch) {
                   9003:                     next;
                   9004:                 }
1.419     raeburn  9005:             }
1.275     raeburn  9006:             if (defined($$types{'active'})) {
1.288     raeburn  9007:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9008:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9009:                     $match = 1;
1.275     raeburn  9010:                 }
                   9011:             }
                   9012:             if (defined($$types{'previous'})) {
1.609     raeburn  9013:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9014:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9015:                     $match = 1;
1.275     raeburn  9016:                 }
                   9017:             }
                   9018:             if (defined($$types{'future'})) {
1.609     raeburn  9019:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9020:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9021:                     $match = 1;
1.275     raeburn  9022:                 }
                   9023:             }
1.609     raeburn  9024:             if ($match) {
                   9025:                 push(@{$seclists{$student}},$section);
                   9026:                 if (ref($userdata) eq 'HASH') {
                   9027:                     $$userdata{$student} = $$classlist{$student};
                   9028:                 }
                   9029:                 if (ref($statushash) eq 'HASH') {
                   9030:                     $statushash->{$student}{'st'}{$section} = $status;
                   9031:                 }
1.288     raeburn  9032:             }
1.275     raeburn  9033:         }
                   9034:     }
1.412     raeburn  9035:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9036:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9037:         my $now = time;
1.609     raeburn  9038:         my %displaystatus = ( previous => 'Expired',
                   9039:                               active   => 'Active',
                   9040:                               future   => 'Future',
                   9041:                             );
1.1121    raeburn  9042:         my (%nothide,@possdoms);
1.630     raeburn  9043:         if ($hidepriv) {
                   9044:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9045:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9046:                 if ($user !~ /:/) {
                   9047:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9048:                 } else {
                   9049:                     $nothide{$user} = 1;
                   9050:                 }
                   9051:             }
1.1121    raeburn  9052:             my @possdoms = ($cdom);
                   9053:             if ($coursehash{'checkforpriv'}) {
                   9054:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9055:             }
1.630     raeburn  9056:         }
1.439     raeburn  9057:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9058:             my $match = 0;
1.412     raeburn  9059:             my $secmatch = 0;
1.439     raeburn  9060:             my $status;
1.412     raeburn  9061:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9062:             $user =~ s/:$//;
1.439     raeburn  9063:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9064:             if ($end == -1 || $start == -1) {
                   9065:                 next;
                   9066:             }
                   9067:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9068:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9069:                 my ($uname,$udom) = split(/:/,$user);
                   9070:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9071:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9072:                         $secmatch = 1;
                   9073:                     } elsif ($usec eq '') {
1.420     albertel 9074:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9075:                             $secmatch = 1;
                   9076:                         }
                   9077:                     } else {
                   9078:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9079:                             $secmatch = 1;
                   9080:                         }
                   9081:                     }
                   9082:                     if (!$secmatch) {
                   9083:                         next;
                   9084:                     }
1.288     raeburn  9085:                 }
1.419     raeburn  9086:                 if ($usec eq '') {
                   9087:                     $usec = 'none';
                   9088:                 }
1.275     raeburn  9089:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9090:                     if ($hidepriv) {
1.1121    raeburn  9091:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9092:                             (!$nothide{$uname.':'.$udom})) {
                   9093:                             next;
                   9094:                         }
                   9095:                     }
1.503     raeburn  9096:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9097:                         $status = 'previous';
                   9098:                     } elsif ($start > $now) {
                   9099:                         $status = 'future';
                   9100:                     } else {
                   9101:                         $status = 'active';
                   9102:                     }
1.277     albertel 9103:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9104:                         if ($status eq $type) {
1.420     albertel 9105:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9106:                                 push(@{$$users{$role}{$user}},$type);
                   9107:                             }
1.288     raeburn  9108:                             $match = 1;
                   9109:                         }
                   9110:                     }
1.419     raeburn  9111:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9112:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9113: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9114:                         }
1.420     albertel 9115:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9116:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9117:                         }
1.609     raeburn  9118:                         if (ref($statushash) eq 'HASH') {
                   9119:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9120:                         }
1.275     raeburn  9121:                     }
                   9122:                 }
                   9123:             }
                   9124:         }
1.290     albertel 9125:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9126:             if ((defined($cdom)) && (defined($cnum))) {
                   9127:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9128:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9129:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9130:                     next if ($owner eq '');
                   9131:                     my ($ownername,$ownerdom);
                   9132:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9133:                         $ownername = $1;
                   9134:                         $ownerdom = $2;
                   9135:                     } else {
                   9136:                         $ownername = $owner;
                   9137:                         $ownerdom = $cdom;
                   9138:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9139:                     }
                   9140:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9141:                     if (defined($userdata) && 
1.609     raeburn  9142: 			!exists($$userdata{$owner})) {
                   9143: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9144:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9145:                             push(@{$seclists{$owner}},'none');
                   9146:                         }
                   9147:                         if (ref($statushash) eq 'HASH') {
                   9148:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9149:                         }
1.290     albertel 9150: 		    }
1.279     raeburn  9151:                 }
                   9152:             }
                   9153:         }
1.419     raeburn  9154:         foreach my $user (keys(%seclists)) {
                   9155:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9156:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9157:         }
1.275     raeburn  9158:     }
                   9159:     return;
                   9160: }
                   9161: 
1.288     raeburn  9162: sub get_user_info {
                   9163:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9164:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9165: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9166:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9167:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9168:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9169:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9170:     return;
                   9171: }
1.275     raeburn  9172: 
1.472     raeburn  9173: ###############################################
                   9174: 
                   9175: =pod
                   9176: 
                   9177: =item * &get_user_quota()
                   9178: 
1.1134    raeburn  9179: Retrieves quota assigned for storage of user files.
                   9180: Default is to report quota for portfolio files.
1.472     raeburn  9181: 
                   9182: Incoming parameters:
                   9183: 1. user's username
                   9184: 2. user's domain
1.1134    raeburn  9185: 3. quota name - portfolio, author, or course
1.1136    raeburn  9186:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  9187: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  9188:    course
1.472     raeburn  9189: 
                   9190: Returns:
1.1163    raeburn  9191: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9192: 2. (Optional) Type of setting: custom or default
                   9193:    (individually assigned or default for user's 
                   9194:    institutional status).
                   9195: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9196:    or student - types as defined in localenroll::inst_usertypes 
                   9197:    for user's domain, which determines default quota for user.
                   9198: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9199: 
                   9200: If a value has been stored in the user's environment, 
1.536     raeburn  9201: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9202: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9203: 
                   9204: =cut
                   9205: 
                   9206: ###############################################
                   9207: 
                   9208: 
                   9209: sub get_user_quota {
1.1136    raeburn  9210:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9211:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9212:     if (!defined($udom)) {
                   9213:         $udom = $env{'user.domain'};
                   9214:     }
                   9215:     if (!defined($uname)) {
                   9216:         $uname = $env{'user.name'};
                   9217:     }
                   9218:     if (($udom eq '' || $uname eq '') ||
                   9219:         ($udom eq 'public') && ($uname eq 'public')) {
                   9220:         $quota = 0;
1.536     raeburn  9221:         $quotatype = 'default';
                   9222:         $defquota = 0; 
1.472     raeburn  9223:     } else {
1.536     raeburn  9224:         my $inststatus;
1.1134    raeburn  9225:         if ($quotaname eq 'course') {
                   9226:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9227:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9228:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9229:             } else {
                   9230:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9231:                 $quota = $cenv{'internal.uploadquota'};
                   9232:             }
1.536     raeburn  9233:         } else {
1.1134    raeburn  9234:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9235:                 if ($quotaname eq 'author') {
                   9236:                     $quota = $env{'environment.authorquota'};
                   9237:                 } else {
                   9238:                     $quota = $env{'environment.portfolioquota'};
                   9239:                 }
                   9240:                 $inststatus = $env{'environment.inststatus'};
                   9241:             } else {
                   9242:                 my %userenv = 
                   9243:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9244:                                          'authorquota','inststatus'],$udom,$uname);
                   9245:                 my ($tmp) = keys(%userenv);
                   9246:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9247:                     if ($quotaname eq 'author') {
                   9248:                         $quota = $userenv{'authorquota'};
                   9249:                     } else {
                   9250:                         $quota = $userenv{'portfolioquota'};
                   9251:                     }
                   9252:                     $inststatus = $userenv{'inststatus'};
                   9253:                 } else {
                   9254:                     undef(%userenv);
                   9255:                 }
                   9256:             }
                   9257:         }
                   9258:         if ($quota eq '' || wantarray) {
                   9259:             if ($quotaname eq 'course') {
                   9260:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9261:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   9262:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  9263:                     $defquota = $domdefs{$crstype.'quota'};
                   9264:                 }
                   9265:                 if ($defquota eq '') {
                   9266:                     $defquota = 500;
                   9267:                 }
1.1134    raeburn  9268:             } else {
                   9269:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9270:             }
                   9271:             if ($quota eq '') {
                   9272:                 $quota = $defquota;
                   9273:                 $quotatype = 'default';
                   9274:             } else {
                   9275:                 $quotatype = 'custom';
                   9276:             }
1.472     raeburn  9277:         }
                   9278:     }
1.536     raeburn  9279:     if (wantarray) {
                   9280:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9281:     } else {
                   9282:         return $quota;
                   9283:     }
1.472     raeburn  9284: }
                   9285: 
                   9286: ###############################################
                   9287: 
                   9288: =pod
                   9289: 
                   9290: =item * &default_quota()
                   9291: 
1.536     raeburn  9292: Retrieves default quota assigned for storage of user portfolio files,
                   9293: given an (optional) user's institutional status.
1.472     raeburn  9294: 
                   9295: Incoming parameters:
1.1142    raeburn  9296: 
1.472     raeburn  9297: 1. domain
1.536     raeburn  9298: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9299:    status types (e.g., faculty, staff, student etc.)
                   9300:    which apply to the user for whom the default is being retrieved.
                   9301:    If the institutional status string in undefined, the domain
1.1134    raeburn  9302:    default quota will be returned.
                   9303: 3.  quota name - portfolio, author, or course
                   9304:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9305: 
                   9306: Returns:
1.1142    raeburn  9307: 
1.1163    raeburn  9308: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9309: 2. (Optional) institutional type which determined the value of the
                   9310:    default quota.
1.472     raeburn  9311: 
                   9312: If a value has been stored in the domain's configuration db,
                   9313: it will return that, otherwise it returns 20 (for backwards 
                   9314: compatibility with domains which have not set up a configuration
1.1163    raeburn  9315: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9316: 
1.536     raeburn  9317: If the user's status includes multiple types (e.g., staff and student),
                   9318: the largest default quota which applies to the user determines the
                   9319: default quota returned.
                   9320: 
1.472     raeburn  9321: =cut
                   9322: 
                   9323: ###############################################
                   9324: 
                   9325: 
                   9326: sub default_quota {
1.1134    raeburn  9327:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9328:     my ($defquota,$settingstatus);
                   9329:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9330:                                             ['quotas'],$udom);
1.1134    raeburn  9331:     my $key = 'defaultquota';
                   9332:     if ($quotaname eq 'author') {
                   9333:         $key = 'authorquota';
                   9334:     }
1.622     raeburn  9335:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9336:         if ($inststatus ne '') {
1.765     raeburn  9337:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9338:             foreach my $item (@statuses) {
1.1134    raeburn  9339:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9340:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9341:                         if ($defquota eq '') {
1.1134    raeburn  9342:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9343:                             $settingstatus = $item;
1.1134    raeburn  9344:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9345:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9346:                             $settingstatus = $item;
                   9347:                         }
                   9348:                     }
1.1134    raeburn  9349:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9350:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9351:                         if ($defquota eq '') {
                   9352:                             $defquota = $quotahash{'quotas'}{$item};
                   9353:                             $settingstatus = $item;
                   9354:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9355:                             $defquota = $quotahash{'quotas'}{$item};
                   9356:                             $settingstatus = $item;
                   9357:                         }
1.536     raeburn  9358:                     }
                   9359:                 }
                   9360:             }
                   9361:         }
                   9362:         if ($defquota eq '') {
1.1134    raeburn  9363:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9364:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9365:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9366:                 $defquota = $quotahash{'quotas'}{'default'};
                   9367:             }
1.536     raeburn  9368:             $settingstatus = 'default';
1.1139    raeburn  9369:             if ($defquota eq '') {
                   9370:                 if ($quotaname eq 'author') {
                   9371:                     $defquota = 500;
                   9372:                 }
                   9373:             }
1.536     raeburn  9374:         }
                   9375:     } else {
                   9376:         $settingstatus = 'default';
1.1134    raeburn  9377:         if ($quotaname eq 'author') {
                   9378:             $defquota = 500;
                   9379:         } else {
                   9380:             $defquota = 20;
                   9381:         }
1.536     raeburn  9382:     }
                   9383:     if (wantarray) {
                   9384:         return ($defquota,$settingstatus);
1.472     raeburn  9385:     } else {
1.536     raeburn  9386:         return $defquota;
1.472     raeburn  9387:     }
                   9388: }
                   9389: 
1.1135    raeburn  9390: ###############################################
                   9391: 
                   9392: =pod
                   9393: 
1.1136    raeburn  9394: =item * &excess_filesize_warning()
1.1135    raeburn  9395: 
                   9396: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9397: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9398: space to be exceeded.
1.1136    raeburn  9399: 
                   9400: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9401: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9402: 
1.1165    raeburn  9403: Inputs: 7 
1.1136    raeburn  9404: 1. username or coursenum
1.1135    raeburn  9405: 2. domain
1.1136    raeburn  9406: 3. context ('author' or 'course')
1.1135    raeburn  9407: 4. filename of file for which action is being requested
                   9408: 5. filesize (kB) of file
                   9409: 6. action being taken: copy or upload.
1.1165    raeburn  9410: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  9411: 
                   9412: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9413:          otherwise return null.
                   9414: 
                   9415: =back
1.1135    raeburn  9416: 
                   9417: =cut
                   9418: 
1.1136    raeburn  9419: sub excess_filesize_warning {
1.1165    raeburn  9420:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9421:     my $current_disk_usage = 0;
1.1165    raeburn  9422:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9423:     if ($context eq 'author') {
                   9424:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9425:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9426:     } else {
                   9427:         foreach my $subdir ('docs','supplemental') {
                   9428:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9429:         }
                   9430:     }
1.1135    raeburn  9431:     $disk_quota = int($disk_quota * 1000);
                   9432:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9433:         return '<p class="LC_warning">'.
1.1135    raeburn  9434:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9435:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9436:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9437:                             $disk_quota,$current_disk_usage).
                   9438:                '</p>';
                   9439:     }
                   9440:     return;
                   9441: }
                   9442: 
                   9443: ###############################################
                   9444: 
                   9445: 
1.1136    raeburn  9446: 
                   9447: 
1.384     raeburn  9448: sub get_secgrprole_info {
                   9449:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9450:     my %sections_count = &get_sections($cdom,$cnum);
                   9451:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9452:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9453:     my @groups = sort(keys(%curr_groups));
                   9454:     my $allroles = [];
                   9455:     my $rolehash;
                   9456:     my $accesshash = {
                   9457:                      active => 'Currently has access',
                   9458:                      future => 'Will have future access',
                   9459:                      previous => 'Previously had access',
                   9460:                   };
                   9461:     if ($needroles) {
                   9462:         $rolehash = {'all' => 'all'};
1.385     albertel 9463:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9464: 	if (&Apache::lonnet::error(%user_roles)) {
                   9465: 	    undef(%user_roles);
                   9466: 	}
                   9467:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9468:             my ($role)=split(/\:/,$item,2);
                   9469:             if ($role eq 'cr') { next; }
                   9470:             if ($role =~ /^cr/) {
                   9471:                 $$rolehash{$role} = (split('/',$role))[3];
                   9472:             } else {
                   9473:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9474:             }
                   9475:         }
                   9476:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9477:             push(@{$allroles},$key);
                   9478:         }
                   9479:         push (@{$allroles},'st');
                   9480:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9481:     }
                   9482:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9483: }
                   9484: 
1.555     raeburn  9485: sub user_picker {
1.994     raeburn  9486:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9487:     my $currdom = $dom;
                   9488:     my %curr_selected = (
                   9489:                         srchin => 'dom',
1.580     raeburn  9490:                         srchby => 'lastname',
1.555     raeburn  9491:                       );
                   9492:     my $srchterm;
1.625     raeburn  9493:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9494:         if ($srch->{'srchby'} ne '') {
                   9495:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9496:         }
                   9497:         if ($srch->{'srchin'} ne '') {
                   9498:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9499:         }
                   9500:         if ($srch->{'srchtype'} ne '') {
                   9501:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9502:         }
                   9503:         if ($srch->{'srchdomain'} ne '') {
                   9504:             $currdom = $srch->{'srchdomain'};
                   9505:         }
                   9506:         $srchterm = $srch->{'srchterm'};
                   9507:     }
                   9508:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9509:                     'usr'       => 'Search criteria',
1.563     raeburn  9510:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9511:                     'uname'     => 'username',
                   9512:                     'lastname'  => 'last name',
1.555     raeburn  9513:                     'lastfirst' => 'last name, first name',
1.558     albertel 9514:                     'crs'       => 'in this course',
1.576     raeburn  9515:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9516:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9517:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9518:                     'exact'     => 'is',
                   9519:                     'contains'  => 'contains',
1.569     raeburn  9520:                     'begins'    => 'begins with',
1.571     raeburn  9521:                     'youm'      => "You must include some text to search for.",
                   9522:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9523:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9524:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9525:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9526:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9527:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9528:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9529:                                        );
1.563     raeburn  9530:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9531:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9532: 
                   9533:     my @srchins = ('crs','dom','alc','instd');
                   9534: 
                   9535:     foreach my $option (@srchins) {
                   9536:         # FIXME 'alc' option unavailable until 
                   9537:         #       loncreateuser::print_user_query_page()
                   9538:         #       has been completed.
                   9539:         next if ($option eq 'alc');
1.880     raeburn  9540:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9541:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9542:         if ($curr_selected{'srchin'} eq $option) {
                   9543:             $srchinsel .= ' 
                   9544:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9545:         } else {
                   9546:             $srchinsel .= '
                   9547:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9548:         }
1.555     raeburn  9549:     }
1.563     raeburn  9550:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9551: 
                   9552:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9553:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9554:         if ($curr_selected{'srchby'} eq $option) {
                   9555:             $srchbysel .= '
                   9556:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9557:         } else {
                   9558:             $srchbysel .= '
                   9559:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9560:          }
                   9561:     }
                   9562:     $srchbysel .= "\n  </select>\n";
                   9563: 
                   9564:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9565:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9566:         if ($curr_selected{'srchtype'} eq $option) {
                   9567:             $srchtypesel .= '
                   9568:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9569:         } else {
                   9570:             $srchtypesel .= '
                   9571:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9572:         }
                   9573:     }
                   9574:     $srchtypesel .= "\n  </select>\n";
                   9575: 
1.558     albertel 9576:     my ($newuserscript,$new_user_create);
1.994     raeburn  9577:     my $context_dom = $env{'request.role.domain'};
                   9578:     if ($context eq 'requestcrs') {
                   9579:         if ($env{'form.coursedom'} ne '') { 
                   9580:             $context_dom = $env{'form.coursedom'};
                   9581:         }
                   9582:     }
1.556     raeburn  9583:     if ($forcenewuser) {
1.576     raeburn  9584:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9585:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9586:                 if ($cancreate) {
                   9587:                     $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>';
                   9588:                 } else {
1.799     bisitz   9589:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9590:                     my %usertypetext = (
                   9591:                         official   => 'institutional',
                   9592:                         unofficial => 'non-institutional',
                   9593:                     );
1.799     bisitz   9594:                     $new_user_create = '<p class="LC_warning">'
                   9595:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9596:                                       .' '
                   9597:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9598:                                           ,'<a href="'.$helplink.'">','</a>')
                   9599:                                       .'</p><br />';
1.627     raeburn  9600:                 }
1.576     raeburn  9601:             }
                   9602:         }
                   9603: 
1.556     raeburn  9604:         $newuserscript = <<"ENDSCRIPT";
                   9605: 
1.570     raeburn  9606: function setSearch(createnew,callingForm) {
1.556     raeburn  9607:     if (createnew == 1) {
1.570     raeburn  9608:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9609:             if (callingForm.srchby.options[i].value == 'uname') {
                   9610:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9611:             }
                   9612:         }
1.570     raeburn  9613:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9614:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9615: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9616:             }
                   9617:         }
1.570     raeburn  9618:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9619:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9620:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9621:             }
                   9622:         }
1.570     raeburn  9623:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9624:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9625:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9626:             }
                   9627:         }
                   9628:     }
                   9629: }
                   9630: ENDSCRIPT
1.558     albertel 9631: 
1.556     raeburn  9632:     }
                   9633: 
1.555     raeburn  9634:     my $output = <<"END_BLOCK";
1.556     raeburn  9635: <script type="text/javascript">
1.824     bisitz   9636: // <![CDATA[
1.570     raeburn  9637: function validateEntry(callingForm) {
1.558     albertel 9638: 
1.556     raeburn  9639:     var checkok = 1;
1.558     albertel 9640:     var srchin;
1.570     raeburn  9641:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9642: 	if ( callingForm.srchin[i].checked ) {
                   9643: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9644: 	}
                   9645:     }
                   9646: 
1.570     raeburn  9647:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9648:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9649:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9650:     var srchterm =  callingForm.srchterm.value;
                   9651:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9652:     var msg = "";
                   9653: 
                   9654:     if (srchterm == "") {
                   9655:         checkok = 0;
1.571     raeburn  9656:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9657:     }
                   9658: 
1.569     raeburn  9659:     if (srchtype== 'begins') {
                   9660:         if (srchterm.length < 2) {
                   9661:             checkok = 0;
1.571     raeburn  9662:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9663:         }
                   9664:     }
                   9665: 
1.556     raeburn  9666:     if (srchtype== 'contains') {
                   9667:         if (srchterm.length < 3) {
                   9668:             checkok = 0;
1.571     raeburn  9669:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9670:         }
                   9671:     }
                   9672:     if (srchin == 'instd') {
                   9673:         if (srchdomain == '') {
                   9674:             checkok = 0;
1.571     raeburn  9675:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9676:         }
                   9677:     }
                   9678:     if (srchin == 'dom') {
                   9679:         if (srchdomain == '') {
                   9680:             checkok = 0;
1.571     raeburn  9681:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9682:         }
                   9683:     }
                   9684:     if (srchby == 'lastfirst') {
                   9685:         if (srchterm.indexOf(",") == -1) {
                   9686:             checkok = 0;
1.571     raeburn  9687:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9688:         }
                   9689:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9690:             checkok = 0;
1.571     raeburn  9691:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9692:         }
                   9693:     }
                   9694:     if (checkok == 0) {
1.571     raeburn  9695:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9696:         return;
                   9697:     }
                   9698:     if (checkok == 1) {
1.570     raeburn  9699:         callingForm.submit();
1.556     raeburn  9700:     }
                   9701: }
                   9702: 
                   9703: $newuserscript
                   9704: 
1.824     bisitz   9705: // ]]>
1.556     raeburn  9706: </script>
1.558     albertel 9707: 
                   9708: $new_user_create
                   9709: 
1.555     raeburn  9710: END_BLOCK
1.558     albertel 9711: 
1.876     raeburn  9712:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9713:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9714:                $domform.
                   9715:                &Apache::lonhtmlcommon::row_closure().
                   9716:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9717:                $srchbysel.
                   9718:                $srchtypesel. 
                   9719:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9720:                $srchinsel.
                   9721:                &Apache::lonhtmlcommon::row_closure(1). 
                   9722:                &Apache::lonhtmlcommon::end_pick_box().
                   9723:                '<br />';
1.555     raeburn  9724:     return $output;
                   9725: }
                   9726: 
1.612     raeburn  9727: sub user_rule_check {
1.615     raeburn  9728:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9729:     my $response;
                   9730:     if (ref($usershash) eq 'HASH') {
                   9731:         foreach my $user (keys(%{$usershash})) {
                   9732:             my ($uname,$udom) = split(/:/,$user);
                   9733:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9734:             my ($id,$newuser);
1.612     raeburn  9735:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9736:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9737:                 $id = $usershash->{$user}->{'id'};
                   9738:             }
                   9739:             my $inst_response;
                   9740:             if (ref($checks) eq 'HASH') {
                   9741:                 if (defined($checks->{'username'})) {
1.615     raeburn  9742:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9743:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9744:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9745:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9746:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9747:                 }
1.615     raeburn  9748:             } else {
                   9749:                 ($inst_response,%{$inst_results->{$user}}) =
                   9750:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9751:                 return;
1.612     raeburn  9752:             }
1.615     raeburn  9753:             if (!$got_rules->{$udom}) {
1.612     raeburn  9754:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9755:                                                   ['usercreation'],$udom);
                   9756:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9757:                     foreach my $item ('username','id') {
1.612     raeburn  9758:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9759:                             $$curr_rules{$udom}{$item} = 
                   9760:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9761:                         }
                   9762:                     }
                   9763:                 }
1.615     raeburn  9764:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9765:             }
1.612     raeburn  9766:             foreach my $item (keys(%{$checks})) {
                   9767:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9768:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9769:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9770:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9771:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9772:                                 if ($rule_check{$rule}) {
                   9773:                                     $$rulematch{$user}{$item} = $rule;
                   9774:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9775:                                         if (ref($inst_results) eq 'HASH') {
                   9776:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9777:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9778:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9779:                                                 }
1.612     raeburn  9780:                                             }
                   9781:                                         }
1.615     raeburn  9782:                                     }
                   9783:                                     last;
1.585     raeburn  9784:                                 }
                   9785:                             }
                   9786:                         }
                   9787:                     }
                   9788:                 }
                   9789:             }
                   9790:         }
                   9791:     }
1.612     raeburn  9792:     return;
                   9793: }
                   9794: 
                   9795: sub user_rule_formats {
                   9796:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9797:     my %text = ( 
                   9798:                  'username' => 'Usernames',
                   9799:                  'id'       => 'IDs',
                   9800:                );
                   9801:     my $output;
                   9802:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9803:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9804:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9805:             $output = '<br />'.
                   9806:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9807:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9808:                       ' <ul>';
1.612     raeburn  9809:             foreach my $rule (@{$ruleorder}) {
                   9810:                 if (ref($curr_rules) eq 'ARRAY') {
                   9811:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9812:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9813:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9814:                                         $rules->{$rule}{'desc'}.'</li>';
                   9815:                         }
                   9816:                     }
                   9817:                 }
                   9818:             }
                   9819:             $output .= '</ul>';
                   9820:         }
                   9821:     }
                   9822:     return $output;
                   9823: }
                   9824: 
                   9825: sub instrule_disallow_msg {
1.615     raeburn  9826:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9827:     my $response;
                   9828:     my %text = (
                   9829:                   item   => 'username',
                   9830:                   items  => 'usernames',
                   9831:                   match  => 'matches',
                   9832:                   do     => 'does',
                   9833:                   action => 'a username',
                   9834:                   one    => 'one',
                   9835:                );
                   9836:     if ($count > 1) {
                   9837:         $text{'item'} = 'usernames';
                   9838:         $text{'match'} ='match';
                   9839:         $text{'do'} = 'do';
                   9840:         $text{'action'} = 'usernames',
                   9841:         $text{'one'} = 'ones';
                   9842:     }
                   9843:     if ($checkitem eq 'id') {
                   9844:         $text{'items'} = 'IDs';
                   9845:         $text{'item'} = 'ID';
                   9846:         $text{'action'} = 'an ID';
1.615     raeburn  9847:         if ($count > 1) {
                   9848:             $text{'item'} = 'IDs';
                   9849:             $text{'action'} = 'IDs';
                   9850:         }
1.612     raeburn  9851:     }
1.674     bisitz   9852:     $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  9853:     if ($mode eq 'upload') {
                   9854:         if ($checkitem eq 'username') {
                   9855:             $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'}.");
                   9856:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9857:             $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  9858:         }
1.669     raeburn  9859:     } elsif ($mode eq 'selfcreate') {
                   9860:         if ($checkitem eq 'id') {
                   9861:             $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.");
                   9862:         }
1.615     raeburn  9863:     } else {
                   9864:         if ($checkitem eq 'username') {
                   9865:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9866:         } elsif ($checkitem eq 'id') {
                   9867:             $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.");
                   9868:         }
1.612     raeburn  9869:     }
                   9870:     return $response;
1.585     raeburn  9871: }
                   9872: 
1.624     raeburn  9873: sub personal_data_fieldtitles {
                   9874:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9875:                         id => 'Student/Employee ID',
                   9876:                         permanentemail => 'E-mail address',
                   9877:                         lastname => 'Last Name',
                   9878:                         firstname => 'First Name',
                   9879:                         middlename => 'Middle Name',
                   9880:                         generation => 'Generation',
                   9881:                         gen => 'Generation',
1.765     raeburn  9882:                         inststatus => 'Affiliation',
1.624     raeburn  9883:                    );
                   9884:     return %fieldtitles;
                   9885: }
                   9886: 
1.642     raeburn  9887: sub sorted_inst_types {
                   9888:     my ($dom) = @_;
1.1185    raeburn  9889:     my ($usertypes,$order);
                   9890:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9891:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9892:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9893:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9894:     } else {
                   9895:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9896:     }
1.642     raeburn  9897:     my $othertitle = &mt('All users');
                   9898:     if ($env{'request.course.id'}) {
1.668     raeburn  9899:         $othertitle  = &mt('Any users');
1.642     raeburn  9900:     }
                   9901:     my @types;
                   9902:     if (ref($order) eq 'ARRAY') {
                   9903:         @types = @{$order};
                   9904:     }
                   9905:     if (@types == 0) {
                   9906:         if (ref($usertypes) eq 'HASH') {
                   9907:             @types = sort(keys(%{$usertypes}));
                   9908:         }
                   9909:     }
                   9910:     if (keys(%{$usertypes}) > 0) {
                   9911:         $othertitle = &mt('Other users');
                   9912:     }
                   9913:     return ($othertitle,$usertypes,\@types);
                   9914: }
                   9915: 
1.645     raeburn  9916: sub get_institutional_codes {
                   9917:     my ($settings,$allcourses,$LC_code) = @_;
                   9918: # Get complete list of course sections to update
                   9919:     my @currsections = ();
                   9920:     my @currxlists = ();
                   9921:     my $coursecode = $$settings{'internal.coursecode'};
                   9922: 
                   9923:     if ($$settings{'internal.sectionnums'} ne '') {
                   9924:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9925:     }
                   9926: 
                   9927:     if ($$settings{'internal.crosslistings'} ne '') {
                   9928:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9929:     }
                   9930: 
                   9931:     if (@currxlists > 0) {
                   9932:         foreach (@currxlists) {
                   9933:             if (m/^([^:]+):(\w*)$/) {
                   9934:                 unless (grep/^$1$/,@{$allcourses}) {
                   9935:                     push @{$allcourses},$1;
                   9936:                     $$LC_code{$1} = $2;
                   9937:                 }
                   9938:             }
                   9939:         }
                   9940:     }
                   9941:  
                   9942:     if (@currsections > 0) {
                   9943:         foreach (@currsections) {
                   9944:             if (m/^(\w+):(\w*)$/) {
                   9945:                 my $sec = $coursecode.$1;
                   9946:                 my $lc_sec = $2;
                   9947:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9948:                     push @{$allcourses},$sec;
                   9949:                     $$LC_code{$sec} = $lc_sec;
                   9950:                 }
                   9951:             }
                   9952:         }
                   9953:     }
                   9954:     return;
                   9955: }
                   9956: 
1.971     raeburn  9957: sub get_standard_codeitems {
                   9958:     return ('Year','Semester','Department','Number','Section');
                   9959: }
                   9960: 
1.112     bowersj2 9961: =pod
                   9962: 
1.780     raeburn  9963: =head1 Slot Helpers
                   9964: 
                   9965: =over 4
                   9966: 
                   9967: =item * sorted_slots()
                   9968: 
1.1040    raeburn  9969: Sorts an array of slot names in order of an optional sort key,
                   9970: default sort is by slot start time (earliest first). 
1.780     raeburn  9971: 
                   9972: Inputs:
                   9973: 
                   9974: =over 4
                   9975: 
                   9976: slotsarr  - Reference to array of unsorted slot names.
                   9977: 
                   9978: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9979: 
1.1040    raeburn  9980: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9981: 
1.549     albertel 9982: =back
                   9983: 
1.780     raeburn  9984: Returns:
                   9985: 
                   9986: =over 4
                   9987: 
1.1040    raeburn  9988: sorted   - An array of slot names sorted by a specified sort key 
                   9989:            (default sort key is start time of the slot).
1.780     raeburn  9990: 
                   9991: =back
                   9992: 
                   9993: =cut
                   9994: 
                   9995: 
                   9996: sub sorted_slots {
1.1040    raeburn  9997:     my ($slotsarr,$slots,$sortkey) = @_;
                   9998:     if ($sortkey eq '') {
                   9999:         $sortkey = 'starttime';
                   10000:     }
1.780     raeburn  10001:     my @sorted;
                   10002:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10003:         @sorted =
                   10004:             sort {
                   10005:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10006:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10007:                      }
                   10008:                      if (ref($slots->{$a})) { return -1;}
                   10009:                      if (ref($slots->{$b})) { return 1;}
                   10010:                      return 0;
                   10011:                  } @{$slotsarr};
                   10012:     }
                   10013:     return @sorted;
                   10014: }
                   10015: 
1.1040    raeburn  10016: =pod
                   10017: 
                   10018: =item * get_future_slots()
                   10019: 
                   10020: Inputs:
                   10021: 
                   10022: =over 4
                   10023: 
                   10024: cnum - course number
                   10025: 
                   10026: cdom - course domain
                   10027: 
                   10028: now - current UNIX time
                   10029: 
                   10030: symb - optional symb
                   10031: 
                   10032: =back
                   10033: 
                   10034: Returns:
                   10035: 
                   10036: =over 4
                   10037: 
                   10038: sorted_reservable - ref to array of student_schedulable slots currently 
                   10039:                     reservable, ordered by end date of reservation period.
                   10040: 
                   10041: reservable_now - ref to hash of student_schedulable slots currently
                   10042:                  reservable.
                   10043: 
                   10044:     Keys in inner hash are:
                   10045:     (a) symb: either blank or symb to which slot use is restricted.
                   10046:     (b) endreserve: end date of reservation period. 
                   10047: 
                   10048: sorted_future - ref to array of student_schedulable slots reservable in
                   10049:                 the future, ordered by start date of reservation period.
                   10050: 
                   10051: future_reservable - ref to hash of student_schedulable slots reservable
                   10052:                     in the future.
                   10053: 
                   10054:     Keys in inner hash are:
                   10055:     (a) symb: either blank or symb to which slot use is restricted.
                   10056:     (b) startreserve:  start date of reservation period.
                   10057: 
                   10058: =back
                   10059: 
                   10060: =cut
                   10061: 
                   10062: sub get_future_slots {
                   10063:     my ($cnum,$cdom,$now,$symb) = @_;
                   10064:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10065:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10066:     foreach my $slot (keys(%slots)) {
                   10067:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10068:         if ($symb) {
                   10069:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10070:                      ($slots{$slot}->{'symb'} ne $symb));
                   10071:         }
                   10072:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10073:             ($slots{$slot}->{'endtime'} > $now)) {
                   10074:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10075:                 my $userallowed = 0;
                   10076:                 if ($slots{$slot}->{'allowedsections'}) {
                   10077:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10078:                     if (!defined($env{'request.role.sec'})
                   10079:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10080:                         $userallowed=1;
                   10081:                     } else {
                   10082:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10083:                             $userallowed=1;
                   10084:                         }
                   10085:                     }
                   10086:                     unless ($userallowed) {
                   10087:                         if (defined($env{'request.course.groups'})) {
                   10088:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10089:                             foreach my $group (@groups) {
                   10090:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10091:                                     $userallowed=1;
                   10092:                                     last;
                   10093:                                 }
                   10094:                             }
                   10095:                         }
                   10096:                     }
                   10097:                 }
                   10098:                 if ($slots{$slot}->{'allowedusers'}) {
                   10099:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10100:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10101:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10102:                         $userallowed = 1;
                   10103:                     }
                   10104:                 }
                   10105:                 next unless($userallowed);
                   10106:             }
                   10107:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10108:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10109:             my $symb = $slots{$slot}->{'symb'};
                   10110:             if (($startreserve < $now) &&
                   10111:                 (!$endreserve || $endreserve > $now)) {
                   10112:                 my $lastres = $endreserve;
                   10113:                 if (!$lastres) {
                   10114:                     $lastres = $slots{$slot}->{'starttime'};
                   10115:                 }
                   10116:                 $reservable_now{$slot} = {
                   10117:                                            symb       => $symb,
                   10118:                                            endreserve => $lastres
                   10119:                                          };
                   10120:             } elsif (($startreserve > $now) &&
                   10121:                      (!$endreserve || $endreserve > $startreserve)) {
                   10122:                 $future_reservable{$slot} = {
                   10123:                                               symb         => $symb,
                   10124:                                               startreserve => $startreserve
                   10125:                                             };
                   10126:             }
                   10127:         }
                   10128:     }
                   10129:     my @unsorted_reservable = keys(%reservable_now);
                   10130:     if (@unsorted_reservable > 0) {
                   10131:         @sorted_reservable = 
                   10132:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10133:     }
                   10134:     my @unsorted_future = keys(%future_reservable);
                   10135:     if (@unsorted_future > 0) {
                   10136:         @sorted_future =
                   10137:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10138:     }
                   10139:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10140: }
1.780     raeburn  10141: 
                   10142: =pod
                   10143: 
1.1057    foxr     10144: =back
                   10145: 
1.549     albertel 10146: =head1 HTTP Helpers
                   10147: 
                   10148: =over 4
                   10149: 
1.648     raeburn  10150: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10151: 
1.258     albertel 10152: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10153: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10154: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10155: 
                   10156: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10157: $possible_names is an ref to an array of form element names.  As an example:
                   10158: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10159: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10160: 
                   10161: =cut
1.1       albertel 10162: 
1.6       albertel 10163: sub get_unprocessed_cgi {
1.25      albertel 10164:   my ($query,$possible_names)= @_;
1.26      matthew  10165:   # $Apache::lonxml::debug=1;
1.356     albertel 10166:   foreach my $pair (split(/&/,$query)) {
                   10167:     my ($name, $value) = split(/=/,$pair);
1.369     www      10168:     $name = &unescape($name);
1.25      albertel 10169:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10170:       $value =~ tr/+/ /;
                   10171:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10172:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10173:     }
1.16      harris41 10174:   }
1.6       albertel 10175: }
                   10176: 
1.112     bowersj2 10177: =pod
                   10178: 
1.648     raeburn  10179: =item * &cacheheader() 
1.112     bowersj2 10180: 
                   10181: returns cache-controlling header code
                   10182: 
                   10183: =cut
                   10184: 
1.7       albertel 10185: sub cacheheader {
1.258     albertel 10186:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10187:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10188:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10189:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10190:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10191:     return $output;
1.7       albertel 10192: }
                   10193: 
1.112     bowersj2 10194: =pod
                   10195: 
1.648     raeburn  10196: =item * &no_cache($r) 
1.112     bowersj2 10197: 
                   10198: specifies header code to not have cache
                   10199: 
                   10200: =cut
                   10201: 
1.9       albertel 10202: sub no_cache {
1.216     albertel 10203:     my ($r) = @_;
                   10204:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10205: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10206:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10207:     $r->no_cache(1);
                   10208:     $r->header_out("Expires" => $date);
                   10209:     $r->header_out("Pragma" => "no-cache");
1.123     www      10210: }
                   10211: 
                   10212: sub content_type {
1.181     albertel 10213:     my ($r,$type,$charset) = @_;
1.299     foxr     10214:     if ($r) {
                   10215: 	#  Note that printout.pl calls this with undef for $r.
                   10216: 	&no_cache($r);
                   10217:     }
1.258     albertel 10218:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10219:     unless ($charset) {
                   10220: 	$charset=&Apache::lonlocal::current_encoding;
                   10221:     }
                   10222:     if ($charset) { $type.='; charset='.$charset; }
                   10223:     if ($r) {
                   10224: 	$r->content_type($type);
                   10225:     } else {
                   10226: 	print("Content-type: $type\n\n");
                   10227:     }
1.9       albertel 10228: }
1.25      albertel 10229: 
1.112     bowersj2 10230: =pod
                   10231: 
1.648     raeburn  10232: =item * &add_to_env($name,$value) 
1.112     bowersj2 10233: 
1.258     albertel 10234: adds $name to the %env hash with value
1.112     bowersj2 10235: $value, if $name already exists, the entry is converted to an array
                   10236: reference and $value is added to the array.
                   10237: 
                   10238: =cut
                   10239: 
1.25      albertel 10240: sub add_to_env {
                   10241:   my ($name,$value)=@_;
1.258     albertel 10242:   if (defined($env{$name})) {
                   10243:     if (ref($env{$name})) {
1.25      albertel 10244:       #already have multiple values
1.258     albertel 10245:       push(@{ $env{$name} },$value);
1.25      albertel 10246:     } else {
                   10247:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10248:       my $first=$env{$name};
                   10249:       undef($env{$name});
                   10250:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10251:     }
                   10252:   } else {
1.258     albertel 10253:     $env{$name}=$value;
1.25      albertel 10254:   }
1.31      albertel 10255: }
1.149     albertel 10256: 
                   10257: =pod
                   10258: 
1.648     raeburn  10259: =item * &get_env_multiple($name) 
1.149     albertel 10260: 
1.258     albertel 10261: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10262: values may be defined and end up as an array ref.
                   10263: 
                   10264: returns an array of values
                   10265: 
                   10266: =cut
                   10267: 
                   10268: sub get_env_multiple {
                   10269:     my ($name) = @_;
                   10270:     my @values;
1.258     albertel 10271:     if (defined($env{$name})) {
1.149     albertel 10272:         # exists is it an array
1.258     albertel 10273:         if (ref($env{$name})) {
                   10274:             @values=@{ $env{$name} };
1.149     albertel 10275:         } else {
1.258     albertel 10276:             $values[0]=$env{$name};
1.149     albertel 10277:         }
                   10278:     }
                   10279:     return(@values);
                   10280: }
                   10281: 
1.660     raeburn  10282: sub ask_for_embedded_content {
                   10283:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10284:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10285:         %currsubfile,%unused,$rem);
1.1071    raeburn  10286:     my $counter = 0;
                   10287:     my $numnew = 0;
1.987     raeburn  10288:     my $numremref = 0;
                   10289:     my $numinvalid = 0;
                   10290:     my $numpathchg = 0;
                   10291:     my $numexisting = 0;
1.1071    raeburn  10292:     my $numunused = 0;
                   10293:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10294:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10295:     my $heading = &mt('Upload embedded files');
                   10296:     my $buttontext = &mt('Upload');
                   10297: 
1.1085    raeburn  10298:     if ($env{'request.course.id'}) {
1.1123    raeburn  10299:         if ($actionurl eq '/adm/dependencies') {
                   10300:             $navmap = Apache::lonnavmaps::navmap->new();
                   10301:         }
                   10302:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10303:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10304:     }
1.1123    raeburn  10305:     if (($actionurl eq '/adm/portfolio') || 
                   10306:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10307:         my $current_path='/';
                   10308:         if ($env{'form.currentpath'}) {
                   10309:             $current_path = $env{'form.currentpath'};
                   10310:         }
                   10311:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10312:             $udom = $cdom;
                   10313:             $uname = $cnum;
1.984     raeburn  10314:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10315:         } else {
                   10316:             $udom = $env{'user.domain'};
                   10317:             $uname = $env{'user.name'};
                   10318:             $url = '/userfiles/portfolio';
                   10319:         }
1.987     raeburn  10320:         $toplevel = $url.'/';
1.984     raeburn  10321:         $url .= $current_path;
                   10322:         $getpropath = 1;
1.987     raeburn  10323:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10324:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10325:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10326:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10327:         $toplevel = $url;
1.984     raeburn  10328:         if ($rest ne '') {
1.987     raeburn  10329:             $url .= $rest;
                   10330:         }
                   10331:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10332:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10333:             $url = $args->{'docs_url'};
                   10334:             $toplevel = $url;
1.1084    raeburn  10335:             if ($args->{'context'} eq 'paste') {
                   10336:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10337:                 ($path) = 
                   10338:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10339:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10340:                 $fileloc =~ s{^/}{};
                   10341:             }
1.1071    raeburn  10342:         }
1.1084    raeburn  10343:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10344:         if ($env{'request.course.id'} ne '') {
                   10345:             if (ref($args) eq 'HASH') {
                   10346:                 $url = $args->{'docs_url'};
                   10347:                 $title = $args->{'docs_title'};
1.1126    raeburn  10348:                 $toplevel = $url; 
                   10349:                 unless ($toplevel =~ m{^/}) {
                   10350:                     $toplevel = "/$url";
                   10351:                 }
1.1085    raeburn  10352:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10353:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10354:                     $path = $1;
                   10355:                 } else {
                   10356:                     ($path) =
                   10357:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10358:                 }
1.1195    raeburn  10359:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10360:                     $fileloc = $toplevel;
                   10361:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10362:                     my ($udom,$uname,$fname) =
                   10363:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10364:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10365:                 } else {
                   10366:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10367:                 }
1.1071    raeburn  10368:                 $fileloc =~ s{^/}{};
                   10369:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10370:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10371:             }
1.987     raeburn  10372:         }
1.1123    raeburn  10373:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10374:         $udom = $cdom;
                   10375:         $uname = $cnum;
                   10376:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10377:         $toplevel = $url;
                   10378:         $path = $url;
                   10379:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10380:         $fileloc =~ s{^/}{};
1.987     raeburn  10381:     }
1.1126    raeburn  10382:     foreach my $file (keys(%{$allfiles})) {
                   10383:         my $embed_file;
                   10384:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10385:             $embed_file = $1;
                   10386:         } else {
                   10387:             $embed_file = $file;
                   10388:         }
1.1158    raeburn  10389:         my ($absolutepath,$cleaned_file);
                   10390:         if ($embed_file =~ m{^\w+://}) {
                   10391:             $cleaned_file = $embed_file;
1.1147    raeburn  10392:             $newfiles{$cleaned_file} = 1;
                   10393:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10394:         } else {
1.1158    raeburn  10395:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10396:             if ($embed_file =~ m{^/}) {
                   10397:                 $absolutepath = $embed_file;
                   10398:             }
1.1147    raeburn  10399:             if ($cleaned_file =~ m{/}) {
                   10400:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10401:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10402:                 my $item = $fname;
                   10403:                 if ($path ne '') {
                   10404:                     $item = $path.'/'.$fname;
                   10405:                     $subdependencies{$path}{$fname} = 1;
                   10406:                 } else {
                   10407:                     $dependencies{$item} = 1;
                   10408:                 }
                   10409:                 if ($absolutepath) {
                   10410:                     $mapping{$item} = $absolutepath;
                   10411:                 } else {
                   10412:                     $mapping{$item} = $embed_file;
                   10413:                 }
                   10414:             } else {
                   10415:                 $dependencies{$embed_file} = 1;
                   10416:                 if ($absolutepath) {
1.1147    raeburn  10417:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10418:                 } else {
1.1147    raeburn  10419:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10420:                 }
                   10421:             }
1.984     raeburn  10422:         }
                   10423:     }
1.1071    raeburn  10424:     my $dirptr = 16384;
1.984     raeburn  10425:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10426:         $currsubfile{$path} = {};
1.1123    raeburn  10427:         if (($actionurl eq '/adm/portfolio') || 
                   10428:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10429:             my ($sublistref,$listerror) =
                   10430:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10431:             if (ref($sublistref) eq 'ARRAY') {
                   10432:                 foreach my $line (@{$sublistref}) {
                   10433:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10434:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10435:                 }
1.984     raeburn  10436:             }
1.987     raeburn  10437:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10438:             if (opendir(my $dir,$url.'/'.$path)) {
                   10439:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10440:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10441:             }
1.1084    raeburn  10442:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10443:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10444:                   ($args->{'context'} eq 'paste')) ||
                   10445:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10446:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10447:                 my $dir;
                   10448:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10449:                     $dir = $fileloc;
                   10450:                 } else {
                   10451:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10452:                 }
1.1071    raeburn  10453:                 if ($dir ne '') {
                   10454:                     my ($sublistref,$listerror) =
                   10455:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10456:                     if (ref($sublistref) eq 'ARRAY') {
                   10457:                         foreach my $line (@{$sublistref}) {
                   10458:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10459:                                 undef,$mtime)=split(/\&/,$line,12);
                   10460:                             unless (($testdir&$dirptr) ||
                   10461:                                     ($file_name =~ /^\.\.?$/)) {
                   10462:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10463:                             }
                   10464:                         }
                   10465:                     }
                   10466:                 }
1.984     raeburn  10467:             }
                   10468:         }
                   10469:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10470:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10471:                 my $item = $path.'/'.$file;
                   10472:                 unless ($mapping{$item} eq $item) {
                   10473:                     $pathchanges{$item} = 1;
                   10474:                 }
                   10475:                 $existing{$item} = 1;
                   10476:                 $numexisting ++;
                   10477:             } else {
                   10478:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10479:             }
                   10480:         }
1.1071    raeburn  10481:         if ($actionurl eq '/adm/dependencies') {
                   10482:             foreach my $path (keys(%currsubfile)) {
                   10483:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10484:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10485:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10486:                              next if (($rem ne '') &&
                   10487:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10488:                                        (ref($navmap) &&
                   10489:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10490:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10491:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10492:                              $unused{$path.'/'.$file} = 1; 
                   10493:                          }
                   10494:                     }
                   10495:                 }
                   10496:             }
                   10497:         }
1.984     raeburn  10498:     }
1.987     raeburn  10499:     my %currfile;
1.1123    raeburn  10500:     if (($actionurl eq '/adm/portfolio') ||
                   10501:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10502:         my ($dirlistref,$listerror) =
                   10503:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10504:         if (ref($dirlistref) eq 'ARRAY') {
                   10505:             foreach my $line (@{$dirlistref}) {
                   10506:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10507:                 $currfile{$file_name} = 1;
                   10508:             }
1.984     raeburn  10509:         }
1.987     raeburn  10510:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10511:         if (opendir(my $dir,$url)) {
1.987     raeburn  10512:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10513:             map {$currfile{$_} = 1;} @dir_list;
                   10514:         }
1.1084    raeburn  10515:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10516:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10517:               ($args->{'context'} eq 'paste')) ||
                   10518:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10519:         if ($env{'request.course.id'} ne '') {
                   10520:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10521:             if ($dir ne '') {
                   10522:                 my ($dirlistref,$listerror) =
                   10523:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10524:                 if (ref($dirlistref) eq 'ARRAY') {
                   10525:                     foreach my $line (@{$dirlistref}) {
                   10526:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10527:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10528:                         unless (($testdir&$dirptr) ||
                   10529:                                 ($file_name =~ /^\.\.?$/)) {
                   10530:                             $currfile{$file_name} = [$size,$mtime];
                   10531:                         }
                   10532:                     }
                   10533:                 }
                   10534:             }
                   10535:         }
1.984     raeburn  10536:     }
                   10537:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10538:         if (exists($currfile{$file})) {
1.987     raeburn  10539:             unless ($mapping{$file} eq $file) {
                   10540:                 $pathchanges{$file} = 1;
                   10541:             }
                   10542:             $existing{$file} = 1;
                   10543:             $numexisting ++;
                   10544:         } else {
1.984     raeburn  10545:             $newfiles{$file} = 1;
                   10546:         }
                   10547:     }
1.1071    raeburn  10548:     foreach my $file (keys(%currfile)) {
                   10549:         unless (($file eq $filename) ||
                   10550:                 ($file eq $filename.'.bak') ||
                   10551:                 ($dependencies{$file})) {
1.1085    raeburn  10552:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10553:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10554:                     next if (($rem ne '') &&
                   10555:                              (($env{"httpref.$rem".$file} ne '') ||
                   10556:                               (ref($navmap) &&
                   10557:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10558:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10559:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10560:                 }
1.1085    raeburn  10561:             }
1.1071    raeburn  10562:             $unused{$file} = 1;
                   10563:         }
                   10564:     }
1.1084    raeburn  10565:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10566:         ($args->{'context'} eq 'paste')) {
                   10567:         $counter = scalar(keys(%existing));
                   10568:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10569:         return ($output,$counter,$numpathchg,\%existing);
                   10570:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10571:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10572:         $counter = scalar(keys(%existing));
                   10573:         $numpathchg = scalar(keys(%pathchanges));
                   10574:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10575:     }
1.984     raeburn  10576:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10577:         if ($actionurl eq '/adm/dependencies') {
                   10578:             next if ($embed_file =~ m{^\w+://});
                   10579:         }
1.660     raeburn  10580:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10581:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10582:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10583:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10584:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10585:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10586:         }
1.1123    raeburn  10587:         $upload_output .= '</td>';
1.1071    raeburn  10588:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10589:             $upload_output.='<td align="right">'.
                   10590:                             '<span class="LC_info LC_fontsize_medium">'.
                   10591:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10592:             $numremref++;
1.660     raeburn  10593:         } elsif ($args->{'error_on_invalid_names'}
                   10594:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10595:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10596:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10597:             $numinvalid++;
1.660     raeburn  10598:         } else {
1.1123    raeburn  10599:             $upload_output .= '<td>'.
                   10600:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10601:                                                      $embed_file,\%mapping,
1.1071    raeburn  10602:                                                      $allfiles,$codebase,'upload');
                   10603:             $counter ++;
                   10604:             $numnew ++;
1.987     raeburn  10605:         }
                   10606:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10607:     }
                   10608:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10609:         if ($actionurl eq '/adm/dependencies') {
                   10610:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10611:             $modify_output .= &start_data_table_row().
                   10612:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10613:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10614:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10615:                               '<td>'.$size.'</td>'.
                   10616:                               '<td>'.$mtime.'</td>'.
                   10617:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10618:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10619:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10620:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10621:                               &embedded_file_element('upload_embedded',$counter,
                   10622:                                                      $embed_file,\%mapping,
                   10623:                                                      $allfiles,$codebase,'modify').
                   10624:                               '</div></td>'.
                   10625:                               &end_data_table_row()."\n";
                   10626:             $counter ++;
                   10627:         } else {
                   10628:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10629:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10630:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10631:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10632:                               &Apache::loncommon::end_data_table_row()."\n";
                   10633:         }
                   10634:     }
                   10635:     my $delidx = $counter;
                   10636:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10637:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10638:         $delete_output .= &start_data_table_row().
                   10639:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10640:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10641:                           '<td>'.$size.'</td>'.
                   10642:                           '<td>'.$mtime.'</td>'.
                   10643:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10644:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10645:                           &embedded_file_element('upload_embedded',$delidx,
                   10646:                                                  $oldfile,\%mapping,$allfiles,
                   10647:                                                  $codebase,'delete').'</td>'.
                   10648:                           &end_data_table_row()."\n"; 
                   10649:         $numunused ++;
                   10650:         $delidx ++;
1.987     raeburn  10651:     }
                   10652:     if ($upload_output) {
                   10653:         $upload_output = &start_data_table().
                   10654:                          $upload_output.
                   10655:                          &end_data_table()."\n";
                   10656:     }
1.1071    raeburn  10657:     if ($modify_output) {
                   10658:         $modify_output = &start_data_table().
                   10659:                          &start_data_table_header_row().
                   10660:                          '<th>'.&mt('File').'</th>'.
                   10661:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10662:                          '<th>'.&mt('Modified').'</th>'.
                   10663:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10664:                          &end_data_table_header_row().
                   10665:                          $modify_output.
                   10666:                          &end_data_table()."\n";
                   10667:     }
                   10668:     if ($delete_output) {
                   10669:         $delete_output = &start_data_table().
                   10670:                          &start_data_table_header_row().
                   10671:                          '<th>'.&mt('File').'</th>'.
                   10672:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10673:                          '<th>'.&mt('Modified').'</th>'.
                   10674:                          '<th>'.&mt('Delete?').'</th>'.
                   10675:                          &end_data_table_header_row().
                   10676:                          $delete_output.
                   10677:                          &end_data_table()."\n";
                   10678:     }
1.987     raeburn  10679:     my $applies = 0;
                   10680:     if ($numremref) {
                   10681:         $applies ++;
                   10682:     }
                   10683:     if ($numinvalid) {
                   10684:         $applies ++;
                   10685:     }
                   10686:     if ($numexisting) {
                   10687:         $applies ++;
                   10688:     }
1.1071    raeburn  10689:     if ($counter || $numunused) {
1.987     raeburn  10690:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10691:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10692:                   $state.'<h3>'.$heading.'</h3>'; 
                   10693:         if ($actionurl eq '/adm/dependencies') {
                   10694:             if ($numnew) {
                   10695:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10696:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10697:                            $upload_output.'<br />'."\n";
                   10698:             }
                   10699:             if ($numexisting) {
                   10700:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10701:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10702:                            $modify_output.'<br />'."\n";
                   10703:                            $buttontext = &mt('Save changes');
                   10704:             }
                   10705:             if ($numunused) {
                   10706:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10707:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10708:                            $delete_output.'<br />'."\n";
                   10709:                            $buttontext = &mt('Save changes');
                   10710:             }
                   10711:         } else {
                   10712:             $output .= $upload_output.'<br />'."\n";
                   10713:         }
                   10714:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10715:                    $counter.'" />'."\n";
                   10716:         if ($actionurl eq '/adm/dependencies') { 
                   10717:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10718:                        $numnew.'" />'."\n";
                   10719:         } elsif ($actionurl eq '') {
1.987     raeburn  10720:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10721:         }
                   10722:     } elsif ($applies) {
                   10723:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10724:         if ($applies > 1) {
                   10725:             $output .=  
1.1123    raeburn  10726:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10727:             if ($numremref) {
                   10728:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10729:             }
                   10730:             if ($numinvalid) {
                   10731:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10732:             }
                   10733:             if ($numexisting) {
                   10734:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10735:             }
                   10736:             $output .= '</ul><br />';
                   10737:         } elsif ($numremref) {
                   10738:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10739:         } elsif ($numinvalid) {
                   10740:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10741:         } elsif ($numexisting) {
                   10742:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10743:         }
                   10744:         $output .= $upload_output.'<br />';
                   10745:     }
                   10746:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10747:     $chgcount = $counter;
1.987     raeburn  10748:     if (keys(%pathchanges) > 0) {
                   10749:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10750:             if ($counter) {
1.987     raeburn  10751:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10752:                                                   $embed_file,\%mapping,
1.1071    raeburn  10753:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10754:             } else {
                   10755:                 $pathchange_output .= 
                   10756:                     &start_data_table_row().
                   10757:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10758:                     $chgcount.'" checked="checked" /></td>'.
                   10759:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10760:                     '<td>'.$embed_file.
                   10761:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10762:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10763:                     '</td>'.&end_data_table_row();
1.660     raeburn  10764:             }
1.987     raeburn  10765:             $numpathchg ++;
                   10766:             $chgcount ++;
1.660     raeburn  10767:         }
                   10768:     }
1.1127    raeburn  10769:     if (($counter) || ($numunused)) {
1.987     raeburn  10770:         if ($numpathchg) {
                   10771:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10772:                        $numpathchg.'" />'."\n";
                   10773:         }
                   10774:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10775:             ($actionurl eq '/adm/imsimport')) {
                   10776:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10777:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10778:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10779:         } elsif ($actionurl eq '/adm/dependencies') {
                   10780:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10781:         }
1.1123    raeburn  10782:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10783:     } elsif ($numpathchg) {
                   10784:         my %pathchange = ();
                   10785:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10786:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10787:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  10788:         }
1.987     raeburn  10789:     }
1.1071    raeburn  10790:     return ($output,$counter,$numpathchg);
1.987     raeburn  10791: }
                   10792: 
1.1147    raeburn  10793: =pod
                   10794: 
                   10795: =item * clean_path($name)
                   10796: 
                   10797: Performs clean-up of directories, subdirectories and filename in an
                   10798: embedded object, referenced in an HTML file which is being uploaded
                   10799: to a course or portfolio, where 
                   10800: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10801: checked.
                   10802: 
                   10803: Clean-up is similar to replacements in lonnet::clean_filename()
                   10804: except each / between sub-directory and next level is preserved.
                   10805: 
                   10806: =cut
                   10807: 
                   10808: sub clean_path {
                   10809:     my ($embed_file) = @_;
                   10810:     $embed_file =~s{^/+}{};
                   10811:     my @contents;
                   10812:     if ($embed_file =~ m{/}) {
                   10813:         @contents = split(/\//,$embed_file);
                   10814:     } else {
                   10815:         @contents = ($embed_file);
                   10816:     }
                   10817:     my $lastidx = scalar(@contents)-1;
                   10818:     for (my $i=0; $i<=$lastidx; $i++) { 
                   10819:         $contents[$i]=~s{\\}{/}g;
                   10820:         $contents[$i]=~s/\s+/\_/g;
                   10821:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10822:         if ($i == $lastidx) {
                   10823:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10824:         }
                   10825:     }
                   10826:     if ($lastidx > 0) {
                   10827:         return join('/',@contents);
                   10828:     } else {
                   10829:         return $contents[0];
                   10830:     }
                   10831: }
                   10832: 
1.987     raeburn  10833: sub embedded_file_element {
1.1071    raeburn  10834:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10835:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10836:                    (ref($codebase) eq 'HASH'));
                   10837:     my $output;
1.1071    raeburn  10838:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10839:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10840:     }
                   10841:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10842:                &escape($embed_file).'" />';
                   10843:     unless (($context eq 'upload_embedded') && 
                   10844:             ($mapping->{$embed_file} eq $embed_file)) {
                   10845:         $output .='
                   10846:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10847:     }
                   10848:     my $attrib;
                   10849:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10850:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10851:     }
                   10852:     $output .=
                   10853:         "\n\t\t".
                   10854:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10855:         $attrib.'" />';
                   10856:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10857:         $output .=
                   10858:             "\n\t\t".
                   10859:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10860:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10861:     }
1.987     raeburn  10862:     return $output;
1.660     raeburn  10863: }
                   10864: 
1.1071    raeburn  10865: sub get_dependency_details {
                   10866:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10867:     my ($size,$mtime,$showsize,$showmtime);
                   10868:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10869:         if ($embed_file =~ m{/}) {
                   10870:             my ($path,$fname) = split(/\//,$embed_file);
                   10871:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10872:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10873:             }
                   10874:         } else {
                   10875:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10876:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10877:             }
                   10878:         }
                   10879:         $showsize = $size/1024.0;
                   10880:         $showsize = sprintf("%.1f",$showsize);
                   10881:         if ($mtime > 0) {
                   10882:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10883:         }
                   10884:     }
                   10885:     return ($showsize,$showmtime);
                   10886: }
                   10887: 
                   10888: sub ask_embedded_js {
                   10889:     return <<"END";
                   10890: <script type="text/javascript"">
                   10891: // <![CDATA[
                   10892: function toggleBrowse(counter) {
                   10893:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10894:     var fileid = document.getElementById('embedded_item_'+counter);
                   10895:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10896:     if (chkboxid.checked == true) {
                   10897:         uploaddivid.style.display='block';
                   10898:     } else {
                   10899:         uploaddivid.style.display='none';
                   10900:         fileid.value = '';
                   10901:     }
                   10902: }
                   10903: // ]]>
                   10904: </script>
                   10905: 
                   10906: END
                   10907: }
                   10908: 
1.661     raeburn  10909: sub upload_embedded {
                   10910:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10911:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10912:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10913:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10914:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10915:         my $orig_uploaded_filename =
                   10916:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10917:         foreach my $type ('orig','ref','attrib','codebase') {
                   10918:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10919:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10920:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10921:             }
                   10922:         }
1.661     raeburn  10923:         my ($path,$fname) =
                   10924:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10925:         # no path, whole string is fname
                   10926:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10927:         $fname = &Apache::lonnet::clean_filename($fname);
                   10928:         # See if there is anything left
                   10929:         next if ($fname eq '');
                   10930: 
                   10931:         # Check if file already exists as a file or directory.
                   10932:         my ($state,$msg);
                   10933:         if ($context eq 'portfolio') {
                   10934:             my $port_path = $dirpath;
                   10935:             if ($group ne '') {
                   10936:                 $port_path = "groups/$group/$port_path";
                   10937:             }
1.987     raeburn  10938:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10939:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10940:                                               $dir_root,$port_path,$disk_quota,
                   10941:                                               $current_disk_usage,$uname,$udom);
                   10942:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10943:                 || $state eq 'file_locked') {
1.661     raeburn  10944:                 $output .= $msg;
                   10945:                 next;
                   10946:             }
                   10947:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10948:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10949:             if ($state eq 'exists') {
                   10950:                 $output .= $msg;
                   10951:                 next;
                   10952:             }
                   10953:         }
                   10954:         # Check if extension is valid
                   10955:         if (($fname =~ /\.(\w+)$/) &&
                   10956:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   10957:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10958:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10959:             next;
                   10960:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10961:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10962:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10963:             next;
                   10964:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10965:             $output .= &mt('Filename not allowed - rename the file to remove the number immediately before the file extension([_1]) and re-upload.',$2).'<br />';
1.661     raeburn  10966:             next;
                   10967:         }
                   10968:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  10969:         my $subdir = $path;
                   10970:         $subdir =~ s{/+$}{};
1.661     raeburn  10971:         if ($context eq 'portfolio') {
1.984     raeburn  10972:             my $result;
                   10973:             if ($state eq 'existingfile') {
                   10974:                 $result=
                   10975:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  10976:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10977:             } else {
1.984     raeburn  10978:                 $result=
                   10979:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10980:                                                     $dirpath.
1.1123    raeburn  10981:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10982:                 if ($result !~ m|^/uploaded/|) {
                   10983:                     $output .= '<span class="LC_error">'
                   10984:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10985:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10986:                                .'</span><br />';
                   10987:                     next;
                   10988:                 } else {
1.987     raeburn  10989:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10990:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10991:                 }
1.661     raeburn  10992:             }
1.1123    raeburn  10993:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  10994:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10995:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10996:             my $result =
1.1126    raeburn  10997:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10998:             if ($result !~ m|^/uploaded/|) {
                   10999:                 $output .= '<span class="LC_error">'
                   11000:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11001:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11002:                            .'</span><br />';
                   11003:                     next;
                   11004:             } else {
                   11005:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11006:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11007:                 if ($context eq 'syllabus') {
                   11008:                     &Apache::lonnet::make_public_indefinitely($result);
                   11009:                 }
1.987     raeburn  11010:             }
1.661     raeburn  11011:         } else {
                   11012: # Save the file
                   11013:             my $target = $env{'form.embedded_item_'.$i};
                   11014:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11015:             my $dest = $fullpath.$fname;
                   11016:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11017:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11018:             my $count;
                   11019:             my $filepath = $dir_root;
1.1027    raeburn  11020:             foreach my $subdir (@parts) {
                   11021:                 $filepath .= "/$subdir";
                   11022:                 if (!-e $filepath) {
1.661     raeburn  11023:                     mkdir($filepath,0770);
                   11024:                 }
                   11025:             }
                   11026:             my $fh;
                   11027:             if (!open($fh,'>'.$dest)) {
                   11028:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11029:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11030:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11031:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11032:                            '</span><br />';
                   11033:             } else {
                   11034:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11035:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11036:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11037:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11038:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11039:                               '</span><br />';
                   11040:                 } else {
1.987     raeburn  11041:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11042:                                $url.'</span>').'<br />';
                   11043:                     unless ($context eq 'testbank') {
                   11044:                         $footer .= &mt('View embedded file: [_1]',
                   11045:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11046:                     }
                   11047:                 }
                   11048:                 close($fh);
                   11049:             }
                   11050:         }
                   11051:         if ($env{'form.embedded_ref_'.$i}) {
                   11052:             $pathchange{$i} = 1;
                   11053:         }
                   11054:     }
                   11055:     if ($output) {
                   11056:         $output = '<p>'.$output.'</p>';
                   11057:     }
                   11058:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11059:     $returnflag = 'ok';
1.1071    raeburn  11060:     my $numpathchgs = scalar(keys(%pathchange));
                   11061:     if ($numpathchgs > 0) {
1.987     raeburn  11062:         if ($context eq 'portfolio') {
                   11063:             $output .= '<p>'.&mt('or').'</p>';
                   11064:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11065:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11066:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11067:             $returnflag = 'modify_orightml';
                   11068:         }
                   11069:     }
1.1071    raeburn  11070:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11071: }
                   11072: 
                   11073: sub modify_html_form {
                   11074:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11075:     my $end = 0;
                   11076:     my $modifyform;
                   11077:     if ($context eq 'upload_embedded') {
                   11078:         return unless (ref($pathchange) eq 'HASH');
                   11079:         if ($env{'form.number_embedded_items'}) {
                   11080:             $end += $env{'form.number_embedded_items'};
                   11081:         }
                   11082:         if ($env{'form.number_pathchange_items'}) {
                   11083:             $end += $env{'form.number_pathchange_items'};
                   11084:         }
                   11085:         if ($end) {
                   11086:             for (my $i=0; $i<$end; $i++) {
                   11087:                 if ($i < $env{'form.number_embedded_items'}) {
                   11088:                     next unless($pathchange->{$i});
                   11089:                 }
                   11090:                 $modifyform .=
                   11091:                     &start_data_table_row().
                   11092:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11093:                     'checked="checked" /></td>'.
                   11094:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11095:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11096:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11097:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11098:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11099:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11100:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11101:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11102:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11103:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11104:                     &end_data_table_row();
1.1071    raeburn  11105:             }
1.987     raeburn  11106:         }
                   11107:     } else {
                   11108:         $modifyform = $pathchgtable;
                   11109:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11110:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11111:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11112:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11113:         }
                   11114:     }
                   11115:     if ($modifyform) {
1.1071    raeburn  11116:         if ($actionurl eq '/adm/dependencies') {
                   11117:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11118:         }
1.987     raeburn  11119:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11120:                '<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".
                   11121:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11122:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11123:                '</ol></p>'."\n".'<p>'.
                   11124:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11125:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11126:                &start_data_table()."\n".
                   11127:                &start_data_table_header_row().
                   11128:                '<th>'.&mt('Change?').'</th>'.
                   11129:                '<th>'.&mt('Current reference').'</th>'.
                   11130:                '<th>'.&mt('Required reference').'</th>'.
                   11131:                &end_data_table_header_row()."\n".
                   11132:                $modifyform.
                   11133:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11134:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11135:                '</form>'."\n";
                   11136:     }
                   11137:     return;
                   11138: }
                   11139: 
                   11140: sub modify_html_refs {
1.1123    raeburn  11141:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11142:     my $container;
                   11143:     if ($context eq 'portfolio') {
                   11144:         $container = $env{'form.container'};
                   11145:     } elsif ($context eq 'coursedoc') {
                   11146:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11147:     } elsif ($context eq 'manage_dependencies') {
                   11148:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11149:         $container = "/$container";
1.1123    raeburn  11150:     } elsif ($context eq 'syllabus') {
                   11151:         $container = $url;
1.987     raeburn  11152:     } else {
1.1027    raeburn  11153:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11154:     }
                   11155:     my (%allfiles,%codebase,$output,$content);
                   11156:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11157:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11158:         if (wantarray) {
                   11159:             return ('',0,0); 
                   11160:         } else {
                   11161:             return;
                   11162:         }
                   11163:     }
                   11164:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11165:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11166:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11167:             if (wantarray) {
                   11168:                 return ('',0,0);
                   11169:             } else {
                   11170:                 return;
                   11171:             }
                   11172:         } 
1.987     raeburn  11173:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11174:         if ($content eq '-1') {
                   11175:             if (wantarray) {
                   11176:                 return ('',0,0);
                   11177:             } else {
                   11178:                 return;
                   11179:             }
                   11180:         }
1.987     raeburn  11181:     } else {
1.1071    raeburn  11182:         unless ($container =~ /^\Q$dir_root\E/) {
                   11183:             if (wantarray) {
                   11184:                 return ('',0,0);
                   11185:             } else {
                   11186:                 return;
                   11187:             }
                   11188:         } 
1.987     raeburn  11189:         if (open(my $fh,"<$container")) {
                   11190:             $content = join('', <$fh>);
                   11191:             close($fh);
                   11192:         } else {
1.1071    raeburn  11193:             if (wantarray) {
                   11194:                 return ('',0,0);
                   11195:             } else {
                   11196:                 return;
                   11197:             }
1.987     raeburn  11198:         }
                   11199:     }
                   11200:     my ($count,$codebasecount) = (0,0);
                   11201:     my $mm = new File::MMagic;
                   11202:     my $mime_type = $mm->checktype_contents($content);
                   11203:     if ($mime_type eq 'text/html') {
                   11204:         my $parse_result = 
                   11205:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11206:                                                     \%codebase,\$content);
                   11207:         if ($parse_result eq 'ok') {
                   11208:             foreach my $i (@changes) {
                   11209:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11210:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11211:                 if ($allfiles{$ref}) {
                   11212:                     my $newname =  $orig;
                   11213:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11214:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11215:                     if ($attrib_regexp =~ /:/) {
                   11216:                         $attrib_regexp =~ s/\:/|/g;
                   11217:                     }
                   11218:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11219:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11220:                         $count += $numchg;
1.1123    raeburn  11221:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11222:                         delete($allfiles{$ref});
1.987     raeburn  11223:                     }
                   11224:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11225:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11226:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11227:                         $codebasecount ++;
                   11228:                     }
                   11229:                 }
                   11230:             }
1.1123    raeburn  11231:             my $skiprewrites;
1.987     raeburn  11232:             if ($count || $codebasecount) {
                   11233:                 my $saveresult;
1.1071    raeburn  11234:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11235:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11236:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11237:                     if ($url eq $container) {
                   11238:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11239:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11240:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11241:                                             $fname.'</span>').'</p>';
1.987     raeburn  11242:                     } else {
                   11243:                          $output = '<p class="LC_error">'.
                   11244:                                    &mt('Error: update failed for: [_1].',
                   11245:                                    '<span class="LC_filename">'.
                   11246:                                    $container.'</span>').'</p>';
                   11247:                     }
1.1123    raeburn  11248:                     if ($context eq 'syllabus') {
                   11249:                         unless ($saveresult eq 'ok') {
                   11250:                             $skiprewrites = 1;
                   11251:                         }
                   11252:                     }
1.987     raeburn  11253:                 } else {
                   11254:                     if (open(my $fh,">$container")) {
                   11255:                         print $fh $content;
                   11256:                         close($fh);
                   11257:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11258:                                   $count,'<span class="LC_filename">'.
                   11259:                                   $container.'</span>').'</p>';
1.661     raeburn  11260:                     } else {
1.987     raeburn  11261:                          $output = '<p class="LC_error">'.
                   11262:                                    &mt('Error: could not update [_1].',
                   11263:                                    '<span class="LC_filename">'.
                   11264:                                    $container.'</span>').'</p>';
1.661     raeburn  11265:                     }
                   11266:                 }
                   11267:             }
1.1123    raeburn  11268:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11269:                 my ($actionurl,$state);
                   11270:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11271:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11272:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11273:                                               \%codebase,
                   11274:                                               {'context' => 'rewrites',
                   11275:                                                'ignore_remote_references' => 1,});
                   11276:                 if (ref($mapping) eq 'HASH') {
                   11277:                     my $rewrites = 0;
                   11278:                     foreach my $key (keys(%{$mapping})) {
                   11279:                         next if ($key =~ m{^https?://});
                   11280:                         my $ref = $mapping->{$key};
                   11281:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11282:                         my $attrib;
                   11283:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11284:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11285:                         }
                   11286:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11287:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11288:                             $rewrites += $numchg;
                   11289:                         }
                   11290:                     }
                   11291:                     if ($rewrites) {
                   11292:                         my $saveresult; 
                   11293:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11294:                         if ($url eq $container) {
                   11295:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11296:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11297:                                             $count,'<span class="LC_filename">'.
                   11298:                                             $fname.'</span>').'</p>';
                   11299:                         } else {
                   11300:                             $output .= '<p class="LC_error">'.
                   11301:                                        &mt('Error: could not update links in [_1].',
                   11302:                                        '<span class="LC_filename">'.
                   11303:                                        $container.'</span>').'</p>';
                   11304: 
                   11305:                         }
                   11306:                     }
                   11307:                 }
                   11308:             }
1.987     raeburn  11309:         } else {
                   11310:             &logthis('Failed to parse '.$container.
                   11311:                      ' to modify references: '.$parse_result);
1.661     raeburn  11312:         }
                   11313:     }
1.1071    raeburn  11314:     if (wantarray) {
                   11315:         return ($output,$count,$codebasecount);
                   11316:     } else {
                   11317:         return $output;
                   11318:     }
1.661     raeburn  11319: }
                   11320: 
                   11321: sub check_for_existing {
                   11322:     my ($path,$fname,$element) = @_;
                   11323:     my ($state,$msg);
                   11324:     if (-d $path.'/'.$fname) {
                   11325:         $state = 'exists';
                   11326:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11327:     } elsif (-e $path.'/'.$fname) {
                   11328:         $state = 'exists';
                   11329:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11330:     }
                   11331:     if ($state eq 'exists') {
                   11332:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11333:     }
                   11334:     return ($state,$msg);
                   11335: }
                   11336: 
                   11337: sub check_for_upload {
                   11338:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11339:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11340:     my $filesize = length($env{'form.'.$element});
                   11341:     if (!$filesize) {
                   11342:         my $msg = '<span class="LC_error">'.
                   11343:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11344:                       '<span class="LC_filename">'.$fname.'</span>',
                   11345:                       $filesize).'<br />'.
1.1007    raeburn  11346:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11347:                   '</span>';
                   11348:         return ('zero_bytes',$msg);
                   11349:     }
                   11350:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11351:     my $getpropath = 1;
1.1021    raeburn  11352:     my ($dirlistref,$listerror) =
                   11353:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11354:     my $found_file = 0;
                   11355:     my $locked_file = 0;
1.991     raeburn  11356:     my @lockers;
                   11357:     my $navmap;
                   11358:     if ($env{'request.course.id'}) {
                   11359:         $navmap = Apache::lonnavmaps::navmap->new();
                   11360:     }
1.1021    raeburn  11361:     if (ref($dirlistref) eq 'ARRAY') {
                   11362:         foreach my $line (@{$dirlistref}) {
                   11363:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11364:             if ($file_name eq $fname){
                   11365:                 $file_name = $path.$file_name;
                   11366:                 if ($group ne '') {
                   11367:                     $file_name = $group.$file_name;
                   11368:                 }
                   11369:                 $found_file = 1;
                   11370:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11371:                     foreach my $lock (@lockers) {
                   11372:                         if (ref($lock) eq 'ARRAY') {
                   11373:                             my ($symb,$crsid) = @{$lock};
                   11374:                             if ($crsid eq $env{'request.course.id'}) {
                   11375:                                 if (ref($navmap)) {
                   11376:                                     my $res = $navmap->getBySymb($symb);
                   11377:                                     foreach my $part (@{$res->parts()}) { 
                   11378:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11379:                                         unless (($slot_status == $res->RESERVED) ||
                   11380:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11381:                                             $locked_file = 1;
                   11382:                                         }
1.991     raeburn  11383:                                     }
1.1021    raeburn  11384:                                 } else {
                   11385:                                     $locked_file = 1;
1.991     raeburn  11386:                                 }
                   11387:                             } else {
                   11388:                                 $locked_file = 1;
                   11389:                             }
                   11390:                         }
1.1021    raeburn  11391:                    }
                   11392:                 } else {
                   11393:                     my @info = split(/\&/,$rest);
                   11394:                     my $currsize = $info[6]/1000;
                   11395:                     if ($currsize < $filesize) {
                   11396:                         my $extra = $filesize - $currsize;
                   11397:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11398:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11399:                                       &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded if existing (smaller) file with same name (size = [_3] kilobytes) is replaced.',
1.1179    bisitz   11400:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11401:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11402:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11403:                             return ('will_exceed_quota',$msg);
                   11404:                         }
1.984     raeburn  11405:                     }
                   11406:                 }
1.661     raeburn  11407:             }
                   11408:         }
                   11409:     }
                   11410:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11411:         my $msg = '<p class="LC_warning">'.
                   11412:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11413:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11414:         return ('will_exceed_quota',$msg);
                   11415:     } elsif ($found_file) {
                   11416:         if ($locked_file) {
1.1179    bisitz   11417:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11418:             $msg .= &mt('Unable to upload [_1]. A locked file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>','<span class="LC_filename">'.$port_path.$env{'form.currentpath'}.'</span>');
1.1179    bisitz   11419:             $msg .= '</p>';
1.661     raeburn  11420:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11421:             return ('file_locked',$msg);
                   11422:         } else {
1.1179    bisitz   11423:             my $msg = '<p class="LC_error">';
1.984     raeburn  11424:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1179    bisitz   11425:             $msg .= '</p>';
1.984     raeburn  11426:             return ('existingfile',$msg);
1.661     raeburn  11427:         }
                   11428:     }
                   11429: }
                   11430: 
1.987     raeburn  11431: sub check_for_traversal {
                   11432:     my ($path,$url,$toplevel) = @_;
                   11433:     my @parts=split(/\//,$path);
                   11434:     my $cleanpath;
                   11435:     my $fullpath = $url;
                   11436:     for (my $i=0;$i<@parts;$i++) {
                   11437:         next if ($parts[$i] eq '.');
                   11438:         if ($parts[$i] eq '..') {
                   11439:             $fullpath =~ s{([^/]+/)$}{};
                   11440:         } else {
                   11441:             $fullpath .= $parts[$i].'/';
                   11442:         }
                   11443:     }
                   11444:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11445:         $cleanpath = $1;
                   11446:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11447:         my $curr_toprel = $1;
                   11448:         my @parts = split(/\//,$curr_toprel);
                   11449:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11450:         my @urlparts = split(/\//,$url_toprel);
                   11451:         my $doubledots;
                   11452:         my $startdiff = -1;
                   11453:         for (my $i=0; $i<@urlparts; $i++) {
                   11454:             if ($startdiff == -1) {
                   11455:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11456:                     $startdiff = $i;
                   11457:                     $doubledots .= '../';
                   11458:                 }
                   11459:             } else {
                   11460:                 $doubledots .= '../';
                   11461:             }
                   11462:         }
                   11463:         if ($startdiff > -1) {
                   11464:             $cleanpath = $doubledots;
                   11465:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11466:                 $cleanpath .= $parts[$i].'/';
                   11467:             }
                   11468:         }
                   11469:     }
                   11470:     $cleanpath =~ s{(/)$}{};
                   11471:     return $cleanpath;
                   11472: }
1.31      albertel 11473: 
1.1053    raeburn  11474: sub is_archive_file {
                   11475:     my ($mimetype) = @_;
                   11476:     if (($mimetype eq 'application/octet-stream') ||
                   11477:         ($mimetype eq 'application/x-stuffit') ||
                   11478:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11479:         return 1;
                   11480:     }
                   11481:     return;
                   11482: }
                   11483: 
                   11484: sub decompress_form {
1.1065    raeburn  11485:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11486:     my %lt = &Apache::lonlocal::texthash (
                   11487:         this => 'This file is an archive file.',
1.1067    raeburn  11488:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11489:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11490:         youm => 'You may wish to extract its contents.',
                   11491:         extr => 'Extract contents',
1.1067    raeburn  11492:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11493:         proa => 'Process automatically?',
1.1053    raeburn  11494:         yes  => 'Yes',
                   11495:         no   => 'No',
1.1067    raeburn  11496:         fold => 'Title for folder containing movie',
                   11497:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11498:     );
1.1065    raeburn  11499:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11500:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11501:     my $info = &list_archive_contents($fileloc,\@paths);
                   11502:     if (@paths) {
                   11503:         foreach my $path (@paths) {
                   11504:             $path =~ s{^/}{};
1.1067    raeburn  11505:             if ($path =~ m{^([^/]+)/$}) {
                   11506:                 $topdir = $1;
                   11507:             }
1.1065    raeburn  11508:             if ($path =~ m{^([^/]+)/}) {
                   11509:                 $toplevel{$1} = $path;
                   11510:             } else {
                   11511:                 $toplevel{$path} = $path;
                   11512:             }
                   11513:         }
                   11514:     }
1.1067    raeburn  11515:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11516:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11517:                         "$topdir/media/",
                   11518:                         "$topdir/media/$topdir.mp4",
                   11519:                         "$topdir/media/FirstFrame.png",
                   11520:                         "$topdir/media/player.swf",
                   11521:                         "$topdir/media/swfobject.js",
                   11522:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11523:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11524:                          "$topdir/$topdir.mp4",
                   11525:                          "$topdir/$topdir\_config.xml",
                   11526:                          "$topdir/$topdir\_controller.swf",
                   11527:                          "$topdir/$topdir\_embed.css",
                   11528:                          "$topdir/$topdir\_First_Frame.png",
                   11529:                          "$topdir/$topdir\_player.html",
                   11530:                          "$topdir/$topdir\_Thumbnails.png",
                   11531:                          "$topdir/playerProductInstall.swf",
                   11532:                          "$topdir/scripts/",
                   11533:                          "$topdir/scripts/config_xml.js",
                   11534:                          "$topdir/scripts/handlebars.js",
                   11535:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11536:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11537:                          "$topdir/scripts/modernizr.js",
                   11538:                          "$topdir/scripts/player-min.js",
                   11539:                          "$topdir/scripts/swfobject.js",
                   11540:                          "$topdir/skins/",
                   11541:                          "$topdir/skins/configuration_express.xml",
                   11542:                          "$topdir/skins/express_show/",
                   11543:                          "$topdir/skins/express_show/player-min.css",
                   11544:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11545:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11546:                          "$topdir/$topdir.mp4",
                   11547:                          "$topdir/$topdir\_config.xml",
                   11548:                          "$topdir/$topdir\_controller.swf",
                   11549:                          "$topdir/$topdir\_embed.css",
                   11550:                          "$topdir/$topdir\_First_Frame.png",
                   11551:                          "$topdir/$topdir\_player.html",
                   11552:                          "$topdir/$topdir\_Thumbnails.png",
                   11553:                          "$topdir/playerProductInstall.swf",
                   11554:                          "$topdir/scripts/",
                   11555:                          "$topdir/scripts/config_xml.js",
                   11556:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11557:                          "$topdir/skins/",
                   11558:                          "$topdir/skins/configuration_express.xml",
                   11559:                          "$topdir/skins/express_show/",
                   11560:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11561:                          "$topdir/skins/express_show/spritesheet.png",
                   11562:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11563:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11564:         if (@diffs == 0) {
1.1164    raeburn  11565:             $is_camtasia = 6;
                   11566:         } else {
1.1197    raeburn  11567:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11568:             if (@diffs == 0) {
                   11569:                 $is_camtasia = 8;
1.1197    raeburn  11570:             } else {
                   11571:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11572:                 if (@diffs == 0) {
                   11573:                     $is_camtasia = 8;
                   11574:                 }
1.1164    raeburn  11575:             }
1.1067    raeburn  11576:         }
                   11577:     }
                   11578:     my $output;
                   11579:     if ($is_camtasia) {
                   11580:         $output = <<"ENDCAM";
                   11581: <script type="text/javascript" language="Javascript">
                   11582: // <![CDATA[
                   11583: 
                   11584: function camtasiaToggle() {
                   11585:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11586:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11587:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11588:                 document.getElementById('camtasia_titles').style.display='block';
                   11589:             } else {
                   11590:                 document.getElementById('camtasia_titles').style.display='none';
                   11591:             }
                   11592:         }
                   11593:     }
                   11594:     return;
                   11595: }
                   11596: 
                   11597: // ]]>
                   11598: </script>
                   11599: <p>$lt{'camt'}</p>
                   11600: ENDCAM
1.1065    raeburn  11601:     } else {
1.1067    raeburn  11602:         $output = '<p>'.$lt{'this'};
                   11603:         if ($info eq '') {
                   11604:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11605:         } else {
                   11606:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11607:                        '<div><pre>'.$info.'</pre></div>';
                   11608:         }
1.1065    raeburn  11609:     }
1.1067    raeburn  11610:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11611:     my $duplicates;
                   11612:     my $num = 0;
                   11613:     if (ref($dirlist) eq 'ARRAY') {
                   11614:         foreach my $item (@{$dirlist}) {
                   11615:             if (ref($item) eq 'ARRAY') {
                   11616:                 if (exists($toplevel{$item->[0]})) {
                   11617:                     $duplicates .= 
                   11618:                         &start_data_table_row().
                   11619:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11620:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11621:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11622:                         'value="1" />'.&mt('Yes').'</label>'.
                   11623:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11624:                         '<td>'.$item->[0].'</td>';
                   11625:                     if ($item->[2]) {
                   11626:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11627:                     } else {
                   11628:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11629:                     }
                   11630:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11631:                                    '<td>'.
                   11632:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11633:                                    '</td>'.
                   11634:                                    &end_data_table_row();
                   11635:                     $num ++;
                   11636:                 }
                   11637:             }
                   11638:         }
                   11639:     }
                   11640:     my $itemcount;
                   11641:     if (@paths > 0) {
                   11642:         $itemcount = scalar(@paths);
                   11643:     } else {
                   11644:         $itemcount = 1;
                   11645:     }
1.1067    raeburn  11646:     if ($is_camtasia) {
                   11647:         $output .= $lt{'auto'}.'<br />'.
                   11648:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11649:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11650:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11651:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11652:                    $lt{'no'}.'</label></span><br />'.
                   11653:                    '<div id="camtasia_titles" style="display:block">'.
                   11654:                    &Apache::lonhtmlcommon::start_pick_box().
                   11655:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11656:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11657:                    &Apache::lonhtmlcommon::row_closure().
                   11658:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11659:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11660:                    &Apache::lonhtmlcommon::row_closure(1).
                   11661:                    &Apache::lonhtmlcommon::end_pick_box().
                   11662:                    '</div>';
                   11663:     }
1.1065    raeburn  11664:     $output .= 
                   11665:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11666:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11667:         "\n";
1.1065    raeburn  11668:     if ($duplicates ne '') {
                   11669:         $output .= '<p><span class="LC_warning">'.
                   11670:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11671:                    &start_data_table().
                   11672:                    &start_data_table_header_row().
                   11673:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11674:                    '<th>'.&mt('Name').'</th>'.
                   11675:                    '<th>'.&mt('Type').'</th>'.
                   11676:                    '<th>'.&mt('Size').'</th>'.
                   11677:                    '<th>'.&mt('Last modified').'</th>'.
                   11678:                    &end_data_table_header_row().
                   11679:                    $duplicates.
                   11680:                    &end_data_table().
                   11681:                    '</p>';
                   11682:     }
1.1067    raeburn  11683:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11684:     if (ref($hiddenelements) eq 'HASH') {
                   11685:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11686:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11687:         }
                   11688:     }
                   11689:     $output .= <<"END";
1.1067    raeburn  11690: <br />
1.1053    raeburn  11691: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11692: </form>
                   11693: $noextract
                   11694: END
                   11695:     return $output;
                   11696: }
                   11697: 
1.1065    raeburn  11698: sub decompression_utility {
                   11699:     my ($program) = @_;
                   11700:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11701:     my $location;
                   11702:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11703:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11704:                          '/usr/sbin/') {
                   11705:             if (-x $dir.$program) {
                   11706:                 $location = $dir.$program;
                   11707:                 last;
                   11708:             }
                   11709:         }
                   11710:     }
                   11711:     return $location;
                   11712: }
                   11713: 
                   11714: sub list_archive_contents {
                   11715:     my ($file,$pathsref) = @_;
                   11716:     my (@cmd,$output);
                   11717:     my $needsregexp;
                   11718:     if ($file =~ /\.zip$/) {
                   11719:         @cmd = (&decompression_utility('unzip'),"-l");
                   11720:         $needsregexp = 1;
                   11721:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11722:              ($file =~ /\.tgz$/)) {
                   11723:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11724:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11725:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11726:     } elsif ($file =~ m|\.tar$|) {
                   11727:         @cmd = (&decompression_utility('tar'),"-tf");
                   11728:     }
                   11729:     if (@cmd) {
                   11730:         undef($!);
                   11731:         undef($@);
                   11732:         if (open(my $fh,"-|", @cmd, $file)) {
                   11733:             while (my $line = <$fh>) {
                   11734:                 $output .= $line;
                   11735:                 chomp($line);
                   11736:                 my $item;
                   11737:                 if ($needsregexp) {
                   11738:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11739:                 } else {
                   11740:                     $item = $line;
                   11741:                 }
                   11742:                 if ($item ne '') {
                   11743:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11744:                         push(@{$pathsref},$item);
                   11745:                     } 
                   11746:                 }
                   11747:             }
                   11748:             close($fh);
                   11749:         }
                   11750:     }
                   11751:     return $output;
                   11752: }
                   11753: 
1.1053    raeburn  11754: sub decompress_uploaded_file {
                   11755:     my ($file,$dir) = @_;
                   11756:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11757:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11758:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11759:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11760:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11761:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11762:     my $decompressed = $env{'cgi.decompressed'};
                   11763:     &Apache::lonnet::delenv('cgi.file');
                   11764:     &Apache::lonnet::delenv('cgi.dir');
                   11765:     &Apache::lonnet::delenv('cgi.decompressed');
                   11766:     return ($decompressed,$result);
                   11767: }
                   11768: 
1.1055    raeburn  11769: sub process_decompression {
                   11770:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11771:     my ($dir,$error,$warning,$output);
1.1180    raeburn  11772:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   11773:         $error = &mt('Filename not a supported archive file type.').
                   11774:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11775:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11776:     } else {
                   11777:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11778:         if ($docuhome eq 'no_host') {
                   11779:             $error = &mt('Could not determine home server for course.');
                   11780:         } else {
                   11781:             my @ids=&Apache::lonnet::current_machine_ids();
                   11782:             my $currdir = "$dir_root/$destination";
                   11783:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11784:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11785:                        "$dir_root/$destination";
                   11786:             } else {
                   11787:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11788:                        "$dir_root/$docudom/$docuname/$destination";
                   11789:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11790:                     $error = &mt('Archive file not found.');
                   11791:                 }
                   11792:             }
1.1065    raeburn  11793:             my (@to_overwrite,@to_skip);
                   11794:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11795:                 my $total = $env{'form.archive_overwrite_total'};
                   11796:                 for (my $i=0; $i<$total; $i++) {
                   11797:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11798:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11799:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11800:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11801:                     }
                   11802:                 }
                   11803:             }
                   11804:             my $numskip = scalar(@to_skip);
                   11805:             if (($numskip > 0) && 
                   11806:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11807:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11808:             } elsif ($dir eq '') {
1.1055    raeburn  11809:                 $error = &mt('Directory containing archive file unavailable.');
                   11810:             } elsif (!$error) {
1.1065    raeburn  11811:                 my ($decompressed,$display);
                   11812:                 if ($numskip > 0) {
                   11813:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11814:                     mkdir("$dir/$tempdir",0755);
                   11815:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11816:                     ($decompressed,$display) = 
                   11817:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11818:                     foreach my $item (@to_skip) {
                   11819:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11820:                             if (-f "$dir/$tempdir/$item") { 
                   11821:                                 unlink("$dir/$tempdir/$item");
                   11822:                             } elsif (-d "$dir/$tempdir/$item") {
                   11823:                                 system("rm -rf $dir/$tempdir/$item");
                   11824:                             }
                   11825:                         }
                   11826:                     }
                   11827:                     system("mv $dir/$tempdir/* $dir");
                   11828:                     rmdir("$dir/$tempdir");   
                   11829:                 } else {
                   11830:                     ($decompressed,$display) = 
                   11831:                         &decompress_uploaded_file($file,$dir);
                   11832:                 }
1.1055    raeburn  11833:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11834:                     $output = '<p class="LC_info">'.
                   11835:                               &mt('Files extracted successfully from archive.').
                   11836:                               '</p>'."\n";
1.1055    raeburn  11837:                     my ($warning,$result,@contents);
                   11838:                     my ($newdirlistref,$newlisterror) =
                   11839:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11840:                                                  $docuname,1);
                   11841:                     my (%is_dir,%changes,@newitems);
                   11842:                     my $dirptr = 16384;
1.1065    raeburn  11843:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11844:                         foreach my $dir_line (@{$newdirlistref}) {
                   11845:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11846:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11847:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11848:                                 push(@newitems,$item);
                   11849:                                 if ($dirptr&$testdir) {
                   11850:                                     $is_dir{$item} = 1;
                   11851:                                 }
                   11852:                                 $changes{$item} = 1;
                   11853:                             }
                   11854:                         }
                   11855:                     }
                   11856:                     if (keys(%changes) > 0) {
                   11857:                         foreach my $item (sort(@newitems)) {
                   11858:                             if ($changes{$item}) {
                   11859:                                 push(@contents,$item);
                   11860:                             }
                   11861:                         }
                   11862:                     }
                   11863:                     if (@contents > 0) {
1.1067    raeburn  11864:                         my $wantform;
                   11865:                         unless ($env{'form.autoextract_camtasia'}) {
                   11866:                             $wantform = 1;
                   11867:                         }
1.1056    raeburn  11868:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11869:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11870:                                                                 $currdir,\%is_dir,
                   11871:                                                                 \%children,\%parent,
1.1056    raeburn  11872:                                                                 \@contents,\%dirorder,
                   11873:                                                                 \%titles,$wantform);
1.1055    raeburn  11874:                         if ($datatable ne '') {
                   11875:                             $output .= &archive_options_form('decompressed',$datatable,
                   11876:                                                              $count,$hiddenelem);
1.1065    raeburn  11877:                             my $startcount = 6;
1.1055    raeburn  11878:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11879:                                                            \%titles,\%children);
1.1055    raeburn  11880:                         }
1.1067    raeburn  11881:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  11882:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11883:                             my %displayed;
                   11884:                             my $total = 1;
                   11885:                             $env{'form.archive_directory'} = [];
                   11886:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11887:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11888:                                 $path =~ s{/$}{};
                   11889:                                 my $item;
                   11890:                                 if ($path ne '') {
                   11891:                                     $item = "$path/$titles{$i}";
                   11892:                                 } else {
                   11893:                                     $item = $titles{$i};
                   11894:                                 }
                   11895:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11896:                                 if ($item eq $contents[0]) {
                   11897:                                     push(@{$env{'form.archive_directory'}},$i);
                   11898:                                     $env{'form.archive_'.$i} = 'display';
                   11899:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11900:                                     $displayed{'folder'} = $i;
1.1164    raeburn  11901:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11902:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  11903:                                     $env{'form.archive_'.$i} = 'display';
                   11904:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11905:                                     $displayed{'web'} = $i;
                   11906:                                 } else {
1.1164    raeburn  11907:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11908:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11909:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11910:                                         push(@{$env{'form.archive_directory'}},$i);
                   11911:                                     }
                   11912:                                     $env{'form.archive_'.$i} = 'dependency';
                   11913:                                 }
                   11914:                                 $total ++;
                   11915:                             }
                   11916:                             for (my $i=1; $i<$total; $i++) {
                   11917:                                 next if ($i == $displayed{'web'});
                   11918:                                 next if ($i == $displayed{'folder'});
                   11919:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11920:                             }
                   11921:                             $env{'form.phase'} = 'decompress_cleanup';
                   11922:                             $env{'form.archivedelete'} = 1;
                   11923:                             $env{'form.archive_count'} = $total-1;
                   11924:                             $output .=
                   11925:                                 &process_extracted_files('coursedocs',$docudom,
                   11926:                                                          $docuname,$destination,
                   11927:                                                          $dir_root,$hiddenelem);
                   11928:                         }
1.1055    raeburn  11929:                     } else {
                   11930:                         $warning = &mt('No new items extracted from archive file.');
                   11931:                     }
                   11932:                 } else {
                   11933:                     $output = $display;
                   11934:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11935:                 }
                   11936:             }
                   11937:         }
                   11938:     }
                   11939:     if ($error) {
                   11940:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11941:                    $error.'</p>'."\n";
                   11942:     }
                   11943:     if ($warning) {
                   11944:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11945:     }
                   11946:     return $output;
                   11947: }
                   11948: 
                   11949: sub get_extracted {
1.1056    raeburn  11950:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11951:         $titles,$wantform) = @_;
1.1055    raeburn  11952:     my $count = 0;
                   11953:     my $depth = 0;
                   11954:     my $datatable;
1.1056    raeburn  11955:     my @hierarchy;
1.1055    raeburn  11956:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11957:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11958:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11959:     foreach my $item (@{$contents}) {
                   11960:         $count ++;
1.1056    raeburn  11961:         @{$dirorder->{$count}} = @hierarchy;
                   11962:         $titles->{$count} = $item;
1.1055    raeburn  11963:         &archive_hierarchy($depth,$count,$parent,$children);
                   11964:         if ($wantform) {
                   11965:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11966:                                        $currdir,$depth,$count);
                   11967:         }
                   11968:         if ($is_dir->{$item}) {
                   11969:             $depth ++;
1.1056    raeburn  11970:             push(@hierarchy,$count);
                   11971:             $parent->{$depth} = $count;
1.1055    raeburn  11972:             $datatable .=
                   11973:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11974:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11975:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11976:             $depth --;
1.1056    raeburn  11977:             pop(@hierarchy);
1.1055    raeburn  11978:         }
                   11979:     }
                   11980:     return ($count,$datatable);
                   11981: }
                   11982: 
                   11983: sub recurse_extracted_archive {
1.1056    raeburn  11984:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11985:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11986:     my $result='';
1.1056    raeburn  11987:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11988:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11989:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11990:         return $result;
                   11991:     }
                   11992:     my $dirptr = 16384;
                   11993:     my ($newdirlistref,$newlisterror) =
                   11994:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11995:     if (ref($newdirlistref) eq 'ARRAY') {
                   11996:         foreach my $dir_line (@{$newdirlistref}) {
                   11997:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11998:             unless ($item =~ /^\.+$/) {
                   11999:                 $$count ++;
1.1056    raeburn  12000:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12001:                 $titles->{$$count} = $item;
1.1055    raeburn  12002:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12003: 
1.1055    raeburn  12004:                 my $is_dir;
                   12005:                 if ($dirptr&$testdir) {
                   12006:                     $is_dir = 1;
                   12007:                 }
                   12008:                 if ($wantform) {
                   12009:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12010:                 }
                   12011:                 if ($is_dir) {
                   12012:                     $$depth ++;
1.1056    raeburn  12013:                     push(@{$hierarchy},$$count);
                   12014:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12015:                     $result .=
                   12016:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12017:                                                    $docuname,$depth,$count,
1.1056    raeburn  12018:                                                    $hierarchy,$dirorder,$children,
                   12019:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12020:                     $$depth --;
1.1056    raeburn  12021:                     pop(@{$hierarchy});
1.1055    raeburn  12022:                 }
                   12023:             }
                   12024:         }
                   12025:     }
                   12026:     return $result;
                   12027: }
                   12028: 
                   12029: sub archive_hierarchy {
                   12030:     my ($depth,$count,$parent,$children) =@_;
                   12031:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12032:         if (exists($parent->{$depth})) {
                   12033:              $children->{$parent->{$depth}} .= $count.':';
                   12034:         }
                   12035:     }
                   12036:     return;
                   12037: }
                   12038: 
                   12039: sub archive_row {
                   12040:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12041:     my ($name) = ($item =~ m{([^/]+)$});
                   12042:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12043:                                        'display'    => 'Add as file',
1.1055    raeburn  12044:                                        'dependency' => 'Include as dependency',
                   12045:                                        'discard'    => 'Discard',
                   12046:                                       );
                   12047:     if ($is_dir) {
1.1059    raeburn  12048:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12049:     }
1.1056    raeburn  12050:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12051:     my $offset = 0;
1.1055    raeburn  12052:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12053:         $offset ++;
1.1065    raeburn  12054:         if ($action ne 'display') {
                   12055:             $offset ++;
                   12056:         }  
1.1055    raeburn  12057:         $output .= '<td><span class="LC_nobreak">'.
                   12058:                    '<label><input type="radio" name="archive_'.$count.
                   12059:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12060:         my $text = $choices{$action};
                   12061:         if ($is_dir) {
                   12062:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12063:             if ($action eq 'display') {
1.1059    raeburn  12064:                 $text = &mt('Add as folder');
1.1055    raeburn  12065:             }
1.1056    raeburn  12066:         } else {
                   12067:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12068: 
                   12069:         }
                   12070:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12071:         if ($action eq 'dependency') {
                   12072:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12073:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12074:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12075:                        '<option value=""></option>'."\n".
                   12076:                        '</select>'."\n".
                   12077:                        '</div>';
1.1059    raeburn  12078:         } elsif ($action eq 'display') {
                   12079:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12080:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12081:                        '</div>';
1.1055    raeburn  12082:         }
1.1056    raeburn  12083:         $output .= '</td>';
1.1055    raeburn  12084:     }
                   12085:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12086:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12087:     for (my $i=0; $i<$depth; $i++) {
                   12088:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12089:     }
                   12090:     if ($is_dir) {
                   12091:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12092:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12093:     } else {
                   12094:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12095:     }
                   12096:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12097:                &end_data_table_row();
                   12098:     return $output;
                   12099: }
                   12100: 
                   12101: sub archive_options_form {
1.1065    raeburn  12102:     my ($form,$display,$count,$hiddenelem) = @_;
                   12103:     my %lt = &Apache::lonlocal::texthash(
                   12104:                perm => 'Permanently remove archive file?',
                   12105:                hows => 'How should each extracted item be incorporated in the course?',
                   12106:                cont => 'Content actions for all',
                   12107:                addf => 'Add as folder/file',
                   12108:                incd => 'Include as dependency for a displayed file',
                   12109:                disc => 'Discard',
                   12110:                no   => 'No',
                   12111:                yes  => 'Yes',
                   12112:                save => 'Save',
                   12113:     );
                   12114:     my $output = <<"END";
                   12115: <form name="$form" method="post" action="">
                   12116: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12117: <label>
                   12118:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12119: </label>
                   12120: &nbsp;
                   12121: <label>
                   12122:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12123: </span>
                   12124: </p>
                   12125: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12126: <br />$lt{'hows'}
                   12127: <div class="LC_columnSection">
                   12128:   <fieldset>
                   12129:     <legend>$lt{'cont'}</legend>
                   12130:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12131:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12132:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12133:   </fieldset>
                   12134: </div>
                   12135: END
                   12136:     return $output.
1.1055    raeburn  12137:            &start_data_table()."\n".
1.1065    raeburn  12138:            $display."\n".
1.1055    raeburn  12139:            &end_data_table()."\n".
                   12140:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12141:            $hiddenelem.
1.1065    raeburn  12142:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12143:            '</form>';
                   12144: }
                   12145: 
                   12146: sub archive_javascript {
1.1056    raeburn  12147:     my ($startcount,$numitems,$titles,$children) = @_;
                   12148:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12149:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12150:     my $scripttag = <<START;
                   12151: <script type="text/javascript">
                   12152: // <![CDATA[
                   12153: 
                   12154: function checkAll(form,prefix) {
                   12155:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12156:     for (var i=0; i < form.elements.length; i++) {
                   12157:         var id = form.elements[i].id;
                   12158:         if ((id != '') && (id != undefined)) {
                   12159:             if (idstr.test(id)) {
                   12160:                 if (form.elements[i].type == 'radio') {
                   12161:                     form.elements[i].checked = true;
1.1056    raeburn  12162:                     var nostart = i-$startcount;
1.1059    raeburn  12163:                     var offset = nostart%7;
                   12164:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12165:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12166:                 }
                   12167:             }
                   12168:         }
                   12169:     }
                   12170: }
                   12171: 
                   12172: function propagateCheck(form,count) {
                   12173:     if (count > 0) {
1.1059    raeburn  12174:         var startelement = $startcount + ((count-1) * 7);
                   12175:         for (var j=1; j<6; j++) {
                   12176:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12177:                 var item = startelement + j; 
                   12178:                 if (form.elements[item].type == 'radio') {
                   12179:                     if (form.elements[item].checked) {
                   12180:                         containerCheck(form,count,j);
                   12181:                         break;
                   12182:                     }
1.1055    raeburn  12183:                 }
                   12184:             }
                   12185:         }
                   12186:     }
                   12187: }
                   12188: 
                   12189: numitems = $numitems
1.1056    raeburn  12190: var titles = new Array(numitems);
                   12191: var parents = new Array(numitems);
1.1055    raeburn  12192: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12193:     parents[i] = new Array;
1.1055    raeburn  12194: }
1.1059    raeburn  12195: var maintitle = '$maintitle';
1.1055    raeburn  12196: 
                   12197: START
                   12198: 
1.1056    raeburn  12199:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12200:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12201:         for (my $i=0; $i<@contents; $i ++) {
                   12202:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12203:         }
                   12204:     }
                   12205: 
1.1056    raeburn  12206:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12207:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12208:     }
                   12209: 
1.1055    raeburn  12210:     $scripttag .= <<END;
                   12211: 
                   12212: function containerCheck(form,count,offset) {
                   12213:     if (count > 0) {
1.1056    raeburn  12214:         dependencyCheck(form,count,offset);
1.1059    raeburn  12215:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12216:         form.elements[item].checked = true;
                   12217:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12218:             if (parents[count].length > 0) {
                   12219:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12220:                     containerCheck(form,parents[count][j],offset);
                   12221:                 }
                   12222:             }
                   12223:         }
                   12224:     }
                   12225: }
                   12226: 
                   12227: function dependencyCheck(form,count,offset) {
                   12228:     if (count > 0) {
1.1059    raeburn  12229:         var chosen = (offset+$startcount)+7*(count-1);
                   12230:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12231:         var currtype = form.elements[depitem].type;
                   12232:         if (form.elements[chosen].value == 'dependency') {
                   12233:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12234:             form.elements[depitem].options.length = 0;
                   12235:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12236:             for (var i=1; i<=numitems; i++) {
                   12237:                 if (i == count) {
                   12238:                     continue;
                   12239:                 }
1.1059    raeburn  12240:                 var startelement = $startcount + (i-1) * 7;
                   12241:                 for (var j=1; j<6; j++) {
                   12242:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12243:                         var item = startelement + j;
                   12244:                         if (form.elements[item].type == 'radio') {
                   12245:                             if (form.elements[item].checked) {
                   12246:                                 if (form.elements[item].value == 'display') {
                   12247:                                     var n = form.elements[depitem].options.length;
                   12248:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12249:                                 }
                   12250:                             }
                   12251:                         }
                   12252:                     }
                   12253:                 }
                   12254:             }
                   12255:         } else {
                   12256:             document.getElementById('arc_depon_'+count).style.display='none';
                   12257:             form.elements[depitem].options.length = 0;
                   12258:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12259:         }
1.1059    raeburn  12260:         titleCheck(form,count,offset);
1.1056    raeburn  12261:     }
                   12262: }
                   12263: 
                   12264: function propagateSelect(form,count,offset) {
                   12265:     if (count > 0) {
1.1065    raeburn  12266:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12267:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12268:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12269:             if (parents[count].length > 0) {
                   12270:                 for (var j=0; j<parents[count].length; j++) {
                   12271:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12272:                 }
                   12273:             }
                   12274:         }
                   12275:     }
                   12276: }
1.1056    raeburn  12277: 
                   12278: function containerSelect(form,count,offset,picked) {
                   12279:     if (count > 0) {
1.1065    raeburn  12280:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12281:         if (form.elements[item].type == 'radio') {
                   12282:             if (form.elements[item].value == 'dependency') {
                   12283:                 if (form.elements[item+1].type == 'select-one') {
                   12284:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12285:                         if (form.elements[item+1].options[i].value == picked) {
                   12286:                             form.elements[item+1].selectedIndex = i;
                   12287:                             break;
                   12288:                         }
                   12289:                     }
                   12290:                 }
                   12291:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12292:                     if (parents[count].length > 0) {
                   12293:                         for (var j=0; j<parents[count].length; j++) {
                   12294:                             containerSelect(form,parents[count][j],offset,picked);
                   12295:                         }
                   12296:                     }
                   12297:                 }
                   12298:             }
                   12299:         }
                   12300:     }
                   12301: }
                   12302: 
1.1059    raeburn  12303: function titleCheck(form,count,offset) {
                   12304:     if (count > 0) {
                   12305:         var chosen = (offset+$startcount)+7*(count-1);
                   12306:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12307:         var currtype = form.elements[depitem].type;
                   12308:         if (form.elements[chosen].value == 'display') {
                   12309:             document.getElementById('arc_title_'+count).style.display='block';
                   12310:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12311:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12312:             }
                   12313:         } else {
                   12314:             document.getElementById('arc_title_'+count).style.display='none';
                   12315:             if (currtype == 'text') { 
                   12316:                 document.getElementById('archive_title_'+count).value='';
                   12317:             }
                   12318:         }
                   12319:     }
                   12320:     return;
                   12321: }
                   12322: 
1.1055    raeburn  12323: // ]]>
                   12324: </script>
                   12325: END
                   12326:     return $scripttag;
                   12327: }
                   12328: 
                   12329: sub process_extracted_files {
1.1067    raeburn  12330:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12331:     my $numitems = $env{'form.archive_count'};
                   12332:     return unless ($numitems);
                   12333:     my @ids=&Apache::lonnet::current_machine_ids();
                   12334:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12335:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12336:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12337:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12338:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12339:         $pathtocheck = "$dir_root/$destination";
                   12340:         $dir = $dir_root;
                   12341:         $ishome = 1;
                   12342:     } else {
                   12343:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12344:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12345:         $dir = "$dir_root/$docudom/$docuname";    
                   12346:     }
                   12347:     my $currdir = "$dir_root/$destination";
                   12348:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12349:     if ($env{'form.folderpath'}) {
                   12350:         my @items = split('&',$env{'form.folderpath'});
                   12351:         $folders{'0'} = $items[-2];
1.1099    raeburn  12352:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12353:             $containers{'0'}='page';
                   12354:         } else {  
                   12355:             $containers{'0'}='sequence';
                   12356:         }
1.1055    raeburn  12357:     }
                   12358:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12359:     if ($numitems) {
                   12360:         for (my $i=1; $i<=$numitems; $i++) {
                   12361:             my $path = $env{'form.archive_content_'.$i};
                   12362:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12363:                 my $item = $1;
                   12364:                 $toplevelitems{$item} = $i;
                   12365:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12366:                     $is_dir{$item} = 1;
                   12367:                 }
                   12368:             }
                   12369:         }
                   12370:     }
1.1067    raeburn  12371:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12372:     if (keys(%toplevelitems) > 0) {
                   12373:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12374:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12375:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12376:     }
1.1066    raeburn  12377:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12378:     if ($numitems) {
                   12379:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12380:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12381:             my $path = $env{'form.archive_content_'.$i};
                   12382:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12383:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12384:                     if ($prefix ne '' && $path ne '') {
                   12385:                         if (-e $prefix.$path) {
1.1066    raeburn  12386:                             if ((@archdirs > 0) && 
                   12387:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12388:                                 $todeletedir{$prefix.$path} = 1;
                   12389:                             } else {
                   12390:                                 $todelete{$prefix.$path} = 1;
                   12391:                             }
1.1055    raeburn  12392:                         }
                   12393:                     }
                   12394:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12395:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12396:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12397:                     $docstitle = $env{'form.archive_title_'.$i};
                   12398:                     if ($docstitle eq '') {
                   12399:                         $docstitle = $title;
                   12400:                     }
1.1055    raeburn  12401:                     $outer = 0;
1.1056    raeburn  12402:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12403:                         if (@{$dirorder{$i}} > 0) {
                   12404:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12405:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12406:                                     $outer = $item;
                   12407:                                     last;
                   12408:                                 }
                   12409:                             }
                   12410:                         }
                   12411:                     }
                   12412:                     my ($errtext,$fatal) = 
                   12413:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12414:                                                '/'.$folders{$outer}.'.'.
                   12415:                                                $containers{$outer});
                   12416:                     next if ($fatal);
                   12417:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12418:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12419:                             $mapinner{$i} = time;
1.1055    raeburn  12420:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12421:                             $containers{$i} = 'sequence';
                   12422:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12423:                                       $folders{$i}.'.'.$containers{$i};
                   12424:                             my $newidx = &LONCAPA::map::getresidx();
                   12425:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12426:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12427:                             push(@LONCAPA::map::order,$newidx);
                   12428:                             my ($outtext,$errtext) =
                   12429:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12430:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12431:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12432:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12433:                             unless ($errtext) {
                   12434:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12435:                             }
1.1055    raeburn  12436:                         }
                   12437:                     } else {
                   12438:                         if ($context eq 'coursedocs') {
                   12439:                             my $newidx=&LONCAPA::map::getresidx();
                   12440:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12441:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12442:                                       $title;
                   12443:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12444:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12445:                             }
                   12446:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12447:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12448:                             }
                   12449:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12450:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12451:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12452:                                 unless ($ishome) {
                   12453:                                     my $fetch = "$newdest{$i}/$title";
                   12454:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12455:                                     $prompttofetch{$fetch} = 1;
                   12456:                                 }
1.1055    raeburn  12457:                             }
                   12458:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12459:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12460:                             push(@LONCAPA::map::order, $newidx);
                   12461:                             my ($outtext,$errtext)=
                   12462:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12463:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12464:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12465:                             unless ($errtext) {
                   12466:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12467:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12468:                                 }
                   12469:                             }
1.1055    raeburn  12470:                         }
                   12471:                     }
1.1086    raeburn  12472:                 }
                   12473:             } else {
                   12474:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12475:             }
                   12476:         }
                   12477:         for (my $i=1; $i<=$numitems; $i++) {
                   12478:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12479:             my $path = $env{'form.archive_content_'.$i};
                   12480:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12481:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12482:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12483:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12484:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12485:                         my ($itemidx,$fullpath,$relpath);
                   12486:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12487:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12488:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12489:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12490:                                     $itemidx = $j;
1.1056    raeburn  12491:                                 }
                   12492:                             }
1.1086    raeburn  12493:                         }
                   12494:                         if ($itemidx eq '') {
                   12495:                             $itemidx =  0;
                   12496:                         } 
                   12497:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12498:                             if ($mapinner{$referrer{$i}}) {
                   12499:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12500:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12501:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12502:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12503:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12504:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12505:                                             if (!-e $fullpath) {
                   12506:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12507:                                             }
                   12508:                                         }
1.1086    raeburn  12509:                                     } else {
                   12510:                                         last;
1.1056    raeburn  12511:                                     }
1.1086    raeburn  12512:                                 }
                   12513:                             }
                   12514:                         } elsif ($newdest{$referrer{$i}}) {
                   12515:                             $fullpath = $newdest{$referrer{$i}};
                   12516:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12517:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12518:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12519:                                     last;
                   12520:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12521:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12522:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12523:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12524:                                         if (!-e $fullpath) {
                   12525:                                             mkdir($fullpath,0755);
1.1056    raeburn  12526:                                         }
                   12527:                                     }
1.1086    raeburn  12528:                                 } else {
                   12529:                                     last;
1.1056    raeburn  12530:                                 }
1.1055    raeburn  12531:                             }
                   12532:                         }
1.1086    raeburn  12533:                         if ($fullpath ne '') {
                   12534:                             if (-e "$prefix$path") {
                   12535:                                 system("mv $prefix$path $fullpath/$title");
                   12536:                             }
                   12537:                             if (-e "$fullpath/$title") {
                   12538:                                 my $showpath;
                   12539:                                 if ($relpath ne '') {
                   12540:                                     $showpath = "$relpath/$title";
                   12541:                                 } else {
                   12542:                                     $showpath = "/$title";
                   12543:                                 } 
                   12544:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12545:                             } 
                   12546:                             unless ($ishome) {
                   12547:                                 my $fetch = "$fullpath/$title";
                   12548:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12549:                                 $prompttofetch{$fetch} = 1;
                   12550:                             }
                   12551:                         }
1.1055    raeburn  12552:                     }
1.1086    raeburn  12553:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12554:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12555:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12556:                 }
                   12557:             } else {
                   12558:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12559:             }
                   12560:         }
                   12561:         if (keys(%todelete)) {
                   12562:             foreach my $key (keys(%todelete)) {
                   12563:                 unlink($key);
1.1066    raeburn  12564:             }
                   12565:         }
                   12566:         if (keys(%todeletedir)) {
                   12567:             foreach my $key (keys(%todeletedir)) {
                   12568:                 rmdir($key);
                   12569:             }
                   12570:         }
                   12571:         foreach my $dir (sort(keys(%is_dir))) {
                   12572:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12573:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12574:             }
                   12575:         }
1.1067    raeburn  12576:         if ($result ne '') {
                   12577:             $output .= '<ul>'."\n".
                   12578:                        $result."\n".
                   12579:                        '</ul>';
                   12580:         }
                   12581:         unless ($ishome) {
                   12582:             my $replicationfail;
                   12583:             foreach my $item (keys(%prompttofetch)) {
                   12584:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12585:                 unless ($fetchresult eq 'ok') {
                   12586:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12587:                 }
                   12588:             }
                   12589:             if ($replicationfail) {
                   12590:                 $output .= '<p class="LC_error">'.
                   12591:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12592:                            $replicationfail.
                   12593:                            '</ul></p>';
                   12594:             }
                   12595:         }
1.1055    raeburn  12596:     } else {
                   12597:         $warning = &mt('No items found in archive.');
                   12598:     }
                   12599:     if ($error) {
                   12600:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12601:                    $error.'</p>'."\n";
                   12602:     }
                   12603:     if ($warning) {
                   12604:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12605:     }
                   12606:     return $output;
                   12607: }
                   12608: 
1.1066    raeburn  12609: sub cleanup_empty_dirs {
                   12610:     my ($path) = @_;
                   12611:     if (($path ne '') && (-d $path)) {
                   12612:         if (opendir(my $dirh,$path)) {
                   12613:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12614:             my $numitems = 0;
                   12615:             foreach my $item (@dircontents) {
                   12616:                 if (-d "$path/$item") {
1.1111    raeburn  12617:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12618:                     if (-e "$path/$item") {
                   12619:                         $numitems ++;
                   12620:                     }
                   12621:                 } else {
                   12622:                     $numitems ++;
                   12623:                 }
                   12624:             }
                   12625:             if ($numitems == 0) {
                   12626:                 rmdir($path);
                   12627:             }
                   12628:             closedir($dirh);
                   12629:         }
                   12630:     }
                   12631:     return;
                   12632: }
                   12633: 
1.41      ng       12634: =pod
1.45      matthew  12635: 
1.1162    raeburn  12636: =item * &get_folder_hierarchy()
1.1068    raeburn  12637: 
                   12638: Provides hierarchy of names of folders/sub-folders containing the current
                   12639: item,
                   12640: 
                   12641: Inputs: 3
                   12642:      - $navmap - navmaps object
                   12643: 
                   12644:      - $map - url for map (either the trigger itself, or map containing
                   12645:                            the resource, which is the trigger).
                   12646: 
                   12647:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12648: 
                   12649: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12650: 
                   12651: =cut
                   12652: 
                   12653: sub get_folder_hierarchy {
                   12654:     my ($navmap,$map,$showitem) = @_;
                   12655:     my @pathitems;
                   12656:     if (ref($navmap)) {
                   12657:         my $mapres = $navmap->getResourceByUrl($map);
                   12658:         if (ref($mapres)) {
                   12659:             my $pcslist = $mapres->map_hierarchy();
                   12660:             if ($pcslist ne '') {
                   12661:                 my @pcs = split(/,/,$pcslist);
                   12662:                 foreach my $pc (@pcs) {
                   12663:                     if ($pc == 1) {
1.1129    raeburn  12664:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12665:                     } else {
                   12666:                         my $res = $navmap->getByMapPc($pc);
                   12667:                         if (ref($res)) {
                   12668:                             my $title = $res->compTitle();
                   12669:                             $title =~ s/\W+/_/g;
                   12670:                             if ($title ne '') {
                   12671:                                 push(@pathitems,$title);
                   12672:                             }
                   12673:                         }
                   12674:                     }
                   12675:                 }
                   12676:             }
1.1071    raeburn  12677:             if ($showitem) {
                   12678:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12679:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12680:                 } else {
                   12681:                     my $maptitle = $mapres->compTitle();
                   12682:                     $maptitle =~ s/\W+/_/g;
                   12683:                     if ($maptitle ne '') {
                   12684:                         push(@pathitems,$maptitle);
                   12685:                     }
1.1068    raeburn  12686:                 }
                   12687:             }
                   12688:         }
                   12689:     }
                   12690:     return @pathitems;
                   12691: }
                   12692: 
                   12693: =pod
                   12694: 
1.1015    raeburn  12695: =item * &get_turnedin_filepath()
                   12696: 
                   12697: Determines path in a user's portfolio file for storage of files uploaded
                   12698: to a specific essayresponse or dropbox item.
                   12699: 
                   12700: Inputs: 3 required + 1 optional.
                   12701: $symb is symb for resource, $uname and $udom are for current user (required).
                   12702: $caller is optional (can be "submission", if routine is called when storing
                   12703: an upoaded file when "Submit Answer" button was pressed).
                   12704: 
                   12705: Returns array containing $path and $multiresp. 
                   12706: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12707: than one file upload item.  Callers of routine should append partid as a 
                   12708: subdirectory to $path in cases where $multiresp is 1.
                   12709: 
                   12710: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12711: 
                   12712: =cut
                   12713: 
                   12714: sub get_turnedin_filepath {
                   12715:     my ($symb,$uname,$udom,$caller) = @_;
                   12716:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12717:     my $turnindir;
                   12718:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12719:     $turnindir = $userhash{'turnindir'};
                   12720:     my ($path,$multiresp);
                   12721:     if ($turnindir eq '') {
                   12722:         if ($caller eq 'submission') {
                   12723:             $turnindir = &mt('turned in');
                   12724:             $turnindir =~ s/\W+/_/g;
                   12725:             my %newhash = (
                   12726:                             'turnindir' => $turnindir,
                   12727:                           );
                   12728:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12729:         }
                   12730:     }
                   12731:     if ($turnindir ne '') {
                   12732:         $path = '/'.$turnindir.'/';
                   12733:         my ($multipart,$turnin,@pathitems);
                   12734:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12735:         if (defined($navmap)) {
                   12736:             my $mapres = $navmap->getResourceByUrl($map);
                   12737:             if (ref($mapres)) {
                   12738:                 my $pcslist = $mapres->map_hierarchy();
                   12739:                 if ($pcslist ne '') {
                   12740:                     foreach my $pc (split(/,/,$pcslist)) {
                   12741:                         my $res = $navmap->getByMapPc($pc);
                   12742:                         if (ref($res)) {
                   12743:                             my $title = $res->compTitle();
                   12744:                             $title =~ s/\W+/_/g;
                   12745:                             if ($title ne '') {
1.1149    raeburn  12746:                                 if (($pc > 1) && (length($title) > 12)) {
                   12747:                                     $title = substr($title,0,12);
                   12748:                                 }
1.1015    raeburn  12749:                                 push(@pathitems,$title);
                   12750:                             }
                   12751:                         }
                   12752:                     }
                   12753:                 }
                   12754:                 my $maptitle = $mapres->compTitle();
                   12755:                 $maptitle =~ s/\W+/_/g;
                   12756:                 if ($maptitle ne '') {
1.1149    raeburn  12757:                     if (length($maptitle) > 12) {
                   12758:                         $maptitle = substr($maptitle,0,12);
                   12759:                     }
1.1015    raeburn  12760:                     push(@pathitems,$maptitle);
                   12761:                 }
                   12762:                 unless ($env{'request.state'} eq 'construct') {
                   12763:                     my $res = $navmap->getBySymb($symb);
                   12764:                     if (ref($res)) {
                   12765:                         my $partlist = $res->parts();
                   12766:                         my $totaluploads = 0;
                   12767:                         if (ref($partlist) eq 'ARRAY') {
                   12768:                             foreach my $part (@{$partlist}) {
                   12769:                                 my @types = $res->responseType($part);
                   12770:                                 my @ids = $res->responseIds($part);
                   12771:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12772:                                     if ($types[$i] eq 'essay') {
                   12773:                                         my $partid = $part.'_'.$ids[$i];
                   12774:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12775:                                             $totaluploads ++;
                   12776:                                         }
                   12777:                                     }
                   12778:                                 }
                   12779:                             }
                   12780:                             if ($totaluploads > 1) {
                   12781:                                 $multiresp = 1;
                   12782:                             }
                   12783:                         }
                   12784:                     }
                   12785:                 }
                   12786:             } else {
                   12787:                 return;
                   12788:             }
                   12789:         } else {
                   12790:             return;
                   12791:         }
                   12792:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12793:         $restitle =~ s/\W+/_/g;
                   12794:         if ($restitle eq '') {
                   12795:             $restitle = ($resurl =~ m{/[^/]+$});
                   12796:             if ($restitle eq '') {
                   12797:                 $restitle = time;
                   12798:             }
                   12799:         }
1.1149    raeburn  12800:         if (length($restitle) > 12) {
                   12801:             $restitle = substr($restitle,0,12);
                   12802:         }
1.1015    raeburn  12803:         push(@pathitems,$restitle);
                   12804:         $path .= join('/',@pathitems);
                   12805:     }
                   12806:     return ($path,$multiresp);
                   12807: }
                   12808: 
                   12809: =pod
                   12810: 
1.464     albertel 12811: =back
1.41      ng       12812: 
1.112     bowersj2 12813: =head1 CSV Upload/Handling functions
1.38      albertel 12814: 
1.41      ng       12815: =over 4
                   12816: 
1.648     raeburn  12817: =item * &upfile_store($r)
1.41      ng       12818: 
                   12819: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12820: needs $env{'form.upfile'}
1.41      ng       12821: returns $datatoken to be put into hidden field
                   12822: 
                   12823: =cut
1.31      albertel 12824: 
                   12825: sub upfile_store {
                   12826:     my $r=shift;
1.258     albertel 12827:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12828:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12829:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12830:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12831: 
1.258     albertel 12832:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12833: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12834:     {
1.158     raeburn  12835:         my $datafile = $r->dir_config('lonDaemons').
                   12836:                            '/tmp/'.$datatoken.'.tmp';
                   12837:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12838:             print $fh $env{'form.upfile'};
1.158     raeburn  12839:             close($fh);
                   12840:         }
1.31      albertel 12841:     }
                   12842:     return $datatoken;
                   12843: }
                   12844: 
1.56      matthew  12845: =pod
                   12846: 
1.648     raeburn  12847: =item * &load_tmp_file($r)
1.41      ng       12848: 
                   12849: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12850: needs $env{'form.datatoken'},
                   12851: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12852: 
                   12853: =cut
1.31      albertel 12854: 
                   12855: sub load_tmp_file {
                   12856:     my $r=shift;
                   12857:     my @studentdata=();
                   12858:     {
1.158     raeburn  12859:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12860:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12861:         if ( open(my $fh,"<$studentfile") ) {
                   12862:             @studentdata=<$fh>;
                   12863:             close($fh);
                   12864:         }
1.31      albertel 12865:     }
1.258     albertel 12866:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12867: }
                   12868: 
1.56      matthew  12869: =pod
                   12870: 
1.648     raeburn  12871: =item * &upfile_record_sep()
1.41      ng       12872: 
                   12873: Separate uploaded file into records
                   12874: returns array of records,
1.258     albertel 12875: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12876: 
                   12877: =cut
1.31      albertel 12878: 
                   12879: sub upfile_record_sep {
1.258     albertel 12880:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12881:     } else {
1.248     albertel 12882: 	my @records;
1.258     albertel 12883: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12884: 	    if ($line=~/^\s*$/) { next; }
                   12885: 	    push(@records,$line);
                   12886: 	}
                   12887: 	return @records;
1.31      albertel 12888:     }
                   12889: }
                   12890: 
1.56      matthew  12891: =pod
                   12892: 
1.648     raeburn  12893: =item * &record_sep($record)
1.41      ng       12894: 
1.258     albertel 12895: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12896: 
                   12897: =cut
                   12898: 
1.263     www      12899: sub takeleft {
                   12900:     my $index=shift;
                   12901:     return substr('0000'.$index,-4,4);
                   12902: }
                   12903: 
1.31      albertel 12904: sub record_sep {
                   12905:     my $record=shift;
                   12906:     my %components=();
1.258     albertel 12907:     if ($env{'form.upfiletype'} eq 'xml') {
                   12908:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12909:         my $i=0;
1.356     albertel 12910:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12911:             $field=~s/^(\"|\')//;
                   12912:             $field=~s/(\"|\')$//;
1.263     www      12913:             $components{&takeleft($i)}=$field;
1.31      albertel 12914:             $i++;
                   12915:         }
1.258     albertel 12916:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12917:         my $i=0;
1.356     albertel 12918:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12919:             $field=~s/^(\"|\')//;
                   12920:             $field=~s/(\"|\')$//;
1.263     www      12921:             $components{&takeleft($i)}=$field;
1.31      albertel 12922:             $i++;
                   12923:         }
                   12924:     } else {
1.561     www      12925:         my $separator=',';
1.480     banghart 12926:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12927:             $separator=';';
1.480     banghart 12928:         }
1.31      albertel 12929:         my $i=0;
1.561     www      12930: # the character we are looking for to indicate the end of a quote or a record 
                   12931:         my $looking_for=$separator;
                   12932: # do not add the characters to the fields
                   12933:         my $ignore=0;
                   12934: # we just encountered a separator (or the beginning of the record)
                   12935:         my $just_found_separator=1;
                   12936: # store the field we are working on here
                   12937:         my $field='';
                   12938: # work our way through all characters in record
                   12939:         foreach my $character ($record=~/(.)/g) {
                   12940:             if ($character eq $looking_for) {
                   12941:                if ($character ne $separator) {
                   12942: # Found the end of a quote, again looking for separator
                   12943:                   $looking_for=$separator;
                   12944:                   $ignore=1;
                   12945:                } else {
                   12946: # Found a separator, store away what we got
                   12947:                   $components{&takeleft($i)}=$field;
                   12948: 	          $i++;
                   12949:                   $just_found_separator=1;
                   12950:                   $ignore=0;
                   12951:                   $field='';
                   12952:                }
                   12953:                next;
                   12954:             }
                   12955: # single or double quotation marks after a separator indicate beginning of a quote
                   12956: # we are now looking for the end of the quote and need to ignore separators
                   12957:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12958:                $looking_for=$character;
                   12959:                next;
                   12960:             }
                   12961: # ignore would be true after we reached the end of a quote
                   12962:             if ($ignore) { next; }
                   12963:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12964:             $field.=$character;
                   12965:             $just_found_separator=0; 
1.31      albertel 12966:         }
1.561     www      12967: # catch the very last entry, since we never encountered the separator
                   12968:         $components{&takeleft($i)}=$field;
1.31      albertel 12969:     }
                   12970:     return %components;
                   12971: }
                   12972: 
1.144     matthew  12973: ######################################################
                   12974: ######################################################
                   12975: 
1.56      matthew  12976: =pod
                   12977: 
1.648     raeburn  12978: =item * &upfile_select_html()
1.41      ng       12979: 
1.144     matthew  12980: Return HTML code to select a file from the users machine and specify 
                   12981: the file type.
1.41      ng       12982: 
                   12983: =cut
                   12984: 
1.144     matthew  12985: ######################################################
                   12986: ######################################################
1.31      albertel 12987: sub upfile_select_html {
1.144     matthew  12988:     my %Types = (
                   12989:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12990:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12991:                  space => &mt('Space separated'),
                   12992:                  tab   => &mt('Tabulator separated'),
                   12993: #                 xml   => &mt('HTML/XML'),
                   12994:                  );
                   12995:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12996:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12997:     foreach my $type (sort(keys(%Types))) {
                   12998:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12999:     }
                   13000:     $Str .= "</select>\n";
                   13001:     return $Str;
1.31      albertel 13002: }
                   13003: 
1.301     albertel 13004: sub get_samples {
                   13005:     my ($records,$toget) = @_;
                   13006:     my @samples=({});
                   13007:     my $got=0;
                   13008:     foreach my $rec (@$records) {
                   13009: 	my %temp = &record_sep($rec);
                   13010: 	if (! grep(/\S/, values(%temp))) { next; }
                   13011: 	if (%temp) {
                   13012: 	    $samples[$got]=\%temp;
                   13013: 	    $got++;
                   13014: 	    if ($got == $toget) { last; }
                   13015: 	}
                   13016:     }
                   13017:     return \@samples;
                   13018: }
                   13019: 
1.144     matthew  13020: ######################################################
                   13021: ######################################################
                   13022: 
1.56      matthew  13023: =pod
                   13024: 
1.648     raeburn  13025: =item * &csv_print_samples($r,$records)
1.41      ng       13026: 
                   13027: Prints a table of sample values from each column uploaded $r is an
                   13028: Apache Request ref, $records is an arrayref from
                   13029: &Apache::loncommon::upfile_record_sep
                   13030: 
                   13031: =cut
                   13032: 
1.144     matthew  13033: ######################################################
                   13034: ######################################################
1.31      albertel 13035: sub csv_print_samples {
                   13036:     my ($r,$records) = @_;
1.662     bisitz   13037:     my $samples = &get_samples($records,5);
1.301     albertel 13038: 
1.594     raeburn  13039:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13040:               &start_data_table_header_row());
1.356     albertel 13041:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13042:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13043:     $r->print(&end_data_table_header_row());
1.301     albertel 13044:     foreach my $hash (@$samples) {
1.594     raeburn  13045: 	$r->print(&start_data_table_row());
1.356     albertel 13046: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13047: 	    $r->print('<td>');
1.356     albertel 13048: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13049: 	    $r->print('</td>');
                   13050: 	}
1.594     raeburn  13051: 	$r->print(&end_data_table_row());
1.31      albertel 13052:     }
1.594     raeburn  13053:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13054: }
                   13055: 
1.144     matthew  13056: ######################################################
                   13057: ######################################################
                   13058: 
1.56      matthew  13059: =pod
                   13060: 
1.648     raeburn  13061: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13062: 
                   13063: Prints a table to create associations between values and table columns.
1.144     matthew  13064: 
1.41      ng       13065: $r is an Apache Request ref,
                   13066: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13067: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13068: 
                   13069: =cut
                   13070: 
1.144     matthew  13071: ######################################################
                   13072: ######################################################
1.31      albertel 13073: sub csv_print_select_table {
                   13074:     my ($r,$records,$d) = @_;
1.301     albertel 13075:     my $i=0;
                   13076:     my $samples = &get_samples($records,1);
1.144     matthew  13077:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13078: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13079:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13080:               '<th>'.&mt('Column').'</th>'.
                   13081:               &end_data_table_header_row()."\n");
1.356     albertel 13082:     foreach my $array_ref (@$d) {
                   13083: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13084: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13085: 
1.875     bisitz   13086: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13087: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13088: 	$r->print('<option value="none"></option>');
1.356     albertel 13089: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13090: 	    $r->print('<option value="'.$sample.'"'.
                   13091:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13092:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13093: 	}
1.594     raeburn  13094: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13095: 	$i++;
                   13096:     }
1.594     raeburn  13097:     $r->print(&end_data_table());
1.31      albertel 13098:     $i--;
                   13099:     return $i;
                   13100: }
1.56      matthew  13101: 
1.144     matthew  13102: ######################################################
                   13103: ######################################################
                   13104: 
1.56      matthew  13105: =pod
1.31      albertel 13106: 
1.648     raeburn  13107: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13108: 
                   13109: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13110: 
                   13111: $r is an Apache Request ref,
                   13112: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13113: $d is an array of 2 element arrays (internal name, displayed name)
                   13114: 
                   13115: =cut
                   13116: 
1.144     matthew  13117: ######################################################
                   13118: ######################################################
1.31      albertel 13119: sub csv_samples_select_table {
                   13120:     my ($r,$records,$d) = @_;
                   13121:     my $i=0;
1.144     matthew  13122:     #
1.662     bisitz   13123:     my $max_samples = 5;
                   13124:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13125:     $r->print(&start_data_table().
                   13126:               &start_data_table_header_row().'<th>'.
                   13127:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13128:               &end_data_table_header_row());
1.301     albertel 13129: 
                   13130:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13131: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13132: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13133: 	foreach my $option (@$d) {
                   13134: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13135: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13136:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13137:                       $display.'</option>');
1.31      albertel 13138: 	}
                   13139: 	$r->print('</select></td><td>');
1.662     bisitz   13140: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13141: 	    if (defined($samples->[$line]{$key})) { 
                   13142: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13143: 	    }
                   13144: 	}
1.594     raeburn  13145: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13146: 	$i++;
                   13147:     }
1.594     raeburn  13148:     $r->print(&end_data_table());
1.31      albertel 13149:     $i--;
                   13150:     return($i);
1.115     matthew  13151: }
                   13152: 
1.144     matthew  13153: ######################################################
                   13154: ######################################################
                   13155: 
1.115     matthew  13156: =pod
                   13157: 
1.648     raeburn  13158: =item * &clean_excel_name($name)
1.115     matthew  13159: 
                   13160: Returns a replacement for $name which does not contain any illegal characters.
                   13161: 
                   13162: =cut
                   13163: 
1.144     matthew  13164: ######################################################
                   13165: ######################################################
1.115     matthew  13166: sub clean_excel_name {
                   13167:     my ($name) = @_;
                   13168:     $name =~ s/[:\*\?\/\\]//g;
                   13169:     if (length($name) > 31) {
                   13170:         $name = substr($name,0,31);
                   13171:     }
                   13172:     return $name;
1.25      albertel 13173: }
1.84      albertel 13174: 
1.85      albertel 13175: =pod
                   13176: 
1.648     raeburn  13177: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13178: 
                   13179: Returns either 1 or undef
                   13180: 
                   13181: 1 if the part is to be hidden, undef if it is to be shown
                   13182: 
                   13183: Arguments are:
                   13184: 
                   13185: $id the id of the part to be checked
                   13186: $symb, optional the symb of the resource to check
                   13187: $udom, optional the domain of the user to check for
                   13188: $uname, optional the username of the user to check for
                   13189: 
                   13190: =cut
1.84      albertel 13191: 
                   13192: sub check_if_partid_hidden {
                   13193:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13194:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13195: 					 $symb,$udom,$uname);
1.141     albertel 13196:     my $truth=1;
                   13197:     #if the string starts with !, then the list is the list to show not hide
                   13198:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13199:     my @hiddenlist=split(/,/,$hiddenparts);
                   13200:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13201: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13202:     }
1.141     albertel 13203:     return !$truth;
1.84      albertel 13204: }
1.127     matthew  13205: 
1.138     matthew  13206: 
                   13207: ############################################################
                   13208: ############################################################
                   13209: 
                   13210: =pod
                   13211: 
1.157     matthew  13212: =back 
                   13213: 
1.138     matthew  13214: =head1 cgi-bin script and graphing routines
                   13215: 
1.157     matthew  13216: =over 4
                   13217: 
1.648     raeburn  13218: =item * &get_cgi_id()
1.138     matthew  13219: 
                   13220: Inputs: none
                   13221: 
                   13222: Returns an id which can be used to pass environment variables
                   13223: to various cgi-bin scripts.  These environment variables will
                   13224: be removed from the users environment after a given time by
                   13225: the routine &Apache::lonnet::transfer_profile_to_env.
                   13226: 
                   13227: =cut
                   13228: 
                   13229: ############################################################
                   13230: ############################################################
1.152     albertel 13231: my $uniq=0;
1.136     matthew  13232: sub get_cgi_id {
1.154     albertel 13233:     $uniq=($uniq+1)%100000;
1.280     albertel 13234:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13235: }
                   13236: 
1.127     matthew  13237: ############################################################
                   13238: ############################################################
                   13239: 
                   13240: =pod
                   13241: 
1.648     raeburn  13242: =item * &DrawBarGraph()
1.127     matthew  13243: 
1.138     matthew  13244: Facilitates the plotting of data in a (stacked) bar graph.
                   13245: Puts plot definition data into the users environment in order for 
                   13246: graph.png to plot it.  Returns an <img> tag for the plot.
                   13247: The bars on the plot are labeled '1','2',...,'n'.
                   13248: 
                   13249: Inputs:
                   13250: 
                   13251: =over 4
                   13252: 
                   13253: =item $Title: string, the title of the plot
                   13254: 
                   13255: =item $xlabel: string, text describing the X-axis of the plot
                   13256: 
                   13257: =item $ylabel: string, text describing the Y-axis of the plot
                   13258: 
                   13259: =item $Max: scalar, the maximum Y value to use in the plot
                   13260: If $Max is < any data point, the graph will not be rendered.
                   13261: 
1.140     matthew  13262: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13263: they are plotted.  If undefined, default values will be used.
                   13264: 
1.178     matthew  13265: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13266: 
1.138     matthew  13267: =item @Values: An array of array references.  Each array reference holds data
                   13268: to be plotted in a stacked bar chart.
                   13269: 
1.239     matthew  13270: =item If the final element of @Values is a hash reference the key/value
                   13271: pairs will be added to the graph definition.
                   13272: 
1.138     matthew  13273: =back
                   13274: 
                   13275: Returns:
                   13276: 
                   13277: An <img> tag which references graph.png and the appropriate identifying
                   13278: information for the plot.
                   13279: 
1.127     matthew  13280: =cut
                   13281: 
                   13282: ############################################################
                   13283: ############################################################
1.134     matthew  13284: sub DrawBarGraph {
1.178     matthew  13285:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13286:     #
                   13287:     if (! defined($colors)) {
                   13288:         $colors = ['#33ff00', 
                   13289:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13290:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13291:                   ]; 
                   13292:     }
1.228     matthew  13293:     my $extra_settings = {};
                   13294:     if (ref($Values[-1]) eq 'HASH') {
                   13295:         $extra_settings = pop(@Values);
                   13296:     }
1.127     matthew  13297:     #
1.136     matthew  13298:     my $identifier = &get_cgi_id();
                   13299:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13300:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13301:         return '';
                   13302:     }
1.225     matthew  13303:     #
                   13304:     my @Labels;
                   13305:     if (defined($labels)) {
                   13306:         @Labels = @$labels;
                   13307:     } else {
                   13308:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13309:             push (@Labels,$i+1);
                   13310:         }
                   13311:     }
                   13312:     #
1.129     matthew  13313:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13314:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13315:     my %ValuesHash;
                   13316:     my $NumSets=1;
                   13317:     foreach my $array (@Values) {
                   13318:         next if (! ref($array));
1.136     matthew  13319:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13320:             join(',',@$array);
1.129     matthew  13321:     }
1.127     matthew  13322:     #
1.136     matthew  13323:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13324:     if ($NumBars < 3) {
                   13325:         $width = 120+$NumBars*32;
1.220     matthew  13326:         $xskip = 1;
1.225     matthew  13327:         $bar_width = 30;
                   13328:     } elsif ($NumBars < 5) {
                   13329:         $width = 120+$NumBars*20;
                   13330:         $xskip = 1;
                   13331:         $bar_width = 20;
1.220     matthew  13332:     } elsif ($NumBars < 10) {
1.136     matthew  13333:         $width = 120+$NumBars*15;
                   13334:         $xskip = 1;
                   13335:         $bar_width = 15;
                   13336:     } elsif ($NumBars <= 25) {
                   13337:         $width = 120+$NumBars*11;
                   13338:         $xskip = 5;
                   13339:         $bar_width = 8;
                   13340:     } elsif ($NumBars <= 50) {
                   13341:         $width = 120+$NumBars*8;
                   13342:         $xskip = 5;
                   13343:         $bar_width = 4;
                   13344:     } else {
                   13345:         $width = 120+$NumBars*8;
                   13346:         $xskip = 5;
                   13347:         $bar_width = 4;
                   13348:     }
                   13349:     #
1.137     matthew  13350:     $Max = 1 if ($Max < 1);
                   13351:     if ( int($Max) < $Max ) {
                   13352:         $Max++;
                   13353:         $Max = int($Max);
                   13354:     }
1.127     matthew  13355:     $Title  = '' if (! defined($Title));
                   13356:     $xlabel = '' if (! defined($xlabel));
                   13357:     $ylabel = '' if (! defined($ylabel));
1.369     www      13358:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13359:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13360:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13361:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13362:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13363:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13364:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13365:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13366:     $ValuesHash{$id.'.height'}   = $height;
                   13367:     $ValuesHash{$id.'.width'}    = $width;
                   13368:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13369:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13370:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13371:     #
1.228     matthew  13372:     # Deal with other parameters
                   13373:     while (my ($key,$value) = each(%$extra_settings)) {
                   13374:         $ValuesHash{$id.'.'.$key} = $value;
                   13375:     }
                   13376:     #
1.646     raeburn  13377:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13378:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13379: }
                   13380: 
                   13381: ############################################################
                   13382: ############################################################
                   13383: 
                   13384: =pod
                   13385: 
1.648     raeburn  13386: =item * &DrawXYGraph()
1.137     matthew  13387: 
1.138     matthew  13388: Facilitates the plotting of data in an XY graph.
                   13389: Puts plot definition data into the users environment in order for 
                   13390: graph.png to plot it.  Returns an <img> tag for the plot.
                   13391: 
                   13392: Inputs:
                   13393: 
                   13394: =over 4
                   13395: 
                   13396: =item $Title: string, the title of the plot
                   13397: 
                   13398: =item $xlabel: string, text describing the X-axis of the plot
                   13399: 
                   13400: =item $ylabel: string, text describing the Y-axis of the plot
                   13401: 
                   13402: =item $Max: scalar, the maximum Y value to use in the plot
                   13403: If $Max is < any data point, the graph will not be rendered.
                   13404: 
                   13405: =item $colors: Array ref containing the hex color codes for the data to be 
                   13406: plotted in.  If undefined, default values will be used.
                   13407: 
                   13408: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13409: 
                   13410: =item $Ydata: Array ref containing Array refs.  
1.185     www      13411: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13412: 
                   13413: =item %Values: hash indicating or overriding any default values which are 
                   13414: passed to graph.png.  
                   13415: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13416: 
                   13417: =back
                   13418: 
                   13419: Returns:
                   13420: 
                   13421: An <img> tag which references graph.png and the appropriate identifying
                   13422: information for the plot.
                   13423: 
1.137     matthew  13424: =cut
                   13425: 
                   13426: ############################################################
                   13427: ############################################################
                   13428: sub DrawXYGraph {
                   13429:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13430:     #
                   13431:     # Create the identifier for the graph
                   13432:     my $identifier = &get_cgi_id();
                   13433:     my $id = 'cgi.'.$identifier;
                   13434:     #
                   13435:     $Title  = '' if (! defined($Title));
                   13436:     $xlabel = '' if (! defined($xlabel));
                   13437:     $ylabel = '' if (! defined($ylabel));
                   13438:     my %ValuesHash = 
                   13439:         (
1.369     www      13440:          $id.'.title'  => &escape($Title),
                   13441:          $id.'.xlabel' => &escape($xlabel),
                   13442:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13443:          $id.'.y_max_value'=> $Max,
                   13444:          $id.'.labels'     => join(',',@$Xlabels),
                   13445:          $id.'.PlotType'   => 'XY',
                   13446:          );
                   13447:     #
                   13448:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13449:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13450:     }
                   13451:     #
                   13452:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13453:         return '';
                   13454:     }
                   13455:     my $NumSets=1;
1.138     matthew  13456:     foreach my $array (@{$Ydata}){
1.137     matthew  13457:         next if (! ref($array));
                   13458:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13459:     }
1.138     matthew  13460:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13461:     #
                   13462:     # Deal with other parameters
                   13463:     while (my ($key,$value) = each(%Values)) {
                   13464:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13465:     }
                   13466:     #
1.646     raeburn  13467:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13468:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13469: }
                   13470: 
                   13471: ############################################################
                   13472: ############################################################
                   13473: 
                   13474: =pod
                   13475: 
1.648     raeburn  13476: =item * &DrawXYYGraph()
1.138     matthew  13477: 
                   13478: Facilitates the plotting of data in an XY graph with two Y axes.
                   13479: Puts plot definition data into the users environment in order for 
                   13480: graph.png to plot it.  Returns an <img> tag for the plot.
                   13481: 
                   13482: Inputs:
                   13483: 
                   13484: =over 4
                   13485: 
                   13486: =item $Title: string, the title of the plot
                   13487: 
                   13488: =item $xlabel: string, text describing the X-axis of the plot
                   13489: 
                   13490: =item $ylabel: string, text describing the Y-axis of the plot
                   13491: 
                   13492: =item $colors: Array ref containing the hex color codes for the data to be 
                   13493: plotted in.  If undefined, default values will be used.
                   13494: 
                   13495: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13496: 
                   13497: =item $Ydata1: The first data set
                   13498: 
                   13499: =item $Min1: The minimum value of the left Y-axis
                   13500: 
                   13501: =item $Max1: The maximum value of the left Y-axis
                   13502: 
                   13503: =item $Ydata2: The second data set
                   13504: 
                   13505: =item $Min2: The minimum value of the right Y-axis
                   13506: 
                   13507: =item $Max2: The maximum value of the left Y-axis
                   13508: 
                   13509: =item %Values: hash indicating or overriding any default values which are 
                   13510: passed to graph.png.  
                   13511: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13512: 
                   13513: =back
                   13514: 
                   13515: Returns:
                   13516: 
                   13517: An <img> tag which references graph.png and the appropriate identifying
                   13518: information for the plot.
1.136     matthew  13519: 
                   13520: =cut
                   13521: 
                   13522: ############################################################
                   13523: ############################################################
1.137     matthew  13524: sub DrawXYYGraph {
                   13525:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13526:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13527:     #
                   13528:     # Create the identifier for the graph
                   13529:     my $identifier = &get_cgi_id();
                   13530:     my $id = 'cgi.'.$identifier;
                   13531:     #
                   13532:     $Title  = '' if (! defined($Title));
                   13533:     $xlabel = '' if (! defined($xlabel));
                   13534:     $ylabel = '' if (! defined($ylabel));
                   13535:     my %ValuesHash = 
                   13536:         (
1.369     www      13537:          $id.'.title'  => &escape($Title),
                   13538:          $id.'.xlabel' => &escape($xlabel),
                   13539:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13540:          $id.'.labels' => join(',',@$Xlabels),
                   13541:          $id.'.PlotType' => 'XY',
                   13542:          $id.'.NumSets' => 2,
1.137     matthew  13543:          $id.'.two_axes' => 1,
                   13544:          $id.'.y1_max_value' => $Max1,
                   13545:          $id.'.y1_min_value' => $Min1,
                   13546:          $id.'.y2_max_value' => $Max2,
                   13547:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13548:          );
                   13549:     #
1.137     matthew  13550:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13551:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13552:     }
                   13553:     #
                   13554:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13555:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13556:         return '';
                   13557:     }
                   13558:     my $NumSets=1;
1.137     matthew  13559:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13560:         next if (! ref($array));
                   13561:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13562:     }
                   13563:     #
                   13564:     # Deal with other parameters
                   13565:     while (my ($key,$value) = each(%Values)) {
                   13566:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13567:     }
                   13568:     #
1.646     raeburn  13569:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13570:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13571: }
                   13572: 
                   13573: ############################################################
                   13574: ############################################################
                   13575: 
                   13576: =pod
                   13577: 
1.157     matthew  13578: =back 
                   13579: 
1.139     matthew  13580: =head1 Statistics helper routines?  
                   13581: 
                   13582: Bad place for them but what the hell.
                   13583: 
1.157     matthew  13584: =over 4
                   13585: 
1.648     raeburn  13586: =item * &chartlink()
1.139     matthew  13587: 
                   13588: Returns a link to the chart for a specific student.  
                   13589: 
                   13590: Inputs:
                   13591: 
                   13592: =over 4
                   13593: 
                   13594: =item $linktext: The text of the link
                   13595: 
                   13596: =item $sname: The students username
                   13597: 
                   13598: =item $sdomain: The students domain
                   13599: 
                   13600: =back
                   13601: 
1.157     matthew  13602: =back
                   13603: 
1.139     matthew  13604: =cut
                   13605: 
                   13606: ############################################################
                   13607: ############################################################
                   13608: sub chartlink {
                   13609:     my ($linktext, $sname, $sdomain) = @_;
                   13610:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13611:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13612:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13613:        '">'.$linktext.'</a>';
1.153     matthew  13614: }
                   13615: 
                   13616: #######################################################
                   13617: #######################################################
                   13618: 
                   13619: =pod
                   13620: 
                   13621: =head1 Course Environment Routines
1.157     matthew  13622: 
                   13623: =over 4
1.153     matthew  13624: 
1.648     raeburn  13625: =item * &restore_course_settings()
1.153     matthew  13626: 
1.648     raeburn  13627: =item * &store_course_settings()
1.153     matthew  13628: 
                   13629: Restores/Store indicated form parameters from the course environment.
                   13630: Will not overwrite existing values of the form parameters.
                   13631: 
                   13632: Inputs: 
                   13633: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13634: 
                   13635: a hash ref describing the data to be stored.  For example:
                   13636:    
                   13637: %Save_Parameters = ('Status' => 'scalar',
                   13638:     'chartoutputmode' => 'scalar',
                   13639:     'chartoutputdata' => 'scalar',
                   13640:     'Section' => 'array',
1.373     raeburn  13641:     'Group' => 'array',
1.153     matthew  13642:     'StudentData' => 'array',
                   13643:     'Maps' => 'array');
                   13644: 
                   13645: Returns: both routines return nothing
                   13646: 
1.631     raeburn  13647: =back
                   13648: 
1.153     matthew  13649: =cut
                   13650: 
                   13651: #######################################################
                   13652: #######################################################
                   13653: sub store_course_settings {
1.496     albertel 13654:     return &store_settings($env{'request.course.id'},@_);
                   13655: }
                   13656: 
                   13657: sub store_settings {
1.153     matthew  13658:     # save to the environment
                   13659:     # appenv the same items, just to be safe
1.300     albertel 13660:     my $udom  = $env{'user.domain'};
                   13661:     my $uname = $env{'user.name'};
1.496     albertel 13662:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13663:     my %SaveHash;
                   13664:     my %AppHash;
                   13665:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13666:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13667:         my $envname = 'environment.'.$basename;
1.258     albertel 13668:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13669:             # Save this value away
                   13670:             if ($type eq 'scalar' &&
1.258     albertel 13671:                 (! exists($env{$envname}) || 
                   13672:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13673:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13674:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13675:             } elsif ($type eq 'array') {
                   13676:                 my $stored_form;
1.258     albertel 13677:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13678:                     $stored_form = join(',',
                   13679:                                         map {
1.369     www      13680:                                             &escape($_);
1.258     albertel 13681:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13682:                 } else {
                   13683:                     $stored_form = 
1.369     www      13684:                         &escape($env{'form.'.$setting});
1.153     matthew  13685:                 }
                   13686:                 # Determine if the array contents are the same.
1.258     albertel 13687:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13688:                     $SaveHash{$basename} = $stored_form;
                   13689:                     $AppHash{$envname}   = $stored_form;
                   13690:                 }
                   13691:             }
                   13692:         }
                   13693:     }
                   13694:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13695:                                           $udom,$uname);
1.153     matthew  13696:     if ($put_result !~ /^(ok|delayed)/) {
                   13697:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13698:                                  'got error:'.$put_result);
                   13699:     }
                   13700:     # Make sure these settings stick around in this session, too
1.646     raeburn  13701:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13702:     return;
                   13703: }
                   13704: 
                   13705: sub restore_course_settings {
1.499     albertel 13706:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13707: }
                   13708: 
                   13709: sub restore_settings {
                   13710:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13711:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13712:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13713:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13714:             '.'.$setting;
1.258     albertel 13715:         if (exists($env{$envname})) {
1.153     matthew  13716:             if ($type eq 'scalar') {
1.258     albertel 13717:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13718:             } elsif ($type eq 'array') {
1.258     albertel 13719:                 $env{'form.'.$setting} = [ 
1.153     matthew  13720:                                            map { 
1.369     www      13721:                                                &unescape($_); 
1.258     albertel 13722:                                            } split(',',$env{$envname})
1.153     matthew  13723:                                            ];
                   13724:             }
                   13725:         }
                   13726:     }
1.127     matthew  13727: }
                   13728: 
1.618     raeburn  13729: #######################################################
                   13730: #######################################################
                   13731: 
                   13732: =pod
                   13733: 
                   13734: =head1 Domain E-mail Routines  
                   13735: 
                   13736: =over 4
                   13737: 
1.648     raeburn  13738: =item * &build_recipient_list()
1.618     raeburn  13739: 
1.1144    raeburn  13740: Build recipient lists for following types of e-mail:
1.766     raeburn  13741: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  13742: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13743: module change checking, student/employee ID conflict checks, as
                   13744: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13745: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13746: 
                   13747: Inputs:
1.619     raeburn  13748: defmail (scalar - email address of default recipient), 
1.1144    raeburn  13749: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13750: requestsmail, updatesmail, or idconflictsmail).
                   13751: 
1.619     raeburn  13752: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  13753: 
1.619     raeburn  13754: origmail (scalar - email address of recipient from loncapa.conf, 
                   13755: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  13756: 
1.655     raeburn  13757: Returns: comma separated list of addresses to which to send e-mail.
                   13758: 
                   13759: =back
1.618     raeburn  13760: 
                   13761: =cut
                   13762: 
                   13763: ############################################################
                   13764: ############################################################
                   13765: sub build_recipient_list {
1.619     raeburn  13766:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13767:     my @recipients;
                   13768:     my $otheremails;
                   13769:     my %domconfig =
                   13770:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13771:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13772:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13773:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13774:                 my @contacts = ('adminemail','supportemail');
                   13775:                 foreach my $item (@contacts) {
                   13776:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13777:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13778:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13779:                             push(@recipients,$addr);
                   13780:                         }
1.619     raeburn  13781:                     }
1.766     raeburn  13782:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13783:                 }
                   13784:             }
1.766     raeburn  13785:         } elsif ($origmail ne '') {
                   13786:             push(@recipients,$origmail);
1.618     raeburn  13787:         }
1.619     raeburn  13788:     } elsif ($origmail ne '') {
                   13789:         push(@recipients,$origmail);
1.618     raeburn  13790:     }
1.688     raeburn  13791:     if (defined($defmail)) {
                   13792:         if ($defmail ne '') {
                   13793:             push(@recipients,$defmail);
                   13794:         }
1.618     raeburn  13795:     }
                   13796:     if ($otheremails) {
1.619     raeburn  13797:         my @others;
                   13798:         if ($otheremails =~ /,/) {
                   13799:             @others = split(/,/,$otheremails);
1.618     raeburn  13800:         } else {
1.619     raeburn  13801:             push(@others,$otheremails);
                   13802:         }
                   13803:         foreach my $addr (@others) {
                   13804:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13805:                 push(@recipients,$addr);
                   13806:             }
1.618     raeburn  13807:         }
                   13808:     }
1.619     raeburn  13809:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13810:     return $recipientlist;
                   13811: }
                   13812: 
1.127     matthew  13813: ############################################################
                   13814: ############################################################
1.154     albertel 13815: 
1.655     raeburn  13816: =pod
                   13817: 
                   13818: =head1 Course Catalog Routines
                   13819: 
                   13820: =over 4
                   13821: 
                   13822: =item * &gather_categories()
                   13823: 
                   13824: Converts category definitions - keys of categories hash stored in  
                   13825: coursecategories in configuration.db on the primary library server in a 
                   13826: domain - to an array.  Also generates javascript and idx hash used to 
                   13827: generate Domain Coordinator interface for editing Course Categories.
                   13828: 
                   13829: Inputs:
1.663     raeburn  13830: 
1.655     raeburn  13831: categories (reference to hash of category definitions).
1.663     raeburn  13832: 
1.655     raeburn  13833: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13834:       categories and subcategories).
1.663     raeburn  13835: 
1.655     raeburn  13836: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13837:       editing Course Categories).
1.663     raeburn  13838: 
1.655     raeburn  13839: jsarray (reference to array of categories used to create Javascript arrays for
                   13840:          Domain Coordinator interface for editing Course Categories).
                   13841: 
                   13842: Returns: nothing
                   13843: 
                   13844: Side effects: populates cats, idx and jsarray. 
                   13845: 
                   13846: =cut
                   13847: 
                   13848: sub gather_categories {
                   13849:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13850:     my %counters;
                   13851:     my $num = 0;
                   13852:     foreach my $item (keys(%{$categories})) {
                   13853:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13854:         if ($container eq '' && $depth == 0) {
                   13855:             $cats->[$depth][$categories->{$item}] = $cat;
                   13856:         } else {
                   13857:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13858:         }
                   13859:         my ($escitem,$tail) = split(/:/,$item,2);
                   13860:         if ($counters{$tail} eq '') {
                   13861:             $counters{$tail} = $num;
                   13862:             $num ++;
                   13863:         }
                   13864:         if (ref($idx) eq 'HASH') {
                   13865:             $idx->{$item} = $counters{$tail};
                   13866:         }
                   13867:         if (ref($jsarray) eq 'ARRAY') {
                   13868:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13869:         }
                   13870:     }
                   13871:     return;
                   13872: }
                   13873: 
                   13874: =pod
                   13875: 
                   13876: =item * &extract_categories()
                   13877: 
                   13878: Used to generate breadcrumb trails for course categories.
                   13879: 
                   13880: Inputs:
1.663     raeburn  13881: 
1.655     raeburn  13882: categories (reference to hash of category definitions).
1.663     raeburn  13883: 
1.655     raeburn  13884: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13885:       categories and subcategories).
1.663     raeburn  13886: 
1.655     raeburn  13887: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13888: 
1.655     raeburn  13889: allitems (reference to hash - key is category key 
                   13890:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13891: 
1.655     raeburn  13892: idx (reference to hash of counters used in Domain Coordinator interface for
                   13893:       editing Course Categories).
1.663     raeburn  13894: 
1.655     raeburn  13895: jsarray (reference to array of categories used to create Javascript arrays for
                   13896:          Domain Coordinator interface for editing Course Categories).
                   13897: 
1.665     raeburn  13898: subcats (reference to hash of arrays containing all subcategories within each 
                   13899:          category, -recursive)
                   13900: 
1.655     raeburn  13901: Returns: nothing
                   13902: 
                   13903: Side effects: populates trails and allitems hash references.
                   13904: 
                   13905: =cut
                   13906: 
                   13907: sub extract_categories {
1.665     raeburn  13908:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13909:     if (ref($categories) eq 'HASH') {
                   13910:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13911:         if (ref($cats->[0]) eq 'ARRAY') {
                   13912:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13913:                 my $name = $cats->[0][$i];
                   13914:                 my $item = &escape($name).'::0';
                   13915:                 my $trailstr;
                   13916:                 if ($name eq 'instcode') {
                   13917:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13918:                 } elsif ($name eq 'communities') {
                   13919:                     $trailstr = &mt('Communities');
1.655     raeburn  13920:                 } else {
                   13921:                     $trailstr = $name;
                   13922:                 }
                   13923:                 if ($allitems->{$item} eq '') {
                   13924:                     push(@{$trails},$trailstr);
                   13925:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13926:                 }
                   13927:                 my @parents = ($name);
                   13928:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13929:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13930:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13931:                         if (ref($subcats) eq 'HASH') {
                   13932:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13933:                         }
                   13934:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13935:                     }
                   13936:                 } else {
                   13937:                     if (ref($subcats) eq 'HASH') {
                   13938:                         $subcats->{$item} = [];
1.655     raeburn  13939:                     }
                   13940:                 }
                   13941:             }
                   13942:         }
                   13943:     }
                   13944:     return;
                   13945: }
                   13946: 
                   13947: =pod
                   13948: 
1.1162    raeburn  13949: =item * &recurse_categories()
1.655     raeburn  13950: 
                   13951: Recursively used to generate breadcrumb trails for course categories.
                   13952: 
                   13953: Inputs:
1.663     raeburn  13954: 
1.655     raeburn  13955: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13956:       categories and subcategories).
1.663     raeburn  13957: 
1.655     raeburn  13958: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13959: 
                   13960: category (current course category, for which breadcrumb trail is being generated).
                   13961: 
                   13962: trails (reference to array of breadcrumb trails for each category).
                   13963: 
1.655     raeburn  13964: allitems (reference to hash - key is category key
                   13965:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13966: 
1.655     raeburn  13967: parents (array containing containers directories for current category, 
                   13968:          back to top level). 
                   13969: 
                   13970: Returns: nothing
                   13971: 
                   13972: Side effects: populates trails and allitems hash references
                   13973: 
                   13974: =cut
                   13975: 
                   13976: sub recurse_categories {
1.665     raeburn  13977:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13978:     my $shallower = $depth - 1;
                   13979:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13980:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13981:             my $name = $cats->[$depth]{$category}[$k];
                   13982:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13983:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13984:             if ($allitems->{$item} eq '') {
                   13985:                 push(@{$trails},$trailstr);
                   13986:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13987:             }
                   13988:             my $deeper = $depth+1;
                   13989:             push(@{$parents},$category);
1.665     raeburn  13990:             if (ref($subcats) eq 'HASH') {
                   13991:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13992:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13993:                     my $higher;
                   13994:                     if ($j > 0) {
                   13995:                         $higher = &escape($parents->[$j]).':'.
                   13996:                                   &escape($parents->[$j-1]).':'.$j;
                   13997:                     } else {
                   13998:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13999:                     }
                   14000:                     push(@{$subcats->{$higher}},$subcat);
                   14001:                 }
                   14002:             }
                   14003:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14004:                                 $subcats);
1.655     raeburn  14005:             pop(@{$parents});
                   14006:         }
                   14007:     } else {
                   14008:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14009:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14010:         if ($allitems->{$item} eq '') {
                   14011:             push(@{$trails},$trailstr);
                   14012:             $allitems->{$item} = scalar(@{$trails})-1;
                   14013:         }
                   14014:     }
                   14015:     return;
                   14016: }
                   14017: 
1.663     raeburn  14018: =pod
                   14019: 
1.1162    raeburn  14020: =item * &assign_categories_table()
1.663     raeburn  14021: 
                   14022: Create a datatable for display of hierarchical categories in a domain,
                   14023: with checkboxes to allow a course to be categorized. 
                   14024: 
                   14025: Inputs:
                   14026: 
                   14027: cathash - reference to hash of categories defined for the domain (from
                   14028:           configuration.db)
                   14029: 
                   14030: currcat - scalar with an & separated list of categories assigned to a course. 
                   14031: 
1.919     raeburn  14032: type    - scalar contains course type (Course or Community).
                   14033: 
1.663     raeburn  14034: Returns: $output (markup to be displayed) 
                   14035: 
                   14036: =cut
                   14037: 
                   14038: sub assign_categories_table {
1.919     raeburn  14039:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14040:     my $output;
                   14041:     if (ref($cathash) eq 'HASH') {
                   14042:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14043:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14044:         $maxdepth = scalar(@cats);
                   14045:         if (@cats > 0) {
                   14046:             my $itemcount = 0;
                   14047:             if (ref($cats[0]) eq 'ARRAY') {
                   14048:                 my @currcategories;
                   14049:                 if ($currcat ne '') {
                   14050:                     @currcategories = split('&',$currcat);
                   14051:                 }
1.919     raeburn  14052:                 my $table;
1.663     raeburn  14053:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14054:                     my $parent = $cats[0][$i];
1.919     raeburn  14055:                     next if ($parent eq 'instcode');
                   14056:                     if ($type eq 'Community') {
                   14057:                         next unless ($parent eq 'communities');
                   14058:                     } else {
                   14059:                         next if ($parent eq 'communities');
                   14060:                     }
1.663     raeburn  14061:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14062:                     my $item = &escape($parent).'::0';
                   14063:                     my $checked = '';
                   14064:                     if (@currcategories > 0) {
                   14065:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14066:                             $checked = ' checked="checked"';
1.663     raeburn  14067:                         }
                   14068:                     }
1.919     raeburn  14069:                     my $parent_title = $parent;
                   14070:                     if ($parent eq 'communities') {
                   14071:                         $parent_title = &mt('Communities');
                   14072:                     }
                   14073:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14074:                               '<input type="checkbox" name="usecategory" value="'.
                   14075:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14076:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14077:                     my $depth = 1;
                   14078:                     push(@path,$parent);
1.919     raeburn  14079:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14080:                     pop(@path);
1.919     raeburn  14081:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14082:                     $itemcount ++;
                   14083:                 }
1.919     raeburn  14084:                 if ($itemcount) {
                   14085:                     $output = &Apache::loncommon::start_data_table().
                   14086:                               $table.
                   14087:                               &Apache::loncommon::end_data_table();
                   14088:                 }
1.663     raeburn  14089:             }
                   14090:         }
                   14091:     }
                   14092:     return $output;
                   14093: }
                   14094: 
                   14095: =pod
                   14096: 
1.1162    raeburn  14097: =item * &assign_category_rows()
1.663     raeburn  14098: 
                   14099: Create a datatable row for display of nested categories in a domain,
                   14100: with checkboxes to allow a course to be categorized,called recursively.
                   14101: 
                   14102: Inputs:
                   14103: 
                   14104: itemcount - track row number for alternating colors
                   14105: 
                   14106: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14107:       categories and subcategories.
                   14108: 
                   14109: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14110: 
                   14111: parent - parent of current category item
                   14112: 
                   14113: path - Array containing all categories back up through the hierarchy from the
                   14114:        current category to the top level.
                   14115: 
                   14116: currcategories - reference to array of current categories assigned to the course
                   14117: 
                   14118: Returns: $output (markup to be displayed).
                   14119: 
                   14120: =cut
                   14121: 
                   14122: sub assign_category_rows {
                   14123:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14124:     my ($text,$name,$item,$chgstr);
                   14125:     if (ref($cats) eq 'ARRAY') {
                   14126:         my $maxdepth = scalar(@{$cats});
                   14127:         if (ref($cats->[$depth]) eq 'HASH') {
                   14128:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14129:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14130:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14131:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14132:                 for (my $j=0; $j<$numchildren; $j++) {
                   14133:                     $name = $cats->[$depth]{$parent}[$j];
                   14134:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14135:                     my $deeper = $depth+1;
                   14136:                     my $checked = '';
                   14137:                     if (ref($currcategories) eq 'ARRAY') {
                   14138:                         if (@{$currcategories} > 0) {
                   14139:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14140:                                 $checked = ' checked="checked"';
1.663     raeburn  14141:                             }
                   14142:                         }
                   14143:                     }
1.664     raeburn  14144:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14145:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14146:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14147:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14148:                              '</td><td>';
1.663     raeburn  14149:                     if (ref($path) eq 'ARRAY') {
                   14150:                         push(@{$path},$name);
                   14151:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14152:                         pop(@{$path});
                   14153:                     }
                   14154:                     $text .= '</td></tr>';
                   14155:                 }
                   14156:                 $text .= '</table></td>';
                   14157:             }
                   14158:         }
                   14159:     }
                   14160:     return $text;
                   14161: }
                   14162: 
1.1181    raeburn  14163: =pod
                   14164: 
                   14165: =back
                   14166: 
                   14167: =cut
                   14168: 
1.655     raeburn  14169: ############################################################
                   14170: ############################################################
                   14171: 
                   14172: 
1.443     albertel 14173: sub commit_customrole {
1.664     raeburn  14174:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14175:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14176:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14177:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14178:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14179:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14180:                  '</b><br />';
                   14181:     return $output;
                   14182: }
                   14183: 
                   14184: sub commit_standardrole {
1.1116    raeburn  14185:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14186:     my ($output,$logmsg,$linefeed);
                   14187:     if ($context eq 'auto') {
                   14188:         $linefeed = "\n";
                   14189:     } else {
                   14190:         $linefeed = "<br />\n";
                   14191:     }  
1.443     albertel 14192:     if ($three eq 'st') {
1.541     raeburn  14193:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14194:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14195:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14196:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14197:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14198:         } else {
1.541     raeburn  14199:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14200:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14201:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14202:             if ($context eq 'auto') {
                   14203:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14204:             } else {
                   14205:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14206:                &mt('Add to classlist').': <b>ok</b>';
                   14207:             }
                   14208:             $output .= $linefeed;
1.443     albertel 14209:         }
                   14210:     } else {
                   14211:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14212:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14213:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14214:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14215:         if ($context eq 'auto') {
                   14216:             $output .= $result.$linefeed;
                   14217:         } else {
                   14218:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14219:         }
1.443     albertel 14220:     }
                   14221:     return $output;
                   14222: }
                   14223: 
                   14224: sub commit_studentrole {
1.1116    raeburn  14225:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14226:         $credits) = @_;
1.626     raeburn  14227:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14228:     if ($context eq 'auto') {
                   14229:         $linefeed = "\n";
                   14230:     } else {
                   14231:         $linefeed = '<br />'."\n";
                   14232:     }
1.443     albertel 14233:     if (defined($one) && defined($two)) {
                   14234:         my $cid=$one.'_'.$two;
                   14235:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14236:         my $secchange = 0;
                   14237:         my $expire_role_result;
                   14238:         my $modify_section_result;
1.628     raeburn  14239:         if ($oldsec ne '-1') { 
                   14240:             if ($oldsec ne $sec) {
1.443     albertel 14241:                 $secchange = 1;
1.628     raeburn  14242:                 my $now = time;
1.443     albertel 14243:                 my $uurl='/'.$cid;
                   14244:                 $uurl=~s/\_/\//g;
                   14245:                 if ($oldsec) {
                   14246:                     $uurl.='/'.$oldsec;
                   14247:                 }
1.626     raeburn  14248:                 $oldsecurl = $uurl;
1.628     raeburn  14249:                 $expire_role_result = 
1.652     raeburn  14250:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14251:                 if ($env{'request.course.sec'} ne '') { 
                   14252:                     if ($expire_role_result eq 'refused') {
                   14253:                         my @roles = ('st');
                   14254:                         my @statuses = ('previous');
                   14255:                         my @roledoms = ($one);
                   14256:                         my $withsec = 1;
                   14257:                         my %roleshash = 
                   14258:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14259:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14260:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14261:                             my ($oldstart,$oldend) = 
                   14262:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14263:                             if ($oldend > 0 && $oldend <= $now) {
                   14264:                                 $expire_role_result = 'ok';
                   14265:                             }
                   14266:                         }
                   14267:                     }
                   14268:                 }
1.443     albertel 14269:                 $result = $expire_role_result;
                   14270:             }
                   14271:         }
                   14272:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14273:             $modify_section_result = 
                   14274:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14275:                                                            undef,undef,undef,$sec,
                   14276:                                                            $end,$start,'','',$cid,
                   14277:                                                            '',$context,$credits);
1.443     albertel 14278:             if ($modify_section_result =~ /^ok/) {
                   14279:                 if ($secchange == 1) {
1.628     raeburn  14280:                     if ($sec eq '') {
                   14281:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14282:                     } else {
                   14283:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14284:                     }
1.443     albertel 14285:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14286:                     if ($sec eq '') {
                   14287:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14288:                     } else {
                   14289:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14290:                     }
1.443     albertel 14291:                 } else {
1.628     raeburn  14292:                     if ($sec eq '') {
                   14293:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14294:                     } else {
                   14295:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14296:                     }
1.443     albertel 14297:                 }
                   14298:             } else {
1.1115    raeburn  14299:                 if ($secchange) { 
1.628     raeburn  14300:                     $$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;
                   14301:                 } else {
                   14302:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14303:                 }
1.443     albertel 14304:             }
                   14305:             $result = $modify_section_result;
                   14306:         } elsif ($secchange == 1) {
1.628     raeburn  14307:             if ($oldsec eq '') {
1.1103    raeburn  14308:                 $$logmsg .= &mt('Error when attempting to expire existing role without a section for [_1] in course [_2] -error: ',$uname,$cid).' '.$expire_role_result.$linefeed;
1.628     raeburn  14309:             } else {
                   14310:                 $$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;
                   14311:             }
1.626     raeburn  14312:             if ($expire_role_result eq 'refused') {
                   14313:                 my $newsecurl = '/'.$cid;
                   14314:                 $newsecurl =~ s/\_/\//g;
                   14315:                 if ($sec ne '') {
                   14316:                     $newsecurl.='/'.$sec;
                   14317:                 }
                   14318:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14319:                     if ($sec eq '') {
                   14320:                         $$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;
                   14321:                     } else {
                   14322:                         $$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;
                   14323:                     }
                   14324:                 }
                   14325:             }
1.443     albertel 14326:         }
                   14327:     } else {
1.626     raeburn  14328:         $$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 14329:         $result = "error: incomplete course id\n";
                   14330:     }
                   14331:     return $result;
                   14332: }
                   14333: 
1.1108    raeburn  14334: sub show_role_extent {
                   14335:     my ($scope,$context,$role) = @_;
                   14336:     $scope =~ s{^/}{};
                   14337:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14338:     push(@courseroles,'co');
                   14339:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14340:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14341:         $scope =~ s{/}{_};
                   14342:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14343:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14344:         my ($audom,$auname) = split(/\//,$scope);
                   14345:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14346:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14347:     } else {
                   14348:         $scope =~ s{/$}{};
                   14349:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14350:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14351:     }
                   14352: }
                   14353: 
1.443     albertel 14354: ############################################################
                   14355: ############################################################
                   14356: 
1.566     albertel 14357: sub check_clone {
1.578     raeburn  14358:     my ($args,$linefeed) = @_;
1.566     albertel 14359:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14360:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14361:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14362:     my $clonemsg;
                   14363:     my $can_clone = 0;
1.944     raeburn  14364:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14365:     if ($lctype ne 'community') {
                   14366:         $lctype = 'course';
                   14367:     }
1.566     albertel 14368:     if ($clonehome eq 'no_host') {
1.944     raeburn  14369:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14370:             $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'});
                   14371:         } else {
                   14372:             $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'});
                   14373:         }     
1.566     albertel 14374:     } else {
                   14375: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14376:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14377:             if ($clonedesc{'type'} ne 'Community') {
                   14378:                  $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'});
                   14379:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14380:             }
                   14381:         }
1.882     raeburn  14382: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14383:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14384: 	    $can_clone = 1;
                   14385: 	} else {
                   14386: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   14387: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   14388: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  14389:             if (grep(/^\*$/,@cloners)) {
                   14390:                 $can_clone = 1;
                   14391:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14392:                 $can_clone = 1;
                   14393:             } else {
1.908     raeburn  14394:                 my $ccrole = 'cc';
1.944     raeburn  14395:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14396:                     $ccrole = 'co';
                   14397:                 }
1.578     raeburn  14398: 	        my %roleshash =
                   14399: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14400: 					 $args->{'ccdomain'},
1.908     raeburn  14401:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  14402: 					 [$args->{'clonedomain'}]);
1.908     raeburn  14403: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  14404:                     $can_clone = 1;
                   14405:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   14406:                     $can_clone = 1;
                   14407:                 } else {
1.944     raeburn  14408:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14409:                         $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'});
                   14410:                     } else {
                   14411:                         $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'});
                   14412:                     }
1.578     raeburn  14413: 	        }
1.566     albertel 14414: 	    }
1.578     raeburn  14415:         }
1.566     albertel 14416:     }
                   14417:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14418: }
                   14419: 
1.444     albertel 14420: sub construct_course {
1.1166    raeburn  14421:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14422:     my $outcome;
1.541     raeburn  14423:     my $linefeed =  '<br />'."\n";
                   14424:     if ($context eq 'auto') {
                   14425:         $linefeed = "\n";
                   14426:     }
1.566     albertel 14427: 
                   14428: #
                   14429: # Are we cloning?
                   14430: #
                   14431:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14432:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14433: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14434: 	if ($context ne 'auto') {
1.578     raeburn  14435:             if ($clonemsg ne '') {
                   14436: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14437:             }
1.566     albertel 14438: 	}
                   14439: 	$outcome .= $clonemsg.$linefeed;
                   14440: 
                   14441:         if (!$can_clone) {
                   14442: 	    return (0,$outcome);
                   14443: 	}
                   14444:     }
                   14445: 
1.444     albertel 14446: #
                   14447: # Open course
                   14448: #
                   14449:     my $crstype = lc($args->{'crstype'});
                   14450:     my %cenv=();
                   14451:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14452:                                              $args->{'cdescr'},
                   14453:                                              $args->{'curl'},
                   14454:                                              $args->{'course_home'},
                   14455:                                              $args->{'nonstandard'},
                   14456:                                              $args->{'crscode'},
                   14457:                                              $args->{'ccuname'}.':'.
                   14458:                                              $args->{'ccdomain'},
1.882     raeburn  14459:                                              $args->{'crstype'},
1.885     raeburn  14460:                                              $cnum,$context,$category);
1.444     albertel 14461: 
                   14462:     # Note: The testing routines depend on this being output; see 
                   14463:     # Utils::Course. This needs to at least be output as a comment
                   14464:     # if anyone ever decides to not show this, and Utils::Course::new
                   14465:     # will need to be suitably modified.
1.541     raeburn  14466:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14467:     if ($$courseid =~ /^error:/) {
                   14468:         return (0,$outcome);
                   14469:     }
                   14470: 
1.444     albertel 14471: #
                   14472: # Check if created correctly
                   14473: #
1.479     albertel 14474:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14475:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14476:     if ($crsuhome eq 'no_host') {
                   14477:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14478:         return (0,$outcome);
                   14479:     }
1.541     raeburn  14480:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14481: 
1.444     albertel 14482: #
1.566     albertel 14483: # Do the cloning
                   14484: #   
                   14485:     if ($can_clone && $cloneid) {
                   14486: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14487: 	if ($context ne 'auto') {
                   14488: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14489: 	}
                   14490: 	$outcome .= $clonemsg.$linefeed;
                   14491: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14492: # Copy all files
1.637     www      14493: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14494: # Restore URL
1.566     albertel 14495: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14496: # Restore title
1.566     albertel 14497: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14498: # Restore creation date, creator and creation context.
                   14499:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14500:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14501:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14502: # Mark as cloned
1.566     albertel 14503: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14504: # Need to clone grading mode
                   14505:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14506:         $cenv{'grading'}=$newenv{'grading'};
                   14507: # Do not clone these environment entries
                   14508:         &Apache::lonnet::del('environment',
                   14509:                   ['default_enrollment_start_date',
                   14510:                    'default_enrollment_end_date',
                   14511:                    'question.email',
                   14512:                    'policy.email',
                   14513:                    'comment.email',
                   14514:                    'pch.users.denied',
1.725     raeburn  14515:                    'plc.users.denied',
                   14516:                    'hidefromcat',
1.1121    raeburn  14517:                    'checkforpriv',
1.1166    raeburn  14518:                    'categories',
                   14519:                    'internal.uniquecode'],
1.638     www      14520:                    $$crsudom,$$crsunum);
1.1170    raeburn  14521:         if ($args->{'textbook'}) {
                   14522:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14523:         }
1.444     albertel 14524:     }
1.566     albertel 14525: 
1.444     albertel 14526: #
                   14527: # Set environment (will override cloned, if existing)
                   14528: #
                   14529:     my @sections = ();
                   14530:     my @xlists = ();
                   14531:     if ($args->{'crstype'}) {
                   14532:         $cenv{'type'}=$args->{'crstype'};
                   14533:     }
                   14534:     if ($args->{'crsid'}) {
                   14535:         $cenv{'courseid'}=$args->{'crsid'};
                   14536:     }
                   14537:     if ($args->{'crscode'}) {
                   14538:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14539:     }
                   14540:     if ($args->{'crsquota'} ne '') {
                   14541:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14542:     } else {
                   14543:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14544:     }
                   14545:     if ($args->{'ccuname'}) {
                   14546:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14547:                                         ':'.$args->{'ccdomain'};
                   14548:     } else {
                   14549:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14550:     }
1.1116    raeburn  14551:     if ($args->{'defaultcredits'}) {
                   14552:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14553:     }
1.444     albertel 14554:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14555:     if ($args->{'crssections'}) {
                   14556:         $cenv{'internal.sectionnums'} = '';
                   14557:         if ($args->{'crssections'} =~ m/,/) {
                   14558:             @sections = split/,/,$args->{'crssections'};
                   14559:         } else {
                   14560:             $sections[0] = $args->{'crssections'};
                   14561:         }
                   14562:         if (@sections > 0) {
                   14563:             foreach my $item (@sections) {
                   14564:                 my ($sec,$gp) = split/:/,$item;
                   14565:                 my $class = $args->{'crscode'}.$sec;
                   14566:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14567:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14568:                 unless ($addcheck eq 'ok') {
                   14569:                     push @badclasses, $class;
                   14570:                 }
                   14571:             }
                   14572:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14573:         }
                   14574:     }
                   14575: # do not hide course coordinator from staff listing, 
                   14576: # even if privileged
                   14577:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14578: # add course coordinator's domain to domains to check for privileged users
                   14579: # if different to course domain
                   14580:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14581:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14582:     }
1.444     albertel 14583: # add crosslistings
                   14584:     if ($args->{'crsxlist'}) {
                   14585:         $cenv{'internal.crosslistings'}='';
                   14586:         if ($args->{'crsxlist'} =~ m/,/) {
                   14587:             @xlists = split/,/,$args->{'crsxlist'};
                   14588:         } else {
                   14589:             $xlists[0] = $args->{'crsxlist'};
                   14590:         }
                   14591:         if (@xlists > 0) {
                   14592:             foreach my $item (@xlists) {
                   14593:                 my ($xl,$gp) = split/:/,$item;
                   14594:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14595:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14596:                 unless ($addcheck eq 'ok') {
                   14597:                     push @badclasses, $xl;
                   14598:                 }
                   14599:             }
                   14600:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14601:         }
                   14602:     }
                   14603:     if ($args->{'autoadds'}) {
                   14604:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14605:     }
                   14606:     if ($args->{'autodrops'}) {
                   14607:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14608:     }
                   14609: # check for notification of enrollment changes
                   14610:     my @notified = ();
                   14611:     if ($args->{'notify_owner'}) {
                   14612:         if ($args->{'ccuname'} ne '') {
                   14613:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14614:         }
                   14615:     }
                   14616:     if ($args->{'notify_dc'}) {
                   14617:         if ($uname ne '') { 
1.630     raeburn  14618:             push(@notified,$uname.':'.$udom);
1.444     albertel 14619:         }
                   14620:     }
                   14621:     if (@notified > 0) {
                   14622:         my $notifylist;
                   14623:         if (@notified > 1) {
                   14624:             $notifylist = join(',',@notified);
                   14625:         } else {
                   14626:             $notifylist = $notified[0];
                   14627:         }
                   14628:         $cenv{'internal.notifylist'} = $notifylist;
                   14629:     }
                   14630:     if (@badclasses > 0) {
                   14631:         my %lt=&Apache::lonlocal::texthash(
                   14632:                 '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',
                   14633:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14634:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14635:         );
1.541     raeburn  14636:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14637:                            ' ('.$lt{'adby'}.')';
                   14638:         if ($context eq 'auto') {
                   14639:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14640:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14641:             foreach my $item (@badclasses) {
                   14642:                 if ($context eq 'auto') {
                   14643:                     $outcome .= " - $item\n";
                   14644:                 } else {
                   14645:                     $outcome .= "<li>$item</li>\n";
                   14646:                 }
                   14647:             }
                   14648:             if ($context eq 'auto') {
                   14649:                 $outcome .= $linefeed;
                   14650:             } else {
1.566     albertel 14651:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14652:             }
                   14653:         } 
1.444     albertel 14654:     }
                   14655:     if ($args->{'no_end_date'}) {
                   14656:         $args->{'endaccess'} = 0;
                   14657:     }
                   14658:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14659:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14660:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14661:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14662:     if ($args->{'showphotos'}) {
                   14663:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14664:     }
                   14665:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14666:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14667:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14668:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14669:             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'); 
                   14670:             if ($context eq 'auto') {
                   14671:                 $outcome .= $krb_msg;
                   14672:             } else {
1.566     albertel 14673:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14674:             }
                   14675:             $outcome .= $linefeed;
1.444     albertel 14676:         }
                   14677:     }
                   14678:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14679:        if ($args->{'setpolicy'}) {
                   14680:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14681:        }
                   14682:        if ($args->{'setcontent'}) {
                   14683:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14684:        }
                   14685:     }
                   14686:     if ($args->{'reshome'}) {
                   14687: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14688: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14689:     }
                   14690: #
                   14691: # course has keyed access
                   14692: #
                   14693:     if ($args->{'setkeys'}) {
                   14694:        $cenv{'keyaccess'}='yes';
                   14695:     }
                   14696: # if specified, key authority is not course, but user
                   14697: # only active if keyaccess is yes
                   14698:     if ($args->{'keyauth'}) {
1.487     albertel 14699: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14700: 	$user = &LONCAPA::clean_username($user);
                   14701: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14702: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14703: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14704: 	}
                   14705:     }
                   14706: 
1.1166    raeburn  14707: #
1.1167    raeburn  14708: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  14709: #
                   14710:     if ($args->{'uniquecode'}) {
                   14711:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14712:         if ($code) {
                   14713:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  14714:             my %crsinfo =
                   14715:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14716:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14717:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14718:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14719:             } 
1.1166    raeburn  14720:             if (ref($coderef)) {
                   14721:                 $$coderef = $code;
                   14722:             }
                   14723:         }
                   14724:     }
                   14725: 
1.444     albertel 14726:     if ($args->{'disresdis'}) {
                   14727:         $cenv{'pch.roles.denied'}='st';
                   14728:     }
                   14729:     if ($args->{'disablechat'}) {
                   14730:         $cenv{'plc.roles.denied'}='st';
                   14731:     }
                   14732: 
                   14733:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14734:     # course
                   14735:     $cenv{'course.helper.not.run'} = 1;
                   14736:     #
                   14737:     # Use new Randomseed
                   14738:     #
                   14739:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14740:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14741:     #
                   14742:     # The encryption code and receipt prefix for this course
                   14743:     #
                   14744:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14745:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14746:     #
                   14747:     # By default, use standard grading
                   14748:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14749: 
1.541     raeburn  14750:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14751:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14752: #
                   14753: # Open all assignments
                   14754: #
                   14755:     if ($args->{'openall'}) {
                   14756:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14757:        my %storecontent = ($storeunder         => time,
                   14758:                            $storeunder.'.type' => 'date_start');
                   14759:        
                   14760:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14761:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14762:    }
                   14763: #
                   14764: # Set first page
                   14765: #
                   14766:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14767: 	    || ($cloneid)) {
1.445     albertel 14768: 	use LONCAPA::map;
1.444     albertel 14769: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14770: 
                   14771: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14772:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14773: 
1.444     albertel 14774:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14775:         my $title; my $url;
                   14776:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14777: 	    $title=&mt('Syllabus');
1.444     albertel 14778:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14779:         } else {
1.963     raeburn  14780:             $title=&mt('Table of Contents');
1.444     albertel 14781:             $url='/adm/navmaps';
                   14782:         }
1.445     albertel 14783: 
                   14784:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14785: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14786: 
                   14787: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14788:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14789:     }
1.566     albertel 14790: 
                   14791:     return (1,$outcome);
1.444     albertel 14792: }
                   14793: 
1.1166    raeburn  14794: sub make_unique_code {
                   14795:     my ($cdom,$cnum) = @_;
                   14796:     # get lock on uniquecodes db
                   14797:     my $lockhash = {
                   14798:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14799:                                                   ':'.$env{'user.domain'},
                   14800:                    };
                   14801:     my $tries = 0;
                   14802:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14803:     my ($code,$error);
                   14804:   
                   14805:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14806:         $tries ++;
                   14807:         sleep 1;
                   14808:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14809:     }
                   14810:     if ($gotlock eq 'ok') {
                   14811:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14812:         my $gotcode;
                   14813:         my $attempts = 0;
                   14814:         while ((!$gotcode) && ($attempts < 100)) {
                   14815:             $code = &generate_code();
                   14816:             if (!exists($currcodes{$code})) {
                   14817:                 $gotcode = 1;
                   14818:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14819:                     $error = 'nostore';
                   14820:                 }
                   14821:             }
                   14822:             $attempts ++;
                   14823:         }
                   14824:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14825:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14826:     } else {
                   14827:         $error = 'nolock';
                   14828:     }
                   14829:     return ($code,$error);
                   14830: }
                   14831: 
                   14832: sub generate_code {
                   14833:     my $code;
                   14834:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14835:     for (my $i=0; $i<6; $i++) {
                   14836:         my $lettnum = int (rand 2);
                   14837:         my $item = '';
                   14838:         if ($lettnum) {
                   14839:             $item = $letts[int( rand(18) )];
                   14840:         } else {
                   14841:             $item = 1+int( rand(8) );
                   14842:         }
                   14843:         $code .= $item;
                   14844:     }
                   14845:     return $code;
                   14846: }
                   14847: 
1.444     albertel 14848: ############################################################
                   14849: ############################################################
                   14850: 
1.953     droeschl 14851: #SD
                   14852: # only Community and Course, or anything else?
1.378     raeburn  14853: sub course_type {
                   14854:     my ($cid) = @_;
                   14855:     if (!defined($cid)) {
                   14856:         $cid = $env{'request.course.id'};
                   14857:     }
1.404     albertel 14858:     if (defined($env{'course.'.$cid.'.type'})) {
                   14859:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14860:     } else {
                   14861:         return 'Course';
1.377     raeburn  14862:     }
                   14863: }
1.156     albertel 14864: 
1.406     raeburn  14865: sub group_term {
                   14866:     my $crstype = &course_type();
                   14867:     my %names = (
                   14868:                   'Course' => 'group',
1.865     raeburn  14869:                   'Community' => 'group',
1.406     raeburn  14870:                 );
                   14871:     return $names{$crstype};
                   14872: }
                   14873: 
1.902     raeburn  14874: sub course_types {
1.1165    raeburn  14875:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14876:     my %typename = (
                   14877:                          official   => 'Official course',
                   14878:                          unofficial => 'Unofficial course',
                   14879:                          community  => 'Community',
1.1165    raeburn  14880:                          textbook   => 'Textbook course',
1.902     raeburn  14881:                    );
                   14882:     return (\@types,\%typename);
                   14883: }
                   14884: 
1.156     albertel 14885: sub icon {
                   14886:     my ($file)=@_;
1.505     albertel 14887:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14888:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14889:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14890:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14891: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14892: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14893: 	            $curfext.".gif") {
                   14894: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14895: 		$curfext.".gif";
                   14896: 	}
                   14897:     }
1.249     albertel 14898:     return &lonhttpdurl($iconname);
1.154     albertel 14899: } 
1.84      albertel 14900: 
1.575     albertel 14901: sub lonhttpdurl {
1.692     www      14902: #
                   14903: # Had been used for "small fry" static images on separate port 8080.
                   14904: # Modify here if lightweight http functionality desired again.
                   14905: # Currently eliminated due to increasing firewall issues.
                   14906: #
1.575     albertel 14907:     my ($url)=@_;
1.692     www      14908:     return $url;
1.215     albertel 14909: }
                   14910: 
1.213     albertel 14911: sub connection_aborted {
                   14912:     my ($r)=@_;
                   14913:     $r->print(" ");$r->rflush();
                   14914:     my $c = $r->connection;
                   14915:     return $c->aborted();
                   14916: }
                   14917: 
1.221     foxr     14918: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14919: #    strings as 'strings'.
                   14920: sub escape_single {
1.221     foxr     14921:     my ($input) = @_;
1.223     albertel 14922:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14923:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14924:     return $input;
                   14925: }
1.223     albertel 14926: 
1.222     foxr     14927: #  Same as escape_single, but escape's "'s  This 
                   14928: #  can be used for  "strings"
                   14929: sub escape_double {
                   14930:     my ($input) = @_;
                   14931:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14932:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14933:     return $input;
                   14934: }
1.223     albertel 14935:  
1.222     foxr     14936: #   Escapes the last element of a full URL.
                   14937: sub escape_url {
                   14938:     my ($url)   = @_;
1.238     raeburn  14939:     my @urlslices = split(/\//, $url,-1);
1.369     www      14940:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  14941:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14942: }
1.462     albertel 14943: 
1.820     raeburn  14944: sub compare_arrays {
                   14945:     my ($arrayref1,$arrayref2) = @_;
                   14946:     my (@difference,%count);
                   14947:     @difference = ();
                   14948:     %count = ();
                   14949:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14950:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14951:         foreach my $element (keys(%count)) {
                   14952:             if ($count{$element} == 1) {
                   14953:                 push(@difference,$element);
                   14954:             }
                   14955:         }
                   14956:     }
                   14957:     return @difference;
                   14958: }
                   14959: 
1.817     bisitz   14960: # -------------------------------------------------------- Initialize user login
1.462     albertel 14961: sub init_user_environment {
1.463     albertel 14962:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14963:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14964: 
                   14965:     my $public=($username eq 'public' && $domain eq 'public');
                   14966: 
                   14967: # See if old ID present, if so, remove
                   14968: 
1.1062    raeburn  14969:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14970:     my $now=time;
                   14971: 
                   14972:     if ($public) {
                   14973: 	my $max_public=100;
                   14974: 	my $oldest;
                   14975: 	my $oldest_time=0;
                   14976: 	for(my $next=1;$next<=$max_public;$next++) {
                   14977: 	    if (-e $lonids."/publicuser_$next.id") {
                   14978: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14979: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14980: 		    $oldest_time=$mtime;
                   14981: 		    $oldest=$next;
                   14982: 		}
                   14983: 	    } else {
                   14984: 		$cookie="publicuser_$next";
                   14985: 		last;
                   14986: 	    }
                   14987: 	}
                   14988: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14989:     } else {
1.463     albertel 14990: 	# if this isn't a robot, kill any existing non-robot sessions
                   14991: 	if (!$args->{'robot'}) {
                   14992: 	    opendir(DIR,$lonids);
                   14993: 	    while ($filename=readdir(DIR)) {
                   14994: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14995: 		    unlink($lonids.'/'.$filename);
                   14996: 		}
1.462     albertel 14997: 	    }
1.463     albertel 14998: 	    closedir(DIR);
1.1204    raeburn  14999: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15000:             my $namespace = 'nohist_courseeditor';
                   15001:             my $lockingkey = 'paste'."\0".'locked_num';
                   15002:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15003:                                                 $domain,$username);
                   15004:             if (exists($lockhash{$lockingkey})) {
                   15005:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15006:                 unless ($delresult eq 'ok') {
                   15007:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15008:                 }
                   15009:             }
1.462     albertel 15010: 	}
                   15011: # Give them a new cookie
1.463     albertel 15012: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15013: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15014: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15015:     
                   15016: # Initialize roles
                   15017: 
1.1062    raeburn  15018: 	($userroles,$firstaccenv,$timerintenv) = 
                   15019:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15020:     }
                   15021: # ------------------------------------ Check browser type and MathML capability
                   15022: 
1.1194    raeburn  15023:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15024:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15025: 
                   15026: # ------------------------------------------------------------- Get environment
                   15027: 
                   15028:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15029:     my ($tmp) = keys(%userenv);
                   15030:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15031:     } else {
                   15032: 	undef(%userenv);
                   15033:     }
                   15034:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15035: 	$form->{'interface'}=$userenv{'interface'};
                   15036:     }
                   15037:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15038: 
                   15039: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15040:     foreach my $option ('interface','localpath','localres') {
                   15041:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15042:     }
                   15043: # --------------------------------------------------------- Write first profile
                   15044: 
                   15045:     {
                   15046: 	my %initial_env = 
                   15047: 	    ("user.name"          => $username,
                   15048: 	     "user.domain"        => $domain,
                   15049: 	     "user.home"          => $authhost,
                   15050: 	     "browser.type"       => $clientbrowser,
                   15051: 	     "browser.version"    => $clientversion,
                   15052: 	     "browser.mathml"     => $clientmathml,
                   15053: 	     "browser.unicode"    => $clientunicode,
                   15054: 	     "browser.os"         => $clientos,
1.1137    raeburn  15055:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15056:              "browser.info"       => $clientinfo,
1.1194    raeburn  15057:              "browser.osversion"  => $clientosversion,
1.462     albertel 15058: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15059: 	     "request.course.fn"  => '',
                   15060: 	     "request.course.uri" => '',
                   15061: 	     "request.course.sec" => '',
                   15062: 	     "request.role"       => 'cm',
                   15063: 	     "request.role.adv"   => $env{'user.adv'},
                   15064: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15065: 
                   15066:         if ($form->{'localpath'}) {
                   15067: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15068: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15069:         }
                   15070: 	
                   15071: 	if ($form->{'interface'}) {
                   15072: 	    $form->{'interface'}=~s/\W//gs;
                   15073: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15074: 	    $env{'browser.interface'}=$form->{'interface'};
                   15075: 	}
                   15076: 
1.1157    raeburn  15077:         if ($form->{'iptoken'}) {
                   15078:             my $lonhost = $r->dir_config('lonHostID');
                   15079:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15080:             $env{'user.noloadbalance'} = $lonhost;
                   15081:         }
                   15082: 
1.981     raeburn  15083:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15084:         my %domdef;
                   15085:         unless ($domain eq 'public') {
                   15086:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15087:         }
1.980     raeburn  15088: 
1.1081    raeburn  15089:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15090:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15091:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15092:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15093:         }
                   15094: 
1.1165    raeburn  15095:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15096:             $userenv{'canrequest.'.$crstype} =
                   15097:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15098:                                                   'reload','requestcourses',
                   15099:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15100:         }
                   15101: 
1.1092    raeburn  15102:         $userenv{'canrequest.author'} =
                   15103:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15104:                                         'reload','requestauthor',
                   15105:                                         \%userenv,\%domdef,\%is_adv);
                   15106:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15107:                                              $domain,$username);
                   15108:         my $reqstatus = $reqauthor{'author_status'};
                   15109:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15110:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15111:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15112:                                                   $reqauthor{'author'}{'timestamp'};
                   15113:             }
                   15114:         }
                   15115: 
1.462     albertel 15116: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15117: 
1.462     albertel 15118: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15119: 		 &GDBM_WRCREAT(),0640)) {
                   15120: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15121: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15122: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15123:             if (ref($firstaccenv) eq 'HASH') {
                   15124:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15125:             }
                   15126:             if (ref($timerintenv) eq 'HASH') {
                   15127:                 &_add_to_env(\%disk_env,$timerintenv);
                   15128:             }
1.463     albertel 15129: 	    if (ref($args->{'extra_env'})) {
                   15130: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15131: 	    }
1.462     albertel 15132: 	    untie(%disk_env);
                   15133: 	} else {
1.705     tempelho 15134: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15135: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15136: 	    return 'error: '.$!;
                   15137: 	}
                   15138:     }
                   15139:     $env{'request.role'}='cm';
                   15140:     $env{'request.role.adv'}=$env{'user.adv'};
                   15141:     $env{'browser.type'}=$clientbrowser;
                   15142: 
                   15143:     return $cookie;
                   15144: 
                   15145: }
                   15146: 
                   15147: sub _add_to_env {
                   15148:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15149:     if (ref($env_data) eq 'HASH') {
                   15150:         while (my ($key,$value) = each(%$env_data)) {
                   15151: 	    $idf->{$prefix.$key} = $value;
                   15152: 	    $env{$prefix.$key}   = $value;
                   15153:         }
1.462     albertel 15154:     }
                   15155: }
                   15156: 
1.685     tempelho 15157: # --- Get the symbolic name of a problem and the url
                   15158: sub get_symb {
                   15159:     my ($request,$silent) = @_;
1.726     raeburn  15160:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15161:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15162:     if ($symb eq '') {
                   15163:         if (!$silent) {
1.1071    raeburn  15164:             if (ref($request)) { 
                   15165:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15166:             }
1.685     tempelho 15167:             return ();
                   15168:         }
                   15169:     }
                   15170:     &Apache::lonenc::check_decrypt(\$symb);
                   15171:     return ($symb);
                   15172: }
                   15173: 
                   15174: # --------------------------------------------------------------Get annotation
                   15175: 
                   15176: sub get_annotation {
                   15177:     my ($symb,$enc) = @_;
                   15178: 
                   15179:     my $key = $symb;
                   15180:     if (!$enc) {
                   15181:         $key =
                   15182:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15183:     }
                   15184:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15185:     return $annotation{$key};
                   15186: }
                   15187: 
                   15188: sub clean_symb {
1.731     raeburn  15189:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15190: 
                   15191:     &Apache::lonenc::check_decrypt(\$symb);
                   15192:     my $enc = $env{'request.enc'};
1.731     raeburn  15193:     if ($delete_enc) {
1.730     raeburn  15194:         delete($env{'request.enc'});
                   15195:     }
1.685     tempelho 15196: 
                   15197:     return ($symb,$enc);
                   15198: }
1.462     albertel 15199: 
1.1181    raeburn  15200: ############################################################
                   15201: ############################################################
                   15202: 
                   15203: =pod
                   15204: 
                   15205: =head1 Routines for building display used to search for courses
                   15206: 
                   15207: 
                   15208: =over 4
                   15209: 
                   15210: =item * &build_filters()
                   15211: 
                   15212: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15213: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15214: and quotacheck.pl
                   15215: 
1.1181    raeburn  15216: 
                   15217: Inputs:
                   15218: 
                   15219: filterlist - anonymous array of fields to include as potential filters 
                   15220: 
                   15221: crstype - course type
                   15222: 
                   15223: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15224:               to pop-open a course selector (will contain "extra element"). 
                   15225: 
                   15226: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15227: 
                   15228: filter - anonymous hash of criteria and their values
                   15229: 
                   15230: action - form action
                   15231: 
                   15232: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15233: 
1.1182    raeburn  15234: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15235: 
                   15236: cloneruname - username of owner of new course who wants to clone
                   15237: 
                   15238: clonerudom - domain of owner of new course who wants to clone
                   15239: 
                   15240: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15241: 
                   15242: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15243: 
                   15244: codedom - domain
                   15245: 
                   15246: formname - value of form element named "form". 
                   15247: 
                   15248: fixeddom - domain, if fixed.
                   15249: 
                   15250: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15251: 
                   15252: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15253: 
                   15254: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15255: 
                   15256: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15257: 
                   15258: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15259: 
                   15260: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15261: 
                   15262: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15263: 
1.1182    raeburn  15264: 
1.1181    raeburn  15265: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15266: 
1.1182    raeburn  15267: 
1.1181    raeburn  15268: Side Effects: None
                   15269: 
                   15270: =cut
                   15271: 
                   15272: # ---------------------------------------------- search for courses based on last activity etc.
                   15273: 
                   15274: sub build_filters {
                   15275:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15276:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15277:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15278:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15279:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15280:     my ($list,$jscript);
1.1181    raeburn  15281:     my $onchange = 'javascript:updateFilters(this)';
                   15282:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15283:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15284:         $typeselectform,$instcodetitle);
                   15285:     if ($formname eq '') {
                   15286:         $formname = $caller;
                   15287:     }
                   15288:     foreach my $item (@{$filterlist}) {
                   15289:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15290:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15291:             if ($item eq 'domainfilter') {
                   15292:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15293:             } elsif ($item eq 'coursefilter') {
                   15294:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15295:             } elsif ($item eq 'ownerfilter') {
                   15296:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15297:             } elsif ($item eq 'ownerdomfilter') {
                   15298:                 $filter->{'ownerdomfilter'} =
                   15299:                     &LONCAPA::clean_domain($filter->{$item});
                   15300:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15301:                                                        'ownerdomfilter',1);
                   15302:             } elsif ($item eq 'personfilter') {
                   15303:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15304:             } elsif ($item eq 'persondomfilter') {
                   15305:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15306:                                                         'persondomfilter',1);
                   15307:             } else {
                   15308:                 $filter->{$item} =~ s/\W//g;
                   15309:             }
                   15310:             if (!$filter->{$item}) {
                   15311:                 $filter->{$item} = '';
                   15312:             }
                   15313:         }
                   15314:         if ($item eq 'domainfilter') {
                   15315:             my $allow_blank = 1;
                   15316:             if ($formname eq 'portform') {
                   15317:                 $allow_blank=0;
                   15318:             } elsif ($formname eq 'studentform') {
                   15319:                 $allow_blank=0;
                   15320:             }
                   15321:             if ($fixeddom) {
                   15322:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15323:                                     ' value="'.$codedom.'" />'.
                   15324:                                     &Apache::lonnet::domain($codedom,'description');
                   15325:             } else {
                   15326:                 $domainselectform = &select_dom_form($filter->{$item},
                   15327:                                                      'domainfilter',
                   15328:                                                       $allow_blank,'',$onchange);
                   15329:             }
                   15330:         } else {
                   15331:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15332:         }
                   15333:     }
                   15334: 
                   15335:     # last course activity filter and selection
                   15336:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15337: 
                   15338:     # course created filter and selection
                   15339:     if (exists($filter->{'createdfilter'})) {
                   15340:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15341:     }
                   15342: 
                   15343:     my %lt = &Apache::lonlocal::texthash(
                   15344:                 'cac' => "$crstype Activity",
                   15345:                 'ccr' => "$crstype Created",
                   15346:                 'cde' => "$crstype Title",
                   15347:                 'cdo' => "$crstype Domain",
                   15348:                 'ins' => 'Institutional Code',
                   15349:                 'inc' => 'Institutional Categorization',
                   15350:                 'cow' => "$crstype Owner/Co-owner",
                   15351:                 'cop' => "$crstype Personnel Includes",
                   15352:                 'cog' => 'Type',
                   15353:              );
                   15354: 
                   15355:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15356:         my $typeval = 'Course';
                   15357:         if ($crstype eq 'Community') {
                   15358:             $typeval = 'Community';
                   15359:         }
                   15360:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15361:     } else {
                   15362:         $typeselectform =  '<select name="type" size="1"';
                   15363:         if ($onchange) {
                   15364:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15365:         }
                   15366:         $typeselectform .= '>'."\n";
                   15367:         foreach my $posstype ('Course','Community') {
                   15368:             $typeselectform.='<option value="'.$posstype.'"'.
                   15369:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15370:         }
                   15371:         $typeselectform.="</select>";
                   15372:     }
                   15373: 
                   15374:     my ($cloneableonlyform,$cloneabletitle);
                   15375:     if (exists($filter->{'cloneableonly'})) {
                   15376:         my $cloneableon = '';
                   15377:         my $cloneableoff = ' checked="checked"';
                   15378:         if ($filter->{'cloneableonly'}) {
                   15379:             $cloneableon = $cloneableoff;
                   15380:             $cloneableoff = '';
                   15381:         }
                   15382:         $cloneableonlyform = '<span class="LC_nobreak"><label><input type="radio" name="cloneableonly" value="1" '.$cloneableon.'/>&nbsp;'.&mt('Required').'</label>'.('&nbsp;'x3).'<label><input type="radio" name="cloneableonly" value="" '.$cloneableoff.' />&nbsp;'.&mt('No restriction').'</label></span>';
                   15383:         if ($formname eq 'ccrs') {
1.1187    bisitz   15384:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15385:         } else {
                   15386:             $cloneabletitle = &mt('Cloneable by you');
                   15387:         }
                   15388:     }
                   15389:     my $officialjs;
                   15390:     if ($crstype eq 'Course') {
                   15391:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15392: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15393: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15394:             if ($codedom) { 
1.1181    raeburn  15395:                 $officialjs = 1;
                   15396:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15397:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15398:                                                                   $officialjs,$codetitlesref);
                   15399:                 if ($jscript) {
1.1182    raeburn  15400:                     $jscript = '<script type="text/javascript">'."\n".
                   15401:                                '// <![CDATA['."\n".
                   15402:                                $jscript."\n".
                   15403:                                '// ]]>'."\n".
                   15404:                                '</script>'."\n";
1.1181    raeburn  15405:                 }
                   15406:             }
                   15407:             if ($instcodeform eq '') {
                   15408:                 $instcodeform =
                   15409:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15410:                     $list->{'instcodefilter'}.'" />';
                   15411:                 $instcodetitle = $lt{'ins'};
                   15412:             } else {
                   15413:                 $instcodetitle = $lt{'inc'};
                   15414:             }
                   15415:             if ($fixeddom) {
                   15416:                 $instcodetitle .= '<br />('.$codedom.')';
                   15417:             }
                   15418:         }
                   15419:     }
                   15420:     my $output = qq|
                   15421: <form method="post" name="filterpicker" action="$action">
                   15422: <input type="hidden" name="form" value="$formname" />
                   15423: |;
                   15424:     if ($formname eq 'modifycourse') {
                   15425:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15426:                    '<input type="hidden" name="prevphase" value="'.
                   15427:                    $prevphase.'" />'."\n";
1.1198    musolffc 15428:     } elsif ($formname eq 'quotacheck') {
                   15429:         $output .= qq|
                   15430: <input type="hidden" name="sortby" value="" />
                   15431: <input type="hidden" name="sortorder" value="" />
                   15432: |;
                   15433:     } else {
1.1181    raeburn  15434:         my $name_input;
                   15435:         if ($cnameelement ne '') {
                   15436:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15437:                           $cnameelement.'" />';
                   15438:         }
                   15439:         $output .= qq|
1.1182    raeburn  15440: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15441: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15442: $name_input
                   15443: $roleelement
                   15444: $multelement
                   15445: $typeelement
                   15446: |;
                   15447:         if ($formname eq 'portform') {
                   15448:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15449:         }
                   15450:     }
                   15451:     if ($fixeddom) {
                   15452:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15453:     }
                   15454:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15455:     if ($sincefilterform) {
                   15456:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15457:                   .$sincefilterform
                   15458:                   .&Apache::lonhtmlcommon::row_closure();
                   15459:     }
                   15460:     if ($createdfilterform) {
                   15461:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15462:                   .$createdfilterform
                   15463:                   .&Apache::lonhtmlcommon::row_closure();
                   15464:     }
                   15465:     if ($domainselectform) {
                   15466:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15467:                   .$domainselectform
                   15468:                   .&Apache::lonhtmlcommon::row_closure();
                   15469:     }
                   15470:     if ($typeselectform) {
                   15471:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15472:             $output .= $typeselectform;
                   15473:         } else {
                   15474:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15475:                       .$typeselectform
                   15476:                       .&Apache::lonhtmlcommon::row_closure();
                   15477:         }
                   15478:     }
                   15479:     if ($instcodeform) {
                   15480:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15481:                   .$instcodeform
                   15482:                   .&Apache::lonhtmlcommon::row_closure();
                   15483:     }
                   15484:     if (exists($filter->{'ownerfilter'})) {
                   15485:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15486:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15487:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15488:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15489:                    $ownerdomselectform.'</td></tr></table>'.
                   15490:                    &Apache::lonhtmlcommon::row_closure();
                   15491:     }
                   15492:     if (exists($filter->{'personfilter'})) {
                   15493:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15494:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15495:                    '<input type="text" name="personfilter" size="20" value="'.
                   15496:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15497:                    $persondomselectform.'</td></tr></table>'.
                   15498:                    &Apache::lonhtmlcommon::row_closure();
                   15499:     }
                   15500:     if (exists($filter->{'coursefilter'})) {
                   15501:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15502:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15503:                   .$list->{'coursefilter'}.'" />'
                   15504:                   .&Apache::lonhtmlcommon::row_closure();
                   15505:     }
                   15506:     if ($cloneableonlyform) {
                   15507:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15508:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15509:     }
                   15510:     if (exists($filter->{'descriptfilter'})) {
                   15511:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15512:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15513:                   .$list->{'descriptfilter'}.'" />'
                   15514:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15515:     }
                   15516:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15517:                '<input type="hidden" name="updater" value="" />'."\n".
                   15518:                '<input type="submit" name="gosearch" value="'.
                   15519:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15520:     return $jscript.$clonewarning.$output;
                   15521: }
                   15522: 
                   15523: =pod 
                   15524: 
                   15525: =item * &timebased_select_form()
                   15526: 
1.1182    raeburn  15527: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15528: filter e.g., Course Activity, Course Created, when searching for courses
                   15529: or communities
                   15530: 
                   15531: Inputs:
                   15532: 
                   15533: item - name of form element (sincefilter or createdfilter)
                   15534: 
                   15535: filter - anonymous hash of criteria and their values
                   15536: 
                   15537: Returns: HTML for a select box contained a blank, then six time selections,
                   15538:          with value set in incoming form variables currently selected. 
                   15539: 
                   15540: Side Effects: None
                   15541: 
                   15542: =cut
                   15543: 
                   15544: sub timebased_select_form {
                   15545:     my ($item,$filter) = @_;
                   15546:     if (ref($filter) eq 'HASH') {
                   15547:         $filter->{$item} =~ s/[^\d-]//g;
                   15548:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15549:         return &select_form(
                   15550:                             $filter->{$item},
                   15551:                             $item,
                   15552:                             {      '-1' => '',
                   15553:                                 '86400' => &mt('today'),
                   15554:                                '604800' => &mt('last week'),
                   15555:                               '2592000' => &mt('last month'),
                   15556:                               '7776000' => &mt('last three months'),
                   15557:                              '15552000' => &mt('last six months'),
                   15558:                              '31104000' => &mt('last year'),
                   15559:                     'select_form_order' =>
                   15560:                            ['-1','86400','604800','2592000','7776000',
                   15561:                             '15552000','31104000']});
                   15562:     }
                   15563: }
                   15564: 
                   15565: =pod
                   15566: 
                   15567: =item * &js_changer()
                   15568: 
                   15569: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  15570: when course type or domain is changed, and also to hide 'Searching ...' on
                   15571: page load completion for page showing search result.
1.1181    raeburn  15572: 
                   15573: Inputs: None
                   15574: 
1.1183    raeburn  15575: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  15576: 
                   15577: Side Effects: None
                   15578: 
                   15579: =cut
                   15580: 
                   15581: sub js_changer {
                   15582:     return <<ENDJS;
                   15583: <script type="text/javascript">
                   15584: // <![CDATA[
                   15585: function updateFilters(caller) {
                   15586:     if (typeof(caller) != "undefined") {
                   15587:         document.filterpicker.updater.value = caller.name;
                   15588:     }
                   15589:     document.filterpicker.submit();
                   15590: }
1.1183    raeburn  15591: 
                   15592: function hideSearching() {
                   15593:     if (document.getElementById('searching')) {
                   15594:         document.getElementById('searching').style.display = 'none';
                   15595:     }
                   15596:     return;
                   15597: }
                   15598: 
1.1181    raeburn  15599: // ]]>
                   15600: </script>
                   15601: 
                   15602: ENDJS
                   15603: }
                   15604: 
                   15605: =pod
                   15606: 
1.1182    raeburn  15607: =item * &search_courses()
                   15608: 
                   15609: Process selected filters form course search form and pass to lonnet::courseiddump
                   15610: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15611: 
                   15612: Inputs:
                   15613: 
                   15614: dom - domain being searched 
                   15615: 
                   15616: type - course type ('Course' or 'Community' or '.' if any).
                   15617: 
                   15618: filter - anonymous hash of criteria and their values
                   15619: 
                   15620: numtitles - for institutional codes - number of categories
                   15621: 
                   15622: cloneruname - optional username of new course owner
                   15623: 
                   15624: clonerudom - optional domain of new course owner
                   15625: 
                   15626: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
                   15627:             (used when DC is using course creation form)
                   15628: 
                   15629: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15630: 
                   15631: 
                   15632: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15633: 
                   15634: 
                   15635: Side Effects: None
                   15636: 
                   15637: =cut
                   15638: 
                   15639: 
                   15640: sub search_courses {
                   15641:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
                   15642:     my (%courses,%showcourses,$cloner);
                   15643:     if (($filter->{'ownerfilter'} ne '') ||
                   15644:         ($filter->{'ownerdomfilter'} ne '')) {
                   15645:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15646:                                        $filter->{'ownerdomfilter'};
                   15647:     }
                   15648:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15649:         if (!$filter->{$item}) {
                   15650:             $filter->{$item}='.';
                   15651:         }
                   15652:     }
                   15653:     my $now = time;
                   15654:     my $timefilter =
                   15655:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15656:     my ($createdbefore,$createdafter);
                   15657:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15658:         $createdbefore = $now;
                   15659:         $createdafter = $now-$filter->{'createdfilter'};
                   15660:     }
                   15661:     my ($instcodefilter,$regexpok);
                   15662:     if ($numtitles) {
                   15663:         if ($env{'form.official'} eq 'on') {
                   15664:             $instcodefilter =
                   15665:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15666:             $regexpok = 1;
                   15667:         } elsif ($env{'form.official'} eq 'off') {
                   15668:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15669:             unless ($instcodefilter eq '') {
                   15670:                 $regexpok = -1;
                   15671:             }
                   15672:         }
                   15673:     } else {
                   15674:         $instcodefilter = $filter->{'instcodefilter'};
                   15675:     }
                   15676:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15677:     if ($type eq '') { $type = '.'; }
                   15678: 
                   15679:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15680:         $cloner = $cloneruname.':'.$clonerudom;
                   15681:     }
                   15682:     %courses = &Apache::lonnet::courseiddump($dom,
                   15683:                                              $filter->{'descriptfilter'},
                   15684:                                              $timefilter,
                   15685:                                              $instcodefilter,
                   15686:                                              $filter->{'combownerfilter'},
                   15687:                                              $filter->{'coursefilter'},
                   15688:                                              undef,undef,$type,$regexpok,undef,undef,
                   15689:                                              undef,undef,$cloner,$env{'form.cc_clone'},
                   15690:                                              $filter->{'cloneableonly'},
                   15691:                                              $createdbefore,$createdafter,undef,
                   15692:                                              $domcloner);
                   15693:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15694:         my $ccrole;
                   15695:         if ($type eq 'Community') {
                   15696:             $ccrole = 'co';
                   15697:         } else {
                   15698:             $ccrole = 'cc';
                   15699:         }
                   15700:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15701:                                                      $filter->{'persondomfilter'},
                   15702:                                                      'userroles',undef,
                   15703:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15704:                                                      $dom);
                   15705:         foreach my $role (keys(%rolehash)) {
                   15706:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15707:             my $cid = $cdom.'_'.$cnum;
                   15708:             if (exists($courses{$cid})) {
                   15709:                 if (ref($courses{$cid}) eq 'HASH') {
                   15710:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15711:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15712:                             push (@{$courses{$cid}{roles}},$courserole);
                   15713:                         }
                   15714:                     } else {
                   15715:                         $courses{$cid}{roles} = [$courserole];
                   15716:                     }
                   15717:                     $showcourses{$cid} = $courses{$cid};
                   15718:                 }
                   15719:             }
                   15720:         }
                   15721:         %courses = %showcourses;
                   15722:     }
                   15723:     return %courses;
                   15724: }
                   15725: 
                   15726: =pod
                   15727: 
1.1181    raeburn  15728: =back
                   15729: 
1.1207    raeburn  15730: =head1 Routines for version requirements for current course.
                   15731: 
                   15732: =over 4
                   15733: 
                   15734: =item * &check_release_required()
                   15735: 
                   15736: Compares required LON-CAPA version with version on server, and
                   15737: if required version is newer looks for a server with the required version.
                   15738: 
                   15739: Looks first at servers in user's owen domain; if none suitable, looks at
                   15740: servers in course's domain are permitted to host sessions for user's domain.
                   15741: 
                   15742: Inputs:
                   15743: 
                   15744: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15745: 
                   15746: $courseid - Course ID of current course
                   15747: 
                   15748: $rolecode - User's current role in course (for switchserver query string).
                   15749: 
                   15750: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15751: 
                   15752: 
                   15753: Returns:
                   15754: 
                   15755: $switchserver - query string tp append to /adm/switchserver call (if 
                   15756:                 current server's LON-CAPA version is too old. 
                   15757: 
                   15758: $warning - Message is displayed if no suitable server could be found.
                   15759: 
                   15760: =cut
                   15761: 
                   15762: sub check_release_required {
                   15763:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15764:     my ($switchserver,$warning);
                   15765:     if ($required ne '') {
                   15766:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15767:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15768:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15769:             my $otherserver;
                   15770:             if (($major eq '' && $minor eq '') ||
                   15771:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15772:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15773:                 my $switchlcrev =
                   15774:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15775:                                                            $userdomserver);
                   15776:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15777:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15778:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15779:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15780:                     if ($cdom ne $env{'user.domain'}) {
                   15781:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15782:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15783:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15784:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15785:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15786:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15787:                         my $canhost =
                   15788:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15789:                                                               $coursedomserver,
                   15790:                                                               $remoterev,
                   15791:                                                               $udomdefaults{'remotesessions'},
                   15792:                                                               $defdomdefaults{'hostedsessions'});
                   15793: 
                   15794:                         if ($canhost) {
                   15795:                             $otherserver = $coursedomserver;
                   15796:                         } else {
                   15797:                             $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'. &mt("No suitable server could be found amongst servers in either your own domain or in the course's domain.");
                   15798:                         }
                   15799:                     } else {
                   15800:                         $warning = &mt('Requires LON-CAPA version [_1].',$env{'course.'.$courseid.'.internal.releaserequired'}).'<br />'.&mt("No suitable server could be found amongst servers in your own domain (which is also the course's domain).");
                   15801:                     }
                   15802:                 } else {
                   15803:                     $otherserver = $userdomserver;
                   15804:                 }
                   15805:             }
                   15806:             if ($otherserver ne '') {
                   15807:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   15808:             }
                   15809:         }
                   15810:     }
                   15811:     return ($switchserver,$warning);
                   15812: }
                   15813: 
                   15814: =pod
                   15815: 
                   15816: =item * &check_release_result()
                   15817: 
                   15818: Inputs:
                   15819: 
                   15820: $switchwarning - Warning message if no suitable server found to host session.
                   15821: 
                   15822: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15823:                 and current role.
                   15824: 
                   15825: Returns: HTML to display with information about requirement to switch server.
                   15826:          Either displaying warning with link to Roles/Courses screen or
                   15827:          display link to switchserver.
                   15828: 
1.1181    raeburn  15829: =cut
                   15830: 
1.1207    raeburn  15831: sub check_release_result {
                   15832:     my ($switchwarning,$switchserver) = @_;
                   15833:     my $output = &start_page('Selected course unavailable on this server').
                   15834:                  '<p class="LC_warning">';
                   15835:     if ($switchwarning) {
                   15836:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   15837:         if (&show_course()) {
                   15838:             $output .= &mt('Display courses');
                   15839:         } else {
                   15840:             $output .= &mt('Display roles');
                   15841:         }
                   15842:         $output .= '</a>';
                   15843:     } elsif ($switchserver) {
                   15844:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   15845:                    '<br />'.
                   15846:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   15847:                    &mt('Switch Server').
                   15848:                    '</a>';
                   15849:     }
                   15850:     $output .= '</p>'.&end_page();
                   15851:     return $output;
                   15852: }
                   15853: 
                   15854: =pod
                   15855: 
                   15856: =item * &needs_coursereinit()
                   15857: 
                   15858: Determine if course contents stored for user's session needs to be
                   15859: refreshed, because content has changed since "Big Hash" last tied.
                   15860: 
                   15861: Check for change is made if time last checked is more than 10 minutes ago
                   15862: (by default).
                   15863: 
                   15864: Inputs:
                   15865: 
                   15866: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15867: 
                   15868: $interval (optional) - Time which may elapse (in s) between last check for content
                   15869:                        change in current course. (default: 600 s).  
                   15870: 
                   15871: Returns: an array; first element is:
                   15872: 
                   15873: =over 4
                   15874: 
                   15875: 'switch' - if content updates mean user's session
                   15876:            needs to be switched to a server running a newer LON-CAPA version
                   15877:  
                   15878: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   15879:            on current server hosting user's session                
                   15880: 
                   15881: ''       - if no action required.
                   15882: 
                   15883: =back
                   15884: 
                   15885: If first item element is 'switch':
                   15886: 
                   15887: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   15888: 
                   15889: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15890:                               and current role. 
                   15891: 
                   15892: otherwise: no other elements returned.
                   15893: 
                   15894: =back
                   15895: 
                   15896: =cut
                   15897: 
                   15898: sub needs_coursereinit {
                   15899:     my ($loncaparev,$interval) = @_;
                   15900:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   15901:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   15902:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   15903:     my $now = time;
                   15904:     if ($interval eq '') {
                   15905:         $interval = 600;
                   15906:     }
                   15907:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   15908:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15909:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   15910:         if ($lastchange > $env{'request.course.tied'}) {
                   15911:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15912:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   15913:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   15914:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   15915:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   15916:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   15917:                     my ($switchserver,$switchwarning) =
                   15918:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   15919:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   15920:                     if ($switchwarning ne '' || $switchserver ne '') {
                   15921:                         return ('switch',$switchwarning,$switchserver);
                   15922:                     }
                   15923:                 }
                   15924:             }
                   15925:             return ('update');
                   15926:         }
                   15927:     }
                   15928:     return ();
                   15929: }
1.1181    raeburn  15930: 
1.1083    raeburn  15931: sub update_content_constraints {
                   15932:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15933:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15934:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15935:     my %checkresponsetypes;
                   15936:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15937:         my ($item,$name,$value) = split(/:/,$key);
                   15938:         if ($item eq 'resourcetag') {
                   15939:             if ($name eq 'responsetype') {
                   15940:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15941:             }
                   15942:         }
                   15943:     }
                   15944:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15945:     if (defined($navmap)) {
                   15946:         my %allresponses;
                   15947:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15948:             my %responses = $res->responseTypes();
                   15949:             foreach my $key (keys(%responses)) {
                   15950:                 next unless(exists($checkresponsetypes{$key}));
                   15951:                 $allresponses{$key} += $responses{$key};
                   15952:             }
                   15953:         }
                   15954:         foreach my $key (keys(%allresponses)) {
                   15955:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15956:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15957:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15958:             }
                   15959:         }
                   15960:         undef($navmap);
                   15961:     }
                   15962:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15963:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15964:     }
                   15965:     return;
                   15966: }
                   15967: 
1.1110    raeburn  15968: sub allmaps_incourse {
                   15969:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15970:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15971:         $cid = $env{'request.course.id'};
                   15972:         $cdom = $env{'course.'.$cid.'.domain'};
                   15973:         $cnum = $env{'course.'.$cid.'.num'};
                   15974:         $chome = $env{'course.'.$cid.'.home'};
                   15975:     }
                   15976:     my %allmaps = ();
                   15977:     my $lastchange =
                   15978:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15979:     if ($lastchange > $env{'request.course.tied'}) {
                   15980:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15981:         unless ($ferr) {
                   15982:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15983:         }
                   15984:     }
                   15985:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15986:     if (defined($navmap)) {
                   15987:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15988:             $allmaps{$res->src()} = 1;
                   15989:         }
                   15990:     }
                   15991:     return \%allmaps;
                   15992: }
                   15993: 
1.1083    raeburn  15994: sub parse_supplemental_title {
                   15995:     my ($title) = @_;
                   15996: 
                   15997:     my ($foldertitle,$renametitle);
                   15998:     if ($title =~ /&amp;&amp;&amp;/) {
                   15999:         $title = &HTML::Entites::decode($title);
                   16000:     }
                   16001:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16002:         $renametitle=$4;
                   16003:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16004:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16005:         my $name =  &plainname($uname,$udom);
                   16006:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16007:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16008:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16009:             $name.': <br />'.$foldertitle;
                   16010:     }
                   16011:     if (wantarray) {
                   16012:         return ($title,$foldertitle,$renametitle);
                   16013:     }
                   16014:     return $title;
                   16015: }
                   16016: 
1.1143    raeburn  16017: sub recurse_supplemental {
                   16018:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16019:     if ($suppmap) {
                   16020:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16021:         if ($fatal) {
                   16022:             $errors ++;
                   16023:         } else {
                   16024:             if ($#LONCAPA::map::resources > 0) {
                   16025:                 foreach my $res (@LONCAPA::map::resources) {
                   16026:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16027:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16028:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16029:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16030:                         } else {
                   16031:                             $numfiles ++;
                   16032:                         }
                   16033:                     }
                   16034:                 }
                   16035:             }
                   16036:         }
                   16037:     }
                   16038:     return ($numfiles,$errors);
                   16039: }
                   16040: 
1.1101    raeburn  16041: sub symb_to_docspath {
                   16042:     my ($symb) = @_;
                   16043:     return unless ($symb);
                   16044:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16045:     if ($resurl=~/\.(sequence|page)$/) {
                   16046:         $mapurl=$resurl;
                   16047:     } elsif ($resurl eq 'adm/navmaps') {
                   16048:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16049:     }
                   16050:     my $mapresobj;
                   16051:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16052:     if (ref($navmap)) {
                   16053:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16054:     }
                   16055:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16056:     my $type=$2;
                   16057:     my $path;
                   16058:     if (ref($mapresobj)) {
                   16059:         my $pcslist = $mapresobj->map_hierarchy();
                   16060:         if ($pcslist ne '') {
                   16061:             foreach my $pc (split(/,/,$pcslist)) {
                   16062:                 next if ($pc <= 1);
                   16063:                 my $res = $navmap->getByMapPc($pc);
                   16064:                 if (ref($res)) {
                   16065:                     my $thisurl = $res->src();
                   16066:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16067:                     my $thistitle = $res->title();
                   16068:                     $path .= '&'.
                   16069:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16070:                              &escape($thistitle).
1.1101    raeburn  16071:                              ':'.$res->randompick().
                   16072:                              ':'.$res->randomout().
                   16073:                              ':'.$res->encrypted().
                   16074:                              ':'.$res->randomorder().
                   16075:                              ':'.$res->is_page();
                   16076:                 }
                   16077:             }
                   16078:         }
                   16079:         $path =~ s/^\&//;
                   16080:         my $maptitle = $mapresobj->title();
                   16081:         if ($mapurl eq 'default') {
1.1129    raeburn  16082:             $maptitle = 'Main Content';
1.1101    raeburn  16083:         }
                   16084:         $path .= (($path ne '')? '&' : '').
                   16085:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16086:                  &escape($maptitle).
1.1101    raeburn  16087:                  ':'.$mapresobj->randompick().
                   16088:                  ':'.$mapresobj->randomout().
                   16089:                  ':'.$mapresobj->encrypted().
                   16090:                  ':'.$mapresobj->randomorder().
                   16091:                  ':'.$mapresobj->is_page();
                   16092:     } else {
                   16093:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16094:         my $ispage = (($type eq 'page')? 1 : '');
                   16095:         if ($mapurl eq 'default') {
1.1129    raeburn  16096:             $maptitle = 'Main Content';
1.1101    raeburn  16097:         }
                   16098:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16099:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16100:     }
                   16101:     unless ($mapurl eq 'default') {
                   16102:         $path = 'default&'.
1.1146    raeburn  16103:                 &escape('Main Content').
1.1101    raeburn  16104:                 ':::::&'.$path;
                   16105:     }
                   16106:     return $path;
                   16107: }
                   16108: 
1.1094    raeburn  16109: sub captcha_display {
                   16110:     my ($context,$lonhost) = @_;
                   16111:     my ($output,$error);
                   16112:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16113:     if ($captcha eq 'original') {
1.1094    raeburn  16114:         $output = &create_captcha();
                   16115:         unless ($output) {
1.1172    raeburn  16116:             $error = 'captcha';
1.1094    raeburn  16117:         }
                   16118:     } elsif ($captcha eq 'recaptcha') {
                   16119:         $output = &create_recaptcha($pubkey);
                   16120:         unless ($output) {
1.1172    raeburn  16121:             $error = 'recaptcha';
1.1094    raeburn  16122:         }
                   16123:     }
1.1176    raeburn  16124:     return ($output,$error,$captcha);
1.1094    raeburn  16125: }
                   16126: 
                   16127: sub captcha_response {
                   16128:     my ($context,$lonhost) = @_;
                   16129:     my ($captcha_chk,$captcha_error);
                   16130:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16131:     if ($captcha eq 'original') {
1.1094    raeburn  16132:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16133:     } elsif ($captcha eq 'recaptcha') {
                   16134:         $captcha_chk = &check_recaptcha($privkey);
                   16135:     } else {
                   16136:         $captcha_chk = 1;
                   16137:     }
                   16138:     return ($captcha_chk,$captcha_error);
                   16139: }
                   16140: 
                   16141: sub get_captcha_config {
                   16142:     my ($context,$lonhost) = @_;
1.1095    raeburn  16143:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  16144:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16145:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16146:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  16147:     if ($context eq 'usercreation') {
                   16148:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16149:         if (ref($domconfig{$context}) eq 'HASH') {
                   16150:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16151:             if (ref($hashtocheck) eq 'HASH') {
                   16152:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16153:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16154:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16155:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16156:                     }
                   16157:                     if ($privkey && $pubkey) {
                   16158:                         $captcha = 'recaptcha';
                   16159:                     } else {
                   16160:                         $captcha = 'original';
                   16161:                     }
                   16162:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16163:                     $captcha = 'original';
                   16164:                 }
1.1094    raeburn  16165:             }
1.1095    raeburn  16166:         } else {
                   16167:             $captcha = 'captcha';
                   16168:         }
                   16169:     } elsif ($context eq 'login') {
                   16170:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16171:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16172:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16173:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  16174:             if ($privkey && $pubkey) {
                   16175:                 $captcha = 'recaptcha';
1.1095    raeburn  16176:             } else {
                   16177:                 $captcha = 'original';
1.1094    raeburn  16178:             }
1.1095    raeburn  16179:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16180:             $captcha = 'original';
1.1094    raeburn  16181:         }
                   16182:     }
                   16183:     return ($captcha,$pubkey,$privkey);
                   16184: }
                   16185: 
                   16186: sub create_captcha {
                   16187:     my %captcha_params = &captcha_settings();
                   16188:     my ($output,$maxtries,$tries) = ('',10,0);
                   16189:     while ($tries < $maxtries) {
                   16190:         $tries ++;
                   16191:         my $captcha = Authen::Captcha->new (
                   16192:                                            output_folder => $captcha_params{'output_dir'},
                   16193:                                            data_folder   => $captcha_params{'db_dir'},
                   16194:                                           );
                   16195:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16196: 
                   16197:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16198:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16199:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  16200:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16201:                       '<br />'.
                   16202:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  16203:             last;
                   16204:         }
                   16205:     }
                   16206:     return $output;
                   16207: }
                   16208: 
                   16209: sub captcha_settings {
                   16210:     my %captcha_params = (
                   16211:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16212:                            www_output_dir => "/captchaspool",
                   16213:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16214:                            numchars       => '5',
                   16215:                          );
                   16216:     return %captcha_params;
                   16217: }
                   16218: 
                   16219: sub check_captcha {
                   16220:     my ($captcha_chk,$captcha_error);
                   16221:     my $code = $env{'form.code'};
                   16222:     my $md5sum = $env{'form.crypt'};
                   16223:     my %captcha_params = &captcha_settings();
                   16224:     my $captcha = Authen::Captcha->new(
                   16225:                       output_folder => $captcha_params{'output_dir'},
                   16226:                       data_folder   => $captcha_params{'db_dir'},
                   16227:                   );
1.1109    raeburn  16228:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  16229:     my %captcha_hash = (
                   16230:                         0       => 'Code not checked (file error)',
                   16231:                        -1      => 'Failed: code expired',
                   16232:                        -2      => 'Failed: invalid code (not in database)',
                   16233:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16234:     );
                   16235:     if ($captcha_chk != 1) {
                   16236:         $captcha_error = $captcha_hash{$captcha_chk}
                   16237:     }
                   16238:     return ($captcha_chk,$captcha_error);
                   16239: }
                   16240: 
                   16241: sub create_recaptcha {
                   16242:     my ($pubkey) = @_;
1.1153    raeburn  16243:     my $use_ssl;
                   16244:     if ($ENV{'SERVER_PORT'} == 443) {
                   16245:         $use_ssl = 1;
                   16246:     }
1.1094    raeburn  16247:     my $captcha = Captcha::reCAPTCHA->new;
                   16248:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  16249:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1213    raeburn  16250:            &mt('If the text is hard to read, [_1] will replace them.',
1.1133    raeburn  16251:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  16252:            '<br /><br />';
                   16253: }
                   16254: 
                   16255: sub check_recaptcha {
                   16256:     my ($privkey) = @_;
                   16257:     my $captcha_chk;
                   16258:     my $captcha = Captcha::reCAPTCHA->new;
                   16259:     my $captcha_result =
                   16260:         $captcha->check_answer(
                   16261:                                 $privkey,
                   16262:                                 $ENV{'REMOTE_ADDR'},
                   16263:                                 $env{'form.recaptcha_challenge_field'},
                   16264:                                 $env{'form.recaptcha_response_field'},
                   16265:                               );
                   16266:     if ($captcha_result->{is_valid}) {
                   16267:         $captcha_chk = 1;
                   16268:     }
                   16269:     return $captcha_chk;
                   16270: }
                   16271: 
1.1174    raeburn  16272: sub emailusername_info {
1.1177    raeburn  16273:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  16274:     my %titles = &Apache::lonlocal::texthash (
                   16275:                      lastname      => 'Last Name',
                   16276:                      firstname     => 'First Name',
                   16277:                      institution   => 'School/college/university',
                   16278:                      location      => "School's city, state/province, country",
                   16279:                      web           => "School's web address",
                   16280:                      officialemail => 'E-mail address at institution (if different)',
                   16281:                  );
                   16282:     return (\@fields,\%titles);
                   16283: }
                   16284: 
1.1161    raeburn  16285: sub cleanup_html {
                   16286:     my ($incoming) = @_;
                   16287:     my $outgoing;
                   16288:     if ($incoming ne '') {
                   16289:         $outgoing = $incoming;
                   16290:         $outgoing =~ s/;/&#059;/g;
                   16291:         $outgoing =~ s/\#/&#035;/g;
                   16292:         $outgoing =~ s/\&/&#038;/g;
                   16293:         $outgoing =~ s/</&#060;/g;
                   16294:         $outgoing =~ s/>/&#062;/g;
                   16295:         $outgoing =~ s/\(/&#040/g;
                   16296:         $outgoing =~ s/\)/&#041;/g;
                   16297:         $outgoing =~ s/"/&#034;/g;
                   16298:         $outgoing =~ s/'/&#039;/g;
                   16299:         $outgoing =~ s/\$/&#036;/g;
                   16300:         $outgoing =~ s{/}{&#047;}g;
                   16301:         $outgoing =~ s/=/&#061;/g;
                   16302:         $outgoing =~ s/\\/&#092;/g
                   16303:     }
                   16304:     return $outgoing;
                   16305: }
                   16306: 
1.1190    musolffc 16307: # Checks for critical messages and returns a redirect url if one exists.
                   16308: # $interval indicates how often to check for messages.
                   16309: sub critical_redirect {
                   16310:     my ($interval) = @_;
                   16311:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16312:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16313:                                         $env{'user.name'});
                   16314:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16315:         my $redirecturl;
1.1190    musolffc 16316:         if ($what[0]) {
                   16317: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16318: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16319: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16320:                 return (1, $url);
1.1190    musolffc 16321:             }
1.1191    raeburn  16322:         }
                   16323:     } 
                   16324:     return ();
1.1190    musolffc 16325: }
                   16326: 
1.1174    raeburn  16327: # Use:
                   16328: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16329: #
                   16330: ##################################################
                   16331: #          password associated functions         #
                   16332: ##################################################
                   16333: sub des_keys {
                   16334:     # Make a new key for DES encryption.
                   16335:     # Each key has two parts which are returned separately.
                   16336:     # Please note:  Each key must be passed through the &hex function
                   16337:     # before it is output to the web browser.  The hex versions cannot
                   16338:     # be used to decrypt.
                   16339:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16340:                 '8','9','a','b','c','d','e','f');
                   16341:     my $lkey='';
                   16342:     for (0..7) {
                   16343:         $lkey.=$hexstr[rand(15)];
                   16344:     }
                   16345:     my $ukey='';
                   16346:     for (0..7) {
                   16347:         $ukey.=$hexstr[rand(15)];
                   16348:     }
                   16349:     return ($lkey,$ukey);
                   16350: }
                   16351: 
                   16352: sub des_decrypt {
                   16353:     my ($key,$cyphertext) = @_;
                   16354:     my $keybin=pack("H16",$key);
                   16355:     my $cypher;
                   16356:     if ($Crypt::DES::VERSION>=2.03) {
                   16357:         $cypher=new Crypt::DES $keybin;
                   16358:     } else {
                   16359:         $cypher=new DES $keybin;
                   16360:     }
                   16361:     my $plaintext=
                   16362:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16363:     $plaintext.=
                   16364:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16365:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16366:     return $plaintext;
                   16367: }
                   16368: 
1.112     bowersj2 16369: 1;
                   16370: __END__;
1.41      ng       16371: 

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