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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1218  ! droeschl    4: # $Id: loncommon.pm,v 1.1217 2015/04/13 18:52:44 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.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.1205    golterma 6817:   z-index: 100;
1.600     albertel 6818: }
1.795     www      6819: 
1.600     albertel 6820: div.LC_edit_problem_header_title {
1.705     tempelho 6821:   font-weight: bold;
                   6822:   font-size: larger;
1.602     albertel 6823:   background: $tabbg;
                   6824:   padding: 3px;
1.1060    bisitz   6825:   margin: 0 0 5px 0;
1.602     albertel 6826: }
1.795     www      6827: 
1.602     albertel 6828: table.LC_edit_problem_header_title {
                   6829:   width: 100%;
1.600     albertel 6830:   background: $tabbg;
1.602     albertel 6831: }
                   6832: 
1.1205    golterma 6833: div.LC_edit_actionbar {
                   6834:     background-color: $sidebg;
1.1218  ! droeschl 6835:     margin: 0;
        !          6836:     padding: 0;
        !          6837:     line-height: 200%;
1.602     albertel 6838: }
1.795     www      6839: 
1.1218  ! droeschl 6840: div.LC_edit_actionbar div{
        !          6841:     padding: 0;
        !          6842:     margin: 0;
        !          6843:     display: inline-block;
1.600     albertel 6844: }
1.795     www      6845: 
1.1124    bisitz   6846: .LC_edit_opt {
                   6847:   padding-left: 1em;
                   6848:   white-space: nowrap;
                   6849: }
                   6850: 
1.1152    golterma 6851: .LC_edit_problem_latexhelper{
                   6852:     text-align: right;
                   6853: }
                   6854: 
                   6855: #LC_edit_problem_colorful div{
                   6856:     margin-left: 40px;
                   6857: }
                   6858: 
1.1205    golterma 6859: #LC_edit_problem_codemirror div{
                   6860:     margin-left: 0px;
                   6861: }
                   6862: 
1.911     bisitz   6863: img.stift {
1.803     bisitz   6864:   border-width: 0;
                   6865:   vertical-align: middle;
1.677     riegler  6866: }
1.680     riegler  6867: 
1.923     bisitz   6868: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6869:   vertical-align: top;
1.777     tempelho 6870: }
1.795     www      6871: 
1.716     raeburn  6872: div.LC_createcourse {
1.911     bisitz   6873:   margin: 10px 10px 10px 10px;
1.716     raeburn  6874: }
                   6875: 
1.917     raeburn  6876: .LC_dccid {
1.1130    raeburn  6877:   float: right;
1.917     raeburn  6878:   margin: 0.2em 0 0 0;
                   6879:   padding: 0;
                   6880:   font-size: 90%;
                   6881:   display:none;
                   6882: }
                   6883: 
1.897     wenzelju 6884: ol.LC_primary_menu a:hover,
1.721     harmsja  6885: ol#LC_MenuBreadcrumbs a:hover,
                   6886: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6887: ul#LC_secondary_menu a:hover,
1.721     harmsja  6888: .LC_FormSectionClearButton input:hover
1.795     www      6889: ul.LC_TabContent   li:hover a {
1.952     onken    6890:   color:$button_hover;
1.911     bisitz   6891:   text-decoration:none;
1.693     droeschl 6892: }
                   6893: 
1.779     bisitz   6894: h1 {
1.911     bisitz   6895:   padding: 0;
                   6896:   line-height:130%;
1.693     droeschl 6897: }
1.698     harmsja  6898: 
1.911     bisitz   6899: h2,
                   6900: h3,
                   6901: h4,
                   6902: h5,
                   6903: h6 {
                   6904:   margin: 5px 0 5px 0;
                   6905:   padding: 0;
                   6906:   line-height:130%;
1.693     droeschl 6907: }
1.795     www      6908: 
                   6909: .LC_hcell {
1.911     bisitz   6910:   padding:3px 15px 3px 15px;
                   6911:   margin: 0;
                   6912:   background-color:$tabbg;
                   6913:   color:$fontmenu;
                   6914:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6915: }
1.795     www      6916: 
1.840     bisitz   6917: .LC_Box > .LC_hcell {
1.911     bisitz   6918:   margin: 0 -10px 10px -10px;
1.835     bisitz   6919: }
                   6920: 
1.721     harmsja  6921: .LC_noBorder {
1.911     bisitz   6922:   border: 0;
1.698     harmsja  6923: }
1.693     droeschl 6924: 
1.721     harmsja  6925: .LC_FormSectionClearButton input {
1.911     bisitz   6926:   background-color:transparent;
                   6927:   border: none;
                   6928:   cursor:pointer;
                   6929:   text-decoration:underline;
1.693     droeschl 6930: }
1.763     bisitz   6931: 
                   6932: .LC_help_open_topic {
1.911     bisitz   6933:   color: #FFFFFF;
                   6934:   background-color: #EEEEFF;
                   6935:   margin: 1px;
                   6936:   padding: 4px;
                   6937:   border: 1px solid #000033;
                   6938:   white-space: nowrap;
                   6939:   /* vertical-align: middle; */
1.759     neumanie 6940: }
1.693     droeschl 6941: 
1.911     bisitz   6942: dl,
                   6943: ul,
                   6944: div,
                   6945: fieldset {
                   6946:   margin: 10px 10px 10px 0;
                   6947:   /* overflow: hidden; */
1.693     droeschl 6948: }
1.795     www      6949: 
1.1211    raeburn  6950: article.geogebraweb div {
                   6951:     margin: 0;
                   6952: }
                   6953: 
1.838     bisitz   6954: fieldset > legend {
1.911     bisitz   6955:   font-weight: bold;
                   6956:   padding: 0 5px 0 5px;
1.838     bisitz   6957: }
                   6958: 
1.813     bisitz   6959: #LC_nav_bar {
1.911     bisitz   6960:   float: left;
1.995     raeburn  6961:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6962:   margin: 0 0 2px 0;
1.807     droeschl 6963: }
                   6964: 
1.916     droeschl 6965: #LC_realm {
                   6966:   margin: 0.2em 0 0 0;
                   6967:   padding: 0;
                   6968:   font-weight: bold;
                   6969:   text-align: center;
1.995     raeburn  6970:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6971: }
                   6972: 
1.911     bisitz   6973: #LC_nav_bar em {
                   6974:   font-weight: bold;
                   6975:   font-style: normal;
1.807     droeschl 6976: }
                   6977: 
1.897     wenzelju 6978: ol.LC_primary_menu {
1.934     droeschl 6979:   margin: 0;
1.1076    raeburn  6980:   padding: 0;
1.807     droeschl 6981: }
                   6982: 
1.852     droeschl 6983: ol#LC_PathBreadcrumbs {
1.911     bisitz   6984:   margin: 0;
1.693     droeschl 6985: }
                   6986: 
1.897     wenzelju 6987: ol.LC_primary_menu li {
1.1076    raeburn  6988:   color: RGB(80, 80, 80);
                   6989:   vertical-align: middle;
                   6990:   text-align: left;
                   6991:   list-style: none;
1.1205    golterma 6992:   position: relative;
1.1076    raeburn  6993:   float: left;
1.1205    golterma 6994:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   6995:   line-height: 1.5em;
1.1076    raeburn  6996: }
                   6997: 
1.1205    golterma 6998: ol.LC_primary_menu li a,
                   6999: ol.LC_primary_menu li p {
1.1076    raeburn  7000:   display: block;
                   7001:   margin: 0;
                   7002:   padding: 0 5px 0 10px;
                   7003:   text-decoration: none;
                   7004: }
                   7005: 
1.1205    golterma 7006: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7007:   display: inline-block;
                   7008:   width: 95%;
                   7009:   text-align: left;
                   7010: }
                   7011: 
                   7012: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7013:   display: inline-block;	
                   7014:   width: 5%;
                   7015:   float: right;
                   7016:   text-align: right;
                   7017:   font-size: 70%;
                   7018: }
                   7019: 
                   7020: ol.LC_primary_menu ul {
1.1076    raeburn  7021:   display: none;
1.1205    golterma 7022:   width: 15em;
1.1076    raeburn  7023:   background-color: $data_table_light;
1.1205    golterma 7024:   position: absolute;
                   7025:   top: 100%;
1.1076    raeburn  7026: }
                   7027: 
1.1205    golterma 7028: ol.LC_primary_menu ul ul {
                   7029:   left: 100%;
                   7030:   top: 0;
                   7031: }
                   7032: 
                   7033: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1076    raeburn  7034:   display: block;
                   7035:   position: absolute;
                   7036:   margin: 0;
                   7037:   padding: 0;
1.1078    raeburn  7038:   z-index: 2;
1.1076    raeburn  7039: }
                   7040: 
                   7041: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1205    golterma 7042: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1076    raeburn  7043:   font-size: 90%;
1.911     bisitz   7044:   vertical-align: top;
1.1076    raeburn  7045:   float: none;
1.1079    raeburn  7046:   border-left: 1px solid black;
                   7047:   border-right: 1px solid black;
1.1205    golterma 7048: /* A dark bottom border to visualize different menu options; 
                   7049: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7050:   border-bottom: 1px solid $data_table_dark; 
1.1076    raeburn  7051: }
                   7052: 
1.1205    golterma 7053: ol.LC_primary_menu li li p:hover {
                   7054:   color:$button_hover;
                   7055:   text-decoration:none;
                   7056:   background-color:$data_table_dark;
1.1076    raeburn  7057: }
                   7058: 
                   7059: ol.LC_primary_menu li li a:hover {
                   7060:    color:$button_hover;
                   7061:    background-color:$data_table_dark;
1.693     droeschl 7062: }
                   7063: 
1.1205    golterma 7064: /* Font-size equal to the size of the predecessors*/
                   7065: ol.LC_primary_menu li:hover li li {
                   7066:   font-size: 100%;
                   7067: }
                   7068: 
1.897     wenzelju 7069: ol.LC_primary_menu li img {
1.911     bisitz   7070:   vertical-align: bottom;
1.934     droeschl 7071:   height: 1.1em;
1.1077    raeburn  7072:   margin: 0.2em 0 0 0;
1.693     droeschl 7073: }
                   7074: 
1.897     wenzelju 7075: ol.LC_primary_menu a {
1.911     bisitz   7076:   color: RGB(80, 80, 80);
                   7077:   text-decoration: none;
1.693     droeschl 7078: }
1.795     www      7079: 
1.949     droeschl 7080: ol.LC_primary_menu a.LC_new_message {
                   7081:   font-weight:bold;
                   7082:   color: darkred;
                   7083: }
                   7084: 
1.975     raeburn  7085: ol.LC_docs_parameters {
                   7086:   margin-left: 0;
                   7087:   padding: 0;
                   7088:   list-style: none;
                   7089: }
                   7090: 
                   7091: ol.LC_docs_parameters li {
                   7092:   margin: 0;
                   7093:   padding-right: 20px;
                   7094:   display: inline;
                   7095: }
                   7096: 
1.976     raeburn  7097: ol.LC_docs_parameters li:before {
                   7098:   content: "\\002022 \\0020";
                   7099: }
                   7100: 
                   7101: li.LC_docs_parameters_title {
                   7102:   font-weight: bold;
                   7103: }
                   7104: 
                   7105: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7106:   content: "";
                   7107: }
                   7108: 
1.897     wenzelju 7109: ul#LC_secondary_menu {
1.1107    raeburn  7110:   clear: right;
1.911     bisitz   7111:   color: $fontmenu;
                   7112:   background: $tabbg;
                   7113:   list-style: none;
                   7114:   padding: 0;
                   7115:   margin: 0;
                   7116:   width: 100%;
1.995     raeburn  7117:   text-align: left;
1.1107    raeburn  7118:   float: left;
1.808     droeschl 7119: }
                   7120: 
1.897     wenzelju 7121: ul#LC_secondary_menu li {
1.911     bisitz   7122:   font-weight: bold;
                   7123:   line-height: 1.8em;
1.1107    raeburn  7124:   border-right: 1px solid black;
                   7125:   float: left;
                   7126: }
                   7127: 
                   7128: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7129:   background-color: $data_table_light;
                   7130: }
                   7131: 
                   7132: ul#LC_secondary_menu li a {
1.911     bisitz   7133:   padding: 0 0.8em;
1.1107    raeburn  7134: }
                   7135: 
                   7136: ul#LC_secondary_menu li ul {
                   7137:   display: none;
                   7138: }
                   7139: 
                   7140: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7141:   display: block;
                   7142:   position: absolute;
                   7143:   margin: 0;
                   7144:   padding: 0;
                   7145:   list-style:none;
                   7146:   float: none;
                   7147:   background-color: $data_table_light;
                   7148:   z-index: 2;
                   7149:   margin-left: -1px;
                   7150: }
                   7151: 
                   7152: ul#LC_secondary_menu li ul li {
                   7153:   font-size: 90%;
                   7154:   vertical-align: top;
                   7155:   border-left: 1px solid black;
1.911     bisitz   7156:   border-right: 1px solid black;
1.1119    raeburn  7157:   background-color: $data_table_light;
1.1107    raeburn  7158:   list-style:none;
                   7159:   float: none;
                   7160: }
                   7161: 
                   7162: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7163:   background-color: $data_table_dark;
1.807     droeschl 7164: }
                   7165: 
1.847     tempelho 7166: ul.LC_TabContent {
1.911     bisitz   7167:   display:block;
                   7168:   background: $sidebg;
                   7169:   border-bottom: solid 1px $lg_border_color;
                   7170:   list-style:none;
1.1020    raeburn  7171:   margin: -1px -10px 0 -10px;
1.911     bisitz   7172:   padding: 0;
1.693     droeschl 7173: }
                   7174: 
1.795     www      7175: ul.LC_TabContent li,
                   7176: ul.LC_TabContentBigger li {
1.911     bisitz   7177:   float:left;
1.741     harmsja  7178: }
1.795     www      7179: 
1.897     wenzelju 7180: ul#LC_secondary_menu li a {
1.911     bisitz   7181:   color: $fontmenu;
                   7182:   text-decoration: none;
1.693     droeschl 7183: }
1.795     www      7184: 
1.721     harmsja  7185: ul.LC_TabContent {
1.952     onken    7186:   min-height:20px;
1.721     harmsja  7187: }
1.795     www      7188: 
                   7189: ul.LC_TabContent li {
1.911     bisitz   7190:   vertical-align:middle;
1.959     onken    7191:   padding: 0 16px 0 10px;
1.911     bisitz   7192:   background-color:$tabbg;
                   7193:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7194:   border-left: solid 1px $font;
1.721     harmsja  7195: }
1.795     www      7196: 
1.847     tempelho 7197: ul.LC_TabContent .right {
1.911     bisitz   7198:   float:right;
1.847     tempelho 7199: }
                   7200: 
1.911     bisitz   7201: ul.LC_TabContent li a,
                   7202: ul.LC_TabContent li {
                   7203:   color:rgb(47,47,47);
                   7204:   text-decoration:none;
                   7205:   font-size:95%;
                   7206:   font-weight:bold;
1.952     onken    7207:   min-height:20px;
                   7208: }
                   7209: 
1.959     onken    7210: ul.LC_TabContent li a:hover,
                   7211: ul.LC_TabContent li a:focus {
1.952     onken    7212:   color: $button_hover;
1.959     onken    7213:   background:none;
                   7214:   outline:none;
1.952     onken    7215: }
                   7216: 
                   7217: ul.LC_TabContent li:hover {
                   7218:   color: $button_hover;
                   7219:   cursor:pointer;
1.721     harmsja  7220: }
1.795     www      7221: 
1.911     bisitz   7222: ul.LC_TabContent li.active {
1.952     onken    7223:   color: $font;
1.911     bisitz   7224:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7225:   border-bottom:solid 1px #FFFFFF;
                   7226:   cursor: default;
1.744     ehlerst  7227: }
1.795     www      7228: 
1.959     onken    7229: ul.LC_TabContent li.active a {
                   7230:   color:$font;
                   7231:   background:#FFFFFF;
                   7232:   outline: none;
                   7233: }
1.1047    raeburn  7234: 
                   7235: ul.LC_TabContent li.goback {
                   7236:   float: left;
                   7237:   border-left: none;
                   7238: }
                   7239: 
1.870     tempelho 7240: #maincoursedoc {
1.911     bisitz   7241:   clear:both;
1.870     tempelho 7242: }
                   7243: 
                   7244: ul.LC_TabContentBigger {
1.911     bisitz   7245:   display:block;
                   7246:   list-style:none;
                   7247:   padding: 0;
1.870     tempelho 7248: }
                   7249: 
1.795     www      7250: ul.LC_TabContentBigger li {
1.911     bisitz   7251:   vertical-align:bottom;
                   7252:   height: 30px;
                   7253:   font-size:110%;
                   7254:   font-weight:bold;
                   7255:   color: #737373;
1.841     tempelho 7256: }
                   7257: 
1.957     onken    7258: ul.LC_TabContentBigger li.active {
                   7259:   position: relative;
                   7260:   top: 1px;
                   7261: }
                   7262: 
1.870     tempelho 7263: ul.LC_TabContentBigger li a {
1.911     bisitz   7264:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7265:   height: 30px;
                   7266:   line-height: 30px;
                   7267:   text-align: center;
                   7268:   display: block;
                   7269:   text-decoration: none;
1.958     onken    7270:   outline: none;  
1.741     harmsja  7271: }
1.795     www      7272: 
1.870     tempelho 7273: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7274:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7275:   color:$font;
1.744     ehlerst  7276: }
1.795     www      7277: 
1.870     tempelho 7278: ul.LC_TabContentBigger li b {
1.911     bisitz   7279:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7280:   display: block;
                   7281:   float: left;
                   7282:   padding: 0 30px;
1.957     onken    7283:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7284: }
                   7285: 
1.956     onken    7286: ul.LC_TabContentBigger li:hover b {
                   7287:   color:$button_hover;
                   7288: }
                   7289: 
1.870     tempelho 7290: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7291:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7292:   color:$font;
1.957     onken    7293:   border: 0;
1.741     harmsja  7294: }
1.693     droeschl 7295: 
1.870     tempelho 7296: 
1.862     bisitz   7297: ul.LC_CourseBreadcrumbs {
                   7298:   background: $sidebg;
1.1020    raeburn  7299:   height: 2em;
1.862     bisitz   7300:   padding-left: 10px;
1.1020    raeburn  7301:   margin: 0;
1.862     bisitz   7302:   list-style-position: inside;
                   7303: }
                   7304: 
1.911     bisitz   7305: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7306: ol#LC_PathBreadcrumbs {
1.911     bisitz   7307:   padding-left: 10px;
                   7308:   margin: 0;
1.933     droeschl 7309:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7310: }
                   7311: 
1.911     bisitz   7312: ol#LC_MenuBreadcrumbs li,
                   7313: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7314: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7315:   display: inline;
1.933     droeschl 7316:   white-space: normal;  
1.693     droeschl 7317: }
                   7318: 
1.823     bisitz   7319: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7320: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7321:   text-decoration: none;
                   7322:   font-size:90%;
1.693     droeschl 7323: }
1.795     www      7324: 
1.969     droeschl 7325: ol#LC_MenuBreadcrumbs h1 {
                   7326:   display: inline;
                   7327:   font-size: 90%;
                   7328:   line-height: 2.5em;
                   7329:   margin: 0;
                   7330:   padding: 0;
                   7331: }
                   7332: 
1.795     www      7333: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7334:   text-decoration:none;
                   7335:   font-size:100%;
                   7336:   font-weight:bold;
1.693     droeschl 7337: }
1.795     www      7338: 
1.840     bisitz   7339: .LC_Box {
1.911     bisitz   7340:   border: solid 1px $lg_border_color;
                   7341:   padding: 0 10px 10px 10px;
1.746     neumanie 7342: }
1.795     www      7343: 
1.1020    raeburn  7344: .LC_DocsBox {
                   7345:   border: solid 1px $lg_border_color;
                   7346:   padding: 0 0 10px 10px;
                   7347: }
                   7348: 
1.795     www      7349: .LC_AboutMe_Image {
1.911     bisitz   7350:   float:left;
                   7351:   margin-right:10px;
1.747     neumanie 7352: }
1.795     www      7353: 
                   7354: .LC_Clear_AboutMe_Image {
1.911     bisitz   7355:   clear:left;
1.747     neumanie 7356: }
1.795     www      7357: 
1.721     harmsja  7358: dl.LC_ListStyleClean dt {
1.911     bisitz   7359:   padding-right: 5px;
                   7360:   display: table-header-group;
1.693     droeschl 7361: }
                   7362: 
1.721     harmsja  7363: dl.LC_ListStyleClean dd {
1.911     bisitz   7364:   display: table-row;
1.693     droeschl 7365: }
                   7366: 
1.721     harmsja  7367: .LC_ListStyleClean,
                   7368: .LC_ListStyleSimple,
                   7369: .LC_ListStyleNormal,
1.795     www      7370: .LC_ListStyleSpecial {
1.911     bisitz   7371:   /* display:block; */
                   7372:   list-style-position: inside;
                   7373:   list-style-type: none;
                   7374:   overflow: hidden;
                   7375:   padding: 0;
1.693     droeschl 7376: }
                   7377: 
1.721     harmsja  7378: .LC_ListStyleSimple li,
                   7379: .LC_ListStyleSimple dd,
                   7380: .LC_ListStyleNormal li,
                   7381: .LC_ListStyleNormal dd,
                   7382: .LC_ListStyleSpecial li,
1.795     www      7383: .LC_ListStyleSpecial dd {
1.911     bisitz   7384:   margin: 0;
                   7385:   padding: 5px 5px 5px 10px;
                   7386:   clear: both;
1.693     droeschl 7387: }
                   7388: 
1.721     harmsja  7389: .LC_ListStyleClean li,
                   7390: .LC_ListStyleClean dd {
1.911     bisitz   7391:   padding-top: 0;
                   7392:   padding-bottom: 0;
1.693     droeschl 7393: }
                   7394: 
1.721     harmsja  7395: .LC_ListStyleSimple dd,
1.795     www      7396: .LC_ListStyleSimple li {
1.911     bisitz   7397:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7398: }
                   7399: 
1.721     harmsja  7400: .LC_ListStyleSpecial li,
                   7401: .LC_ListStyleSpecial dd {
1.911     bisitz   7402:   list-style-type: none;
                   7403:   background-color: RGB(220, 220, 220);
                   7404:   margin-bottom: 4px;
1.693     droeschl 7405: }
                   7406: 
1.721     harmsja  7407: table.LC_SimpleTable {
1.911     bisitz   7408:   margin:5px;
                   7409:   border:solid 1px $lg_border_color;
1.795     www      7410: }
1.693     droeschl 7411: 
1.721     harmsja  7412: table.LC_SimpleTable tr {
1.911     bisitz   7413:   padding: 0;
                   7414:   border:solid 1px $lg_border_color;
1.693     droeschl 7415: }
1.795     www      7416: 
                   7417: table.LC_SimpleTable thead {
1.911     bisitz   7418:   background:rgb(220,220,220);
1.693     droeschl 7419: }
                   7420: 
1.721     harmsja  7421: div.LC_columnSection {
1.911     bisitz   7422:   display: block;
                   7423:   clear: both;
                   7424:   overflow: hidden;
                   7425:   margin: 0;
1.693     droeschl 7426: }
                   7427: 
1.721     harmsja  7428: div.LC_columnSection>* {
1.911     bisitz   7429:   float: left;
                   7430:   margin: 10px 20px 10px 0;
                   7431:   overflow:hidden;
1.693     droeschl 7432: }
1.721     harmsja  7433: 
1.795     www      7434: table em {
1.911     bisitz   7435:   font-weight: bold;
                   7436:   font-style: normal;
1.748     schulted 7437: }
1.795     www      7438: 
1.779     bisitz   7439: table.LC_tableBrowseRes,
1.795     www      7440: table.LC_tableOfContent {
1.911     bisitz   7441:   border:none;
                   7442:   border-spacing: 1px;
                   7443:   padding: 3px;
                   7444:   background-color: #FFFFFF;
                   7445:   font-size: 90%;
1.753     droeschl 7446: }
1.789     droeschl 7447: 
1.911     bisitz   7448: table.LC_tableOfContent {
                   7449:   border-collapse: collapse;
1.789     droeschl 7450: }
                   7451: 
1.771     droeschl 7452: table.LC_tableBrowseRes a,
1.768     schulted 7453: table.LC_tableOfContent a {
1.911     bisitz   7454:   background-color: transparent;
                   7455:   text-decoration: none;
1.753     droeschl 7456: }
                   7457: 
1.795     www      7458: table.LC_tableOfContent img {
1.911     bisitz   7459:   border: none;
                   7460:   height: 1.3em;
                   7461:   vertical-align: text-bottom;
                   7462:   margin-right: 0.3em;
1.753     droeschl 7463: }
1.757     schulted 7464: 
1.795     www      7465: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7466:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7467: }
                   7468: 
1.795     www      7469: a#LC_content_toolbar_everything {
1.911     bisitz   7470:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7471: }
                   7472: 
1.795     www      7473: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7474:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7475: }
                   7476: 
1.795     www      7477: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7478:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7479: }
                   7480: 
1.795     www      7481: a#LC_content_toolbar_changefolder {
1.911     bisitz   7482:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7483: }
                   7484: 
1.795     www      7485: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7486:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7487: }
                   7488: 
1.1043    raeburn  7489: a#LC_content_toolbar_edittoplevel {
                   7490:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7491: }
                   7492: 
1.795     www      7493: ul#LC_toolbar li a:hover {
1.911     bisitz   7494:   background-position: bottom center;
1.757     schulted 7495: }
                   7496: 
1.795     www      7497: ul#LC_toolbar {
1.911     bisitz   7498:   padding: 0;
                   7499:   margin: 2px;
                   7500:   list-style:none;
                   7501:   position:relative;
                   7502:   background-color:white;
1.1082    raeburn  7503:   overflow: auto;
1.757     schulted 7504: }
                   7505: 
1.795     www      7506: ul#LC_toolbar li {
1.911     bisitz   7507:   border:1px solid white;
                   7508:   padding: 0;
                   7509:   margin: 0;
                   7510:   float: left;
                   7511:   display:inline;
                   7512:   vertical-align:middle;
1.1082    raeburn  7513:   white-space: nowrap;
1.911     bisitz   7514: }
1.757     schulted 7515: 
1.783     amueller 7516: 
1.795     www      7517: a.LC_toolbarItem {
1.911     bisitz   7518:   display:block;
                   7519:   padding: 0;
                   7520:   margin: 0;
                   7521:   height: 32px;
                   7522:   width: 32px;
                   7523:   color:white;
                   7524:   border: none;
                   7525:   background-repeat:no-repeat;
                   7526:   background-color:transparent;
1.757     schulted 7527: }
                   7528: 
1.915     droeschl 7529: ul.LC_funclist {
                   7530:     margin: 0;
                   7531:     padding: 0.5em 1em 0.5em 0;
                   7532: }
                   7533: 
1.933     droeschl 7534: ul.LC_funclist > li:first-child {
                   7535:     font-weight:bold; 
                   7536:     margin-left:0.8em;
                   7537: }
                   7538: 
1.915     droeschl 7539: ul.LC_funclist + ul.LC_funclist {
                   7540:     /* 
                   7541:        left border as a seperator if we have more than
                   7542:        one list 
                   7543:     */
                   7544:     border-left: 1px solid $sidebg;
                   7545:     /* 
                   7546:        this hides the left border behind the border of the 
                   7547:        outer box if element is wrapped to the next 'line' 
                   7548:     */
                   7549:     margin-left: -1px;
                   7550: }
                   7551: 
1.843     bisitz   7552: ul.LC_funclist li {
1.915     droeschl 7553:   display: inline;
1.782     bisitz   7554:   white-space: nowrap;
1.915     droeschl 7555:   margin: 0 0 0 25px;
                   7556:   line-height: 150%;
1.782     bisitz   7557: }
                   7558: 
1.974     wenzelju 7559: .LC_hidden {
                   7560:   display: none;
                   7561: }
                   7562: 
1.1030    www      7563: .LCmodal-overlay {
                   7564: 		position:fixed;
                   7565: 		top:0;
                   7566: 		right:0;
                   7567: 		bottom:0;
                   7568: 		left:0;
                   7569: 		height:100%;
                   7570: 		width:100%;
                   7571: 		margin:0;
                   7572: 		padding:0;
                   7573: 		background:#999;
                   7574: 		opacity:.75;
                   7575: 		filter: alpha(opacity=75);
                   7576: 		-moz-opacity: 0.75;
                   7577: 		z-index:101;
                   7578: }
                   7579: 
                   7580: * html .LCmodal-overlay {   
                   7581: 		position: absolute;
                   7582: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7583: }
                   7584: 
                   7585: .LCmodal-window {
                   7586: 		position:fixed;
                   7587: 		top:50%;
                   7588: 		left:50%;
                   7589: 		margin:0;
                   7590: 		padding:0;
                   7591: 		z-index:102;
                   7592: 	}
                   7593: 
                   7594: * html .LCmodal-window {
                   7595: 		position:absolute;
                   7596: }
                   7597: 
                   7598: .LCclose-window {
                   7599: 		position:absolute;
                   7600: 		width:32px;
                   7601: 		height:32px;
                   7602: 		right:8px;
                   7603: 		top:8px;
                   7604: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7605: 		text-indent:-99999px;
                   7606: 		overflow:hidden;
                   7607: 		cursor:pointer;
                   7608: }
                   7609: 
1.1100    raeburn  7610: /*
                   7611:   styles used by TTH when "Default set of options to pass to tth/m
                   7612:   when converting TeX" in course settings has been set
                   7613: 
                   7614:   option passed: -t
                   7615: 
                   7616: */
                   7617: 
                   7618: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7619: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7620: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7621: td div.norm {line-height:normal;}
                   7622: 
                   7623: /*
                   7624:   option passed -y3
                   7625: */
                   7626: 
                   7627: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7628: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7629: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7630: 
1.343     albertel 7631: END
                   7632: }
                   7633: 
1.306     albertel 7634: =pod
                   7635: 
                   7636: =item * &headtag()
                   7637: 
                   7638: Returns a uniform footer for LON-CAPA web pages.
                   7639: 
1.307     albertel 7640: Inputs: $title - optional title for the head
                   7641:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7642:         $args - optional arguments
1.319     albertel 7643:             force_register - if is true call registerurl so the remote is 
                   7644:                              informed
1.415     albertel 7645:             redirect       -> array ref of
                   7646:                                    1- seconds before redirect occurs
                   7647:                                    2- url to redirect to
                   7648:                                    3- whether the side effect should occur
1.315     albertel 7649:                            (side effect of setting 
                   7650:                                $env{'internal.head.redirect'} to the url 
                   7651:                                redirected too)
1.352     albertel 7652:             domain         -> force to color decorate a page for a specific
                   7653:                                domain
                   7654:             function       -> force usage of a specific rolish color scheme
                   7655:             bgcolor        -> override the default page bgcolor
1.460     albertel 7656:             no_auto_mt_title
                   7657:                            -> prevent &mt()ing the title arg
1.464     albertel 7658: 
1.306     albertel 7659: =cut
                   7660: 
                   7661: sub headtag {
1.313     albertel 7662:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7663:     
1.363     albertel 7664:     my $function = $args->{'function'} || &get_users_function();
                   7665:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7666:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1154    raeburn  7667:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7668:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7669: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7670: 		   #time(),
1.418     albertel 7671: 		   $env{'environment.color.timestamp'},
1.363     albertel 7672: 		   $function,$domain,$bgcolor);
                   7673: 
1.369     www      7674:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7675: 
1.308     albertel 7676:     my $result =
                   7677: 	'<head>'.
1.1160    raeburn  7678: 	&font_settings($args);
1.319     albertel 7679: 
1.1188    raeburn  7680:     my $inhibitprint;
                   7681:     if ($args->{'print_suppress'}) {
                   7682:         $inhibitprint = &print_suppression();
                   7683:     }
1.1064    raeburn  7684: 
1.461     albertel 7685:     if (!$args->{'frameset'}) {
                   7686: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7687:     }
1.962     droeschl 7688:     if ($args->{'force_register'} && $env{'request.noversionuri'} !~ m{^/res/adm/pages/}) {
                   7689:         $result .= Apache::lonxml::display_title();
1.319     albertel 7690:     }
1.436     albertel 7691:     if (!$args->{'no_nav_bar'} 
                   7692: 	&& !$args->{'only_body'}
                   7693: 	&& !$args->{'frameset'}) {
1.1154    raeburn  7694: 	$result .= &help_menu_js($httphost);
1.1032    www      7695:         $result.=&modal_window();
1.1038    www      7696:         $result.=&togglebox_script();
1.1034    www      7697:         $result.=&wishlist_window();
1.1041    www      7698:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7699:     } else {
                   7700:         if ($args->{'add_modal'}) {
                   7701:            $result.=&modal_window();
                   7702:         }
                   7703:         if ($args->{'add_wishlist'}) {
                   7704:            $result.=&wishlist_window();
                   7705:         }
1.1038    www      7706:         if ($args->{'add_togglebox'}) {
                   7707:            $result.=&togglebox_script();
                   7708:         }
1.1041    www      7709:         if ($args->{'add_progressbar'}) {
                   7710:            $result.=&LCprogressbarUpdate_script();
                   7711:         }
1.436     albertel 7712:     }
1.314     albertel 7713:     if (ref($args->{'redirect'})) {
1.414     albertel 7714: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7715: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7716: 	if (!$inhibit_continue) {
                   7717: 	    $env{'internal.head.redirect'} = $url;
                   7718: 	}
1.313     albertel 7719: 	$result.=<<ADDMETA
                   7720: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7721: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7722: ADDMETA
1.1210    raeburn  7723:     } else {
                   7724:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7725:             my $requrl = $env{'request.uri'};
                   7726:             if ($requrl eq '') {
                   7727:                 $requrl = $ENV{'REQUEST_URI'};
                   7728:                 $requrl =~ s/\?.+$//;
                   7729:             }
                   7730:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7731:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7732:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7733:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7734:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7735:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7736:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7737:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7738:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7739:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7740:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7741:                                 my $numsec = 5;
                   7742:                                 my $timeout = $numsec * 1000;
                   7743:                                 my ($newurl,$locknum,%locks,$msg);
                   7744:                                 if ($env{'request.role.adv'}) {
                   7745:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7746:                                 }
                   7747:                                 my $disable_submit = 0;
                   7748:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7749:                                     $disable_submit = 1;
                   7750:                                 }
                   7751:                                 if ($locknum) {
                   7752:                                     my @lockinfo = sort(values(%locks));
                   7753:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7754:                                            join(", ",sort(values(%locks)))."\\n".
                   7755:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7756:                                 } else {
                   7757:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7758:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7759:                                     }
                   7760:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7761:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7762:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7763:                                         $newurl .= '&role='.$env{'request.role'};
                   7764:                                     }
                   7765:                                     if ($env{'request.symb'}) {
                   7766:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7767:                                     } else {
                   7768:                                         $newurl .= '&origurl='.$requrl;
                   7769:                                     }
                   7770:                                 }
                   7771:                                 $result.=<<OFFLOAD
                   7772: <meta http-equiv="pragma" content="no-cache" />
                   7773: <script type="text/javascript">
1.1215    raeburn  7774: // <![CDATA[
1.1210    raeburn  7775: function LC_Offload_Now() {
                   7776:     var dest = "$newurl";
                   7777:     if (dest != '') {
                   7778:         window.location.href="$newurl";
                   7779:     }
                   7780: }
1.1214    raeburn  7781: \$(document).ready(function () {
                   7782:     window.alert('$msg');
                   7783:     if ($disable_submit) {
1.1210    raeburn  7784:         \$(".LC_hwk_submit").prop("disabled", true);
                   7785:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1214    raeburn  7786:     }
                   7787:     setTimeout('LC_Offload_Now()', $timeout);
                   7788: });
1.1215    raeburn  7789: // ]]>
1.1210    raeburn  7790: </script>
                   7791: OFFLOAD
                   7792:                             }
                   7793:                         }
                   7794:                     }
                   7795:                 }
                   7796:             }
                   7797:         }
1.313     albertel 7798:     }
1.306     albertel 7799:     if (!defined($title)) {
                   7800: 	$title = 'The LearningOnline Network with CAPA';
                   7801:     }
1.460     albertel 7802:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7803:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1168    raeburn  7804: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7805:     if (!$args->{'frameset'}) {
                   7806:         $result .= ' /';
                   7807:     }
                   7808:     $result .= '>' 
1.1064    raeburn  7809:         .$inhibitprint
1.414     albertel 7810: 	.$head_extra;
1.1137    raeburn  7811:     if ($env{'browser.mobile'}) {
                   7812:         $result .= '
                   7813: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7814: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7815:     }
1.962     droeschl 7816:     return $result.'</head>';
1.306     albertel 7817: }
                   7818: 
                   7819: =pod
                   7820: 
1.340     albertel 7821: =item * &font_settings()
                   7822: 
                   7823: Returns neccessary <meta> to set the proper encoding
                   7824: 
1.1160    raeburn  7825: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7826: 
                   7827: =cut
                   7828: 
                   7829: sub font_settings {
1.1160    raeburn  7830:     my ($args) = @_;
1.340     albertel 7831:     my $headerstring='';
1.1160    raeburn  7832:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7833:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.1168    raeburn  7834:         $headerstring.=
                   7835:             '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7836:         if (!$args->{'frameset'}) {
                   7837: 	    $headerstring.= ' /';
                   7838:         }
                   7839: 	$headerstring .= '>'."\n";
1.340     albertel 7840:     }
                   7841:     return $headerstring;
                   7842: }
                   7843: 
1.341     albertel 7844: =pod
                   7845: 
1.1064    raeburn  7846: =item * &print_suppression()
                   7847: 
                   7848: In course context returns css which causes the body to be blank when media="print",
                   7849: if printout generation is unavailable for the current resource.
                   7850: 
                   7851: This could be because:
                   7852: 
                   7853: (a) printstartdate is in the future
                   7854: 
                   7855: (b) printenddate is in the past
                   7856: 
                   7857: (c) there is an active exam block with "printout"
                   7858: functionality blocked
                   7859: 
                   7860: Users with pav, pfo or evb privileges are exempt.
                   7861: 
                   7862: Inputs: none
                   7863: 
                   7864: =cut
                   7865: 
                   7866: 
                   7867: sub print_suppression {
                   7868:     my $noprint;
                   7869:     if ($env{'request.course.id'}) {
                   7870:         my $scope = $env{'request.course.id'};
                   7871:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7872:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7873:             return;
                   7874:         }
                   7875:         if ($env{'request.course.sec'} ne '') {
                   7876:             $scope .= "/$env{'request.course.sec'}";
                   7877:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7878:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7879:                 return;
1.1064    raeburn  7880:             }
                   7881:         }
                   7882:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7883:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1189    raeburn  7884:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7885:         if ($blocked) {
                   7886:             my $checkrole = "cm./$cdom/$cnum";
                   7887:             if ($env{'request.course.sec'} ne '') {
                   7888:                 $checkrole .= "/$env{'request.course.sec'}";
                   7889:             }
                   7890:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7891:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7892:                 $noprint = 1;
                   7893:             }
                   7894:         }
                   7895:         unless ($noprint) {
                   7896:             my $symb = &Apache::lonnet::symbread();
                   7897:             if ($symb ne '') {
                   7898:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7899:                 if (ref($navmap)) {
                   7900:                     my $res = $navmap->getBySymb($symb);
                   7901:                     if (ref($res)) {
                   7902:                         if (!$res->resprintable()) {
                   7903:                             $noprint = 1;
                   7904:                         }
                   7905:                     }
                   7906:                 }
                   7907:             }
                   7908:         }
                   7909:         if ($noprint) {
                   7910:             return <<"ENDSTYLE";
                   7911: <style type="text/css" media="print">
                   7912:     body { display:none }
                   7913: </style>
                   7914: ENDSTYLE
                   7915:         }
                   7916:     }
                   7917:     return;
                   7918: }
                   7919: 
                   7920: =pod
                   7921: 
1.341     albertel 7922: =item * &xml_begin()
                   7923: 
                   7924: Returns the needed doctype and <html>
                   7925: 
                   7926: Inputs: none
                   7927: 
                   7928: =cut
                   7929: 
                   7930: sub xml_begin {
1.1168    raeburn  7931:     my ($is_frameset) = @_;
1.341     albertel 7932:     my $output='';
                   7933: 
                   7934:     if ($env{'browser.mathml'}) {
                   7935: 	$output='<?xml version="1.0"?>'
                   7936:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7937: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7938:             
                   7939: #	    .'<!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">] >'
                   7940: 	    .'<!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">'
                   7941:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7942: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1168    raeburn  7943:     } elsif ($is_frameset) {
                   7944:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7945:                 '<html>'."\n";
1.341     albertel 7946:     } else {
1.1168    raeburn  7947: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7948:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7949:     }
                   7950:     return $output;
                   7951: }
1.340     albertel 7952: 
                   7953: =pod
                   7954: 
1.306     albertel 7955: =item * &start_page()
                   7956: 
                   7957: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7958: 
1.648     raeburn  7959: Inputs:
                   7960: 
                   7961: =over 4
                   7962: 
                   7963: $title - optional title for the page
                   7964: 
                   7965: $head_extra - optional extra HTML to incude inside the <head>
                   7966: 
                   7967: $args - additional optional args supported are:
                   7968: 
                   7969: =over 8
                   7970: 
                   7971:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7972:                                     arg on
1.814     bisitz   7973:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7974:              add_entries    -> additional attributes to add to the  <body>
                   7975:              domain         -> force to color decorate a page for a 
1.317     albertel 7976:                                     specific domain
1.648     raeburn  7977:              function       -> force usage of a specific rolish color
1.317     albertel 7978:                                     scheme
1.648     raeburn  7979:              redirect       -> see &headtag()
                   7980:              bgcolor        -> override the default page bg color
                   7981:              js_ready       -> return a string ready for being used in 
1.317     albertel 7982:                                     a javascript writeln
1.648     raeburn  7983:              html_encode    -> return a string ready for being used in 
1.320     albertel 7984:                                     a html attribute
1.648     raeburn  7985:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7986:                                     $forcereg arg
1.648     raeburn  7987:              frameset       -> if true will start with a <frameset>
1.330     albertel 7988:                                     rather than <body>
1.648     raeburn  7989:              skip_phases    -> hash ref of 
1.338     albertel 7990:                                     head -> skip the <html><head> generation
                   7991:                                     body -> skip all <body> generation
1.648     raeburn  7992:              no_auto_mt_title -> prevent &mt()ing the title arg
                   7993:              inherit_jsmath -> when creating popup window in a page,
                   7994:                                     should it have jsmath forced on by the
                   7995:                                     current page
1.867     kalberla 7996:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7997:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1096    raeburn  7998:              group          -> includes the current group, if page is for a 
                   7999:                                specific group  
1.361     albertel 8000: 
1.648     raeburn  8001: =back
1.460     albertel 8002: 
1.648     raeburn  8003: =back
1.562     albertel 8004: 
1.306     albertel 8005: =cut
                   8006: 
                   8007: sub start_page {
1.309     albertel 8008:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8009:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8010: 
1.315     albertel 8011:     $env{'internal.start_page'}++;
1.1096    raeburn  8012:     my ($result,@advtools);
1.964     droeschl 8013: 
1.338     albertel 8014:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1168    raeburn  8015:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8016:     }
                   8017:     
                   8018:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8019: 	if ($args->{'frameset'}) {
                   8020: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8021: 						$args->{'add_entries'});
                   8022: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8023:         } else {
                   8024:             $result .=
                   8025:                 &bodytag($title, 
                   8026:                          $args->{'function'},       $args->{'add_entries'},
                   8027:                          $args->{'only_body'},      $args->{'domain'},
                   8028:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1096    raeburn  8029:                          $args->{'bgcolor'},        $args,
                   8030:                          \@advtools);
1.831     bisitz   8031:         }
1.330     albertel 8032:     }
1.338     albertel 8033: 
1.315     albertel 8034:     if ($args->{'js_ready'}) {
1.713     kaisler  8035: 		$result = &js_ready($result);
1.315     albertel 8036:     }
1.320     albertel 8037:     if ($args->{'html_encode'}) {
1.713     kaisler  8038: 		$result = &html_encode($result);
                   8039:     }
                   8040: 
1.813     bisitz   8041:     # Preparation for new and consistent functionlist at top of screen
                   8042:     # if ($args->{'functionlist'}) {
                   8043:     #            $result .= &build_functionlist();
                   8044:     #}
                   8045: 
1.964     droeschl 8046:     # Don't add anything more if only_body wanted or in const space
                   8047:     return $result if    $args->{'only_body'} 
                   8048:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8049: 
                   8050:     #Breadcrumbs
1.758     kaisler  8051:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8052: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8053: 		#if any br links exists, add them to the breadcrumbs
                   8054: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8055: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8056: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8057: 			}
                   8058: 		}
1.1096    raeburn  8059:                 # if @advtools array contains items add then to the breadcrumbs
                   8060:                 if (@advtools > 0) {
                   8061:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8062:                 }
1.758     kaisler  8063: 
                   8064: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8065: 		if(exists($args->{'bread_crumbs_component'})){
                   8066: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   8067: 		}else{
                   8068: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   8069: 		}
1.320     albertel 8070:     }
1.315     albertel 8071:     return $result;
1.306     albertel 8072: }
                   8073: 
                   8074: sub end_page {
1.315     albertel 8075:     my ($args) = @_;
                   8076:     $env{'internal.end_page'}++;
1.330     albertel 8077:     my $result;
1.335     albertel 8078:     if ($args->{'discussion'}) {
                   8079: 	my ($target,$parser);
                   8080: 	if (ref($args->{'discussion'})) {
                   8081: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8082: 				$args->{'discussion'}{'parser'});
                   8083: 	}
                   8084: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8085:     }
1.330     albertel 8086:     if ($args->{'frameset'}) {
                   8087: 	$result .= '</frameset>';
                   8088:     } else {
1.635     raeburn  8089: 	$result .= &endbodytag($args);
1.330     albertel 8090:     }
1.1080    raeburn  8091:     unless ($args->{'notbody'}) {
                   8092:         $result .= "\n</html>";
                   8093:     }
1.330     albertel 8094: 
1.315     albertel 8095:     if ($args->{'js_ready'}) {
1.317     albertel 8096: 	$result = &js_ready($result);
1.315     albertel 8097:     }
1.335     albertel 8098: 
1.320     albertel 8099:     if ($args->{'html_encode'}) {
                   8100: 	$result = &html_encode($result);
                   8101:     }
1.335     albertel 8102: 
1.315     albertel 8103:     return $result;
                   8104: }
                   8105: 
1.1034    www      8106: sub wishlist_window {
                   8107:     return(<<'ENDWISHLIST');
1.1046    raeburn  8108: <script type="text/javascript">
1.1034    www      8109: // <![CDATA[
                   8110: // <!-- BEGIN LON-CAPA Internal
                   8111: function set_wishlistlink(title, path) {
                   8112:     if (!title) {
                   8113:         title = document.title;
                   8114:         title = title.replace(/^LON-CAPA /,'');
                   8115:     }
1.1175    raeburn  8116:     title = encodeURIComponent(title);
1.1203    raeburn  8117:     title = title.replace("'","\\\'");
1.1034    www      8118:     if (!path) {
                   8119:         path = location.pathname;
                   8120:     }
1.1175    raeburn  8121:     path = encodeURIComponent(path);
1.1203    raeburn  8122:     path = path.replace("'","\\\'");
1.1034    www      8123:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8124:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8125: }
                   8126: // END LON-CAPA Internal -->
                   8127: // ]]>
                   8128: </script>
                   8129: ENDWISHLIST
                   8130: }
                   8131: 
1.1030    www      8132: sub modal_window {
                   8133:     return(<<'ENDMODAL');
1.1046    raeburn  8134: <script type="text/javascript">
1.1030    www      8135: // <![CDATA[
                   8136: // <!-- BEGIN LON-CAPA Internal
                   8137: var modalWindow = {
                   8138: 	parent:"body",
                   8139: 	windowId:null,
                   8140: 	content:null,
                   8141: 	width:null,
                   8142: 	height:null,
                   8143: 	close:function()
                   8144: 	{
                   8145: 	        $(".LCmodal-window").remove();
                   8146: 	        $(".LCmodal-overlay").remove();
                   8147: 	},
                   8148: 	open:function()
                   8149: 	{
                   8150: 		var modal = "";
                   8151: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8152: 		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;\">";
                   8153: 		modal += this.content;
                   8154: 		modal += "</div>";	
                   8155: 
                   8156: 		$(this.parent).append(modal);
                   8157: 
                   8158: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8159: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8160: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8161: 	}
                   8162: };
1.1140    raeburn  8163: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8164: 	{
1.1203    raeburn  8165:                 source = source.replace("'","&#39;");
1.1030    www      8166: 		modalWindow.windowId = "myModal";
                   8167: 		modalWindow.width = width;
                   8168: 		modalWindow.height = height;
1.1196    raeburn  8169: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8170: 		modalWindow.open();
1.1208    raeburn  8171: 	};
1.1030    www      8172: // END LON-CAPA Internal -->
                   8173: // ]]>
                   8174: </script>
                   8175: ENDMODAL
                   8176: }
                   8177: 
                   8178: sub modal_link {
1.1140    raeburn  8179:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8180:     unless ($width) { $width=480; }
                   8181:     unless ($height) { $height=400; }
1.1031    www      8182:     unless ($scrolling) { $scrolling='yes'; }
1.1140    raeburn  8183:     unless ($transparency) { $transparency='true'; }
                   8184: 
1.1074    raeburn  8185:     my $target_attr;
                   8186:     if (defined($target)) {
                   8187:         $target_attr = 'target="'.$target.'"';
                   8188:     }
                   8189:     return <<"ENDLINK";
1.1140    raeburn  8190: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8191:            $linktext</a>
                   8192: ENDLINK
1.1030    www      8193: }
                   8194: 
1.1032    www      8195: sub modal_adhoc_script {
                   8196:     my ($funcname,$width,$height,$content)=@_;
                   8197:     return (<<ENDADHOC);
1.1046    raeburn  8198: <script type="text/javascript">
1.1032    www      8199: // <![CDATA[
                   8200:         var $funcname = function()
                   8201:         {
                   8202:                 modalWindow.windowId = "myModal";
                   8203:                 modalWindow.width = $width;
                   8204:                 modalWindow.height = $height;
                   8205:                 modalWindow.content = '$content';
                   8206:                 modalWindow.open();
                   8207:         };  
                   8208: // ]]>
                   8209: </script>
                   8210: ENDADHOC
                   8211: }
                   8212: 
1.1041    www      8213: sub modal_adhoc_inner {
                   8214:     my ($funcname,$width,$height,$content)=@_;
                   8215:     my $innerwidth=$width-20;
                   8216:     $content=&js_ready(
1.1140    raeburn  8217:                  &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
                   8218:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8219:                  $content.
1.1041    www      8220:                  &end_scrollbox().
1.1140    raeburn  8221:                  &end_page()
1.1041    www      8222:              );
                   8223:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8224: }
                   8225: 
                   8226: sub modal_adhoc_window {
                   8227:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8228:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8229:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8230: }
                   8231: 
                   8232: sub modal_adhoc_launch {
                   8233:     my ($funcname,$width,$height,$content)=@_;
                   8234:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8235: <script type="text/javascript">
                   8236: // <![CDATA[
                   8237: $funcname();
                   8238: // ]]>
                   8239: </script>
                   8240: ENDLAUNCH
                   8241: }
                   8242: 
                   8243: sub modal_adhoc_close {
                   8244:     return (<<ENDCLOSE);
                   8245: <script type="text/javascript">
                   8246: // <![CDATA[
                   8247: modalWindow.close();
                   8248: // ]]>
                   8249: </script>
                   8250: ENDCLOSE
                   8251: }
                   8252: 
1.1038    www      8253: sub togglebox_script {
                   8254:    return(<<ENDTOGGLE);
                   8255: <script type="text/javascript"> 
                   8256: // <![CDATA[
                   8257: function LCtoggleDisplay(id,hidetext,showtext) {
                   8258:    link = document.getElementById(id + "link").childNodes[0];
                   8259:    with (document.getElementById(id).style) {
                   8260:       if (display == "none" ) {
                   8261:           display = "inline";
                   8262:           link.nodeValue = hidetext;
                   8263:         } else {
                   8264:           display = "none";
                   8265:           link.nodeValue = showtext;
                   8266:        }
                   8267:    }
                   8268: }
                   8269: // ]]>
                   8270: </script>
                   8271: ENDTOGGLE
                   8272: }
                   8273: 
1.1039    www      8274: sub start_togglebox {
                   8275:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8276:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8277:     unless ($showtext) { $showtext=&mt('show'); }
                   8278:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8279:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8280:     return &start_data_table().
                   8281:            &start_data_table_header_row().
                   8282:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8283:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8284:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8285:            &end_data_table_header_row().
                   8286:            '<tr id="'.$id.'" style="display:none""><td>';
                   8287: }
                   8288: 
                   8289: sub end_togglebox {
                   8290:     return '</td></tr>'.&end_data_table();
                   8291: }
                   8292: 
1.1041    www      8293: sub LCprogressbar_script {
1.1045    www      8294:    my ($id)=@_;
1.1041    www      8295:    return(<<ENDPROGRESS);
                   8296: <script type="text/javascript">
                   8297: // <![CDATA[
1.1045    www      8298: \$('#progressbar$id').progressbar({
1.1041    www      8299:   value: 0,
                   8300:   change: function(event, ui) {
                   8301:     var newVal = \$(this).progressbar('option', 'value');
                   8302:     \$('.pblabel', this).text(LCprogressTxt);
                   8303:   }
                   8304: });
                   8305: // ]]>
                   8306: </script>
                   8307: ENDPROGRESS
                   8308: }
                   8309: 
                   8310: sub LCprogressbarUpdate_script {
                   8311:    return(<<ENDPROGRESSUPDATE);
                   8312: <style type="text/css">
                   8313: .ui-progressbar { position:relative; }
                   8314: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8315: </style>
                   8316: <script type="text/javascript">
                   8317: // <![CDATA[
1.1045    www      8318: var LCprogressTxt='---';
                   8319: 
                   8320: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8321:    LCprogressTxt=progresstext;
1.1045    www      8322:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8323: }
                   8324: // ]]>
                   8325: </script>
                   8326: ENDPROGRESSUPDATE
                   8327: }
                   8328: 
1.1042    www      8329: my $LClastpercent;
1.1045    www      8330: my $LCidcnt;
                   8331: my $LCcurrentid;
1.1042    www      8332: 
1.1041    www      8333: sub LCprogressbar {
1.1042    www      8334:     my ($r)=(@_);
                   8335:     $LClastpercent=0;
1.1045    www      8336:     $LCidcnt++;
                   8337:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8338:     my $starting=&mt('Starting');
                   8339:     my $content=(<<ENDPROGBAR);
1.1045    www      8340:   <div id="progressbar$LCcurrentid">
1.1041    www      8341:     <span class="pblabel">$starting</span>
                   8342:   </div>
                   8343: ENDPROGBAR
1.1045    www      8344:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8345: }
                   8346: 
                   8347: sub LCprogressbarUpdate {
1.1042    www      8348:     my ($r,$val,$text)=@_;
                   8349:     unless ($val) { 
                   8350:        if ($LClastpercent) {
                   8351:            $val=$LClastpercent;
                   8352:        } else {
                   8353:            $val=0;
                   8354:        }
                   8355:     }
1.1041    www      8356:     if ($val<0) { $val=0; }
                   8357:     if ($val>100) { $val=0; }
1.1042    www      8358:     $LClastpercent=$val;
1.1041    www      8359:     unless ($text) { $text=$val.'%'; }
                   8360:     $text=&js_ready($text);
1.1044    www      8361:     &r_print($r,<<ENDUPDATE);
1.1041    www      8362: <script type="text/javascript">
                   8363: // <![CDATA[
1.1045    www      8364: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8365: // ]]>
                   8366: </script>
                   8367: ENDUPDATE
1.1035    www      8368: }
                   8369: 
1.1042    www      8370: sub LCprogressbarClose {
                   8371:     my ($r)=@_;
                   8372:     $LClastpercent=0;
1.1044    www      8373:     &r_print($r,<<ENDCLOSE);
1.1042    www      8374: <script type="text/javascript">
                   8375: // <![CDATA[
1.1045    www      8376: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8377: // ]]>
                   8378: </script>
                   8379: ENDCLOSE
1.1044    www      8380: }
                   8381: 
                   8382: sub r_print {
                   8383:     my ($r,$to_print)=@_;
                   8384:     if ($r) {
                   8385:       $r->print($to_print);
                   8386:       $r->rflush();
                   8387:     } else {
                   8388:       print($to_print);
                   8389:     }
1.1042    www      8390: }
                   8391: 
1.320     albertel 8392: sub html_encode {
                   8393:     my ($result) = @_;
                   8394: 
1.322     albertel 8395:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8396:     
                   8397:     return $result;
                   8398: }
1.1044    www      8399: 
1.317     albertel 8400: sub js_ready {
                   8401:     my ($result) = @_;
                   8402: 
1.323     albertel 8403:     $result =~ s/[\n\r]/ /xmsg;
                   8404:     $result =~ s/\\/\\\\/xmsg;
                   8405:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8406:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8407:     
                   8408:     return $result;
                   8409: }
                   8410: 
1.315     albertel 8411: sub validate_page {
                   8412:     if (  exists($env{'internal.start_page'})
1.316     albertel 8413: 	  &&     $env{'internal.start_page'} > 1) {
                   8414: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8415: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8416: 				 $ENV{'request.filename'});
1.315     albertel 8417:     }
                   8418:     if (  exists($env{'internal.end_page'})
1.316     albertel 8419: 	  &&     $env{'internal.end_page'} > 1) {
                   8420: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8421: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8422: 				 $env{'request.filename'});
1.315     albertel 8423:     }
                   8424:     if (     exists($env{'internal.start_page'})
                   8425: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8426: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8427: 				 $env{'request.filename'});
1.315     albertel 8428:     }
                   8429:     if (   ! exists($env{'internal.start_page'})
                   8430: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8431: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8432: 				 $env{'request.filename'});
1.315     albertel 8433:     }
1.306     albertel 8434: }
1.315     albertel 8435: 
1.996     www      8436: 
                   8437: sub start_scrollbox {
1.1140    raeburn  8438:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8439:     unless ($outerwidth) { $outerwidth='520px'; }
                   8440:     unless ($width) { $width='500px'; }
                   8441:     unless ($height) { $height='200px'; }
1.1075    raeburn  8442:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8443:     if ($id ne '') {
1.1140    raeburn  8444:         $table_id = ' id="table_'.$id.'"';
1.1137    raeburn  8445:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8446:     }
1.1075    raeburn  8447:     if ($bgcolor ne '') {
                   8448:         $tdcol = "background-color: $bgcolor;";
                   8449:     }
1.1137    raeburn  8450:     my $nicescroll_js;
                   8451:     if ($env{'browser.mobile'}) {
1.1140    raeburn  8452:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8453:     }
                   8454:     return <<"END";
                   8455: $nicescroll_js
                   8456: 
                   8457: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
                   8458: <div style="overflow:auto; width:$width; height:$height;"$div_id>
                   8459: END
                   8460: }
                   8461: 
                   8462: sub end_scrollbox {
                   8463:     return '</div></td></tr></table>';
                   8464: }
                   8465: 
                   8466: sub nicescroll_javascript {
                   8467:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8468:     my %options;
                   8469:     if (ref($cursor) eq 'HASH') {
                   8470:         %options = %{$cursor};
                   8471:     }
                   8472:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8473:         $options{'railalign'} = 'left';
                   8474:     }
                   8475:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8476:         my $function  = &get_users_function();
                   8477:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
1.1138    raeburn  8478:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
1.1140    raeburn  8479:             $options{'cursorcolor'} = '#00F';
1.1138    raeburn  8480:         }
1.1140    raeburn  8481:     }
                   8482:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8483:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
1.1138    raeburn  8484:             $options{'cursoropacity'}='1.0';
                   8485:         }
1.1140    raeburn  8486:     } else {
                   8487:         $options{'cursoropacity'}='1.0';
                   8488:     }
                   8489:     if ($options{'cursorfixedheight'} eq 'none') {
                   8490:         delete($options{'cursorfixedheight'});
                   8491:     } else {
                   8492:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8493:     }
                   8494:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8495:         delete($options{'railoffset'});
                   8496:     }
                   8497:     my @niceoptions;
                   8498:     while (my($key,$value) = each(%options)) {
                   8499:         if ($value =~ /^\{.+\}$/) {
                   8500:             push(@niceoptions,$key.':'.$value);
1.1138    raeburn  8501:         } else {
1.1140    raeburn  8502:             push(@niceoptions,$key.':"'.$value.'"');
1.1138    raeburn  8503:         }
1.1140    raeburn  8504:     }
                   8505:     my $nicescroll_js = '
1.1137    raeburn  8506: $(document).ready(
1.1140    raeburn  8507:       function() {
                   8508:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8509:       }
1.1137    raeburn  8510: );
                   8511: ';
1.1140    raeburn  8512:     if ($framecheck) {
                   8513:         $nicescroll_js .= '
                   8514: function expand_div(caller) {
                   8515:     if (top === self) {
                   8516:         document.getElementById("'.$id.'").style.width = "auto";
                   8517:         document.getElementById("'.$id.'").style.height = "auto";
                   8518:     } else {
                   8519:         try {
                   8520:             if (parent.frames) {
                   8521:                 if (parent.frames.length > 1) {
                   8522:                     var framesrc = parent.frames[1].location.href;
                   8523:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8524:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8525:                         document.getElementById("'.$id.'").style.width = "auto";
                   8526:                         document.getElementById("'.$id.'").style.height = "auto";
                   8527:                     }
                   8528:                 }
                   8529:             }
                   8530:         } catch (e) {
                   8531:             return;
                   8532:         }
1.1137    raeburn  8533:     }
1.1140    raeburn  8534:     return;
1.996     www      8535: }
1.1140    raeburn  8536: ';
                   8537:     }
                   8538:     if ($needjsready) {
                   8539:         $nicescroll_js = '
                   8540: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8541:     } else {
                   8542:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8543:     }
                   8544:     return $nicescroll_js;
1.996     www      8545: }
                   8546: 
1.318     albertel 8547: sub simple_error_page {
1.1150    bisitz   8548:     my ($r,$title,$msg,$args) = @_;
1.1151    raeburn  8549:     if (ref($args) eq 'HASH') {
                   8550:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8551:     } else {
                   8552:         $msg = &mt($msg);
                   8553:     }
1.1150    bisitz   8554: 
1.318     albertel 8555:     my $page =
                   8556: 	&Apache::loncommon::start_page($title).
1.1150    bisitz   8557: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8558: 	&Apache::loncommon::end_page();
                   8559:     if (ref($r)) {
                   8560: 	$r->print($page);
1.327     albertel 8561: 	return;
1.318     albertel 8562:     }
                   8563:     return $page;
                   8564: }
1.347     albertel 8565: 
                   8566: {
1.610     albertel 8567:     my @row_count;
1.961     onken    8568: 
                   8569:     sub start_data_table_count {
                   8570:         unshift(@row_count, 0);
                   8571:         return;
                   8572:     }
                   8573: 
                   8574:     sub end_data_table_count {
                   8575:         shift(@row_count);
                   8576:         return;
                   8577:     }
                   8578: 
1.347     albertel 8579:     sub start_data_table {
1.1018    raeburn  8580: 	my ($add_class,$id) = @_;
1.422     albertel 8581: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8582:         my $table_id;
                   8583:         if (defined($id)) {
                   8584:             $table_id = ' id="'.$id.'"';
                   8585:         }
1.961     onken    8586: 	&start_data_table_count();
1.1018    raeburn  8587: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8588:     }
                   8589: 
                   8590:     sub end_data_table {
1.961     onken    8591: 	&end_data_table_count();
1.389     albertel 8592: 	return '</table>'."\n";;
1.347     albertel 8593:     }
                   8594: 
                   8595:     sub start_data_table_row {
1.974     wenzelju 8596: 	my ($add_class, $id) = @_;
1.610     albertel 8597: 	$row_count[0]++;
                   8598: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8599: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8600:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8601:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8602:     }
1.471     banghart 8603:     
                   8604:     sub continue_data_table_row {
1.974     wenzelju 8605: 	my ($add_class, $id) = @_;
1.610     albertel 8606: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8607: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8608:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8609:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8610:     }
1.347     albertel 8611: 
                   8612:     sub end_data_table_row {
1.389     albertel 8613: 	return '</tr>'."\n";;
1.347     albertel 8614:     }
1.367     www      8615: 
1.421     albertel 8616:     sub start_data_table_empty_row {
1.707     bisitz   8617: #	$row_count[0]++;
1.421     albertel 8618: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8619:     }
                   8620: 
                   8621:     sub end_data_table_empty_row {
                   8622: 	return '</tr>'."\n";;
                   8623:     }
                   8624: 
1.367     www      8625:     sub start_data_table_header_row {
1.389     albertel 8626: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8627:     }
                   8628: 
                   8629:     sub end_data_table_header_row {
1.389     albertel 8630: 	return '</tr>'."\n";;
1.367     www      8631:     }
1.890     droeschl 8632: 
                   8633:     sub data_table_caption {
                   8634:         my $caption = shift;
                   8635:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8636:     }
1.347     albertel 8637: }
                   8638: 
1.548     albertel 8639: =pod
                   8640: 
                   8641: =item * &inhibit_menu_check($arg)
                   8642: 
                   8643: Checks for a inhibitmenu state and generates output to preserve it
                   8644: 
                   8645: Inputs:         $arg - can be any of
                   8646:                      - undef - in which case the return value is a string 
                   8647:                                to add  into arguments list of a uri
                   8648:                      - 'input' - in which case the return value is a HTML
                   8649:                                  <form> <input> field of type hidden to
                   8650:                                  preserve the value
                   8651:                      - a url - in which case the return value is the url with
                   8652:                                the neccesary cgi args added to preserve the
                   8653:                                inhibitmenu state
                   8654:                      - a ref to a url - no return value, but the string is
                   8655:                                         updated to include the neccessary cgi
                   8656:                                         args to preserve the inhibitmenu state
                   8657: 
                   8658: =cut
                   8659: 
                   8660: sub inhibit_menu_check {
                   8661:     my ($arg) = @_;
                   8662:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8663:     if ($arg eq 'input') {
                   8664: 	if ($env{'form.inhibitmenu'}) {
                   8665: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8666: 	} else {
                   8667: 	    return
                   8668: 	}
                   8669:     }
                   8670:     if ($env{'form.inhibitmenu'}) {
                   8671: 	if (ref($arg)) {
                   8672: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8673: 	} elsif ($arg eq '') {
                   8674: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8675: 	} else {
                   8676: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8677: 	}
                   8678:     }
                   8679:     if (!ref($arg)) {
                   8680: 	return $arg;
                   8681:     }
                   8682: }
                   8683: 
1.251     albertel 8684: ###############################################
1.182     matthew  8685: 
                   8686: =pod
                   8687: 
1.549     albertel 8688: =back
                   8689: 
                   8690: =head1 User Information Routines
                   8691: 
                   8692: =over 4
                   8693: 
1.405     albertel 8694: =item * &get_users_function()
1.182     matthew  8695: 
                   8696: Used by &bodytag to determine the current users primary role.
                   8697: Returns either 'student','coordinator','admin', or 'author'.
                   8698: 
                   8699: =cut
                   8700: 
                   8701: ###############################################
                   8702: sub get_users_function {
1.815     tempelho 8703:     my $function = 'norole';
1.818     tempelho 8704:     if ($env{'request.role'}=~/^(st)/) {
                   8705:         $function='student';
                   8706:     }
1.907     raeburn  8707:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8708:         $function='coordinator';
                   8709:     }
1.258     albertel 8710:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8711:         $function='admin';
                   8712:     }
1.826     bisitz   8713:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8714:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8715:         $function='author';
                   8716:     }
                   8717:     return $function;
1.54      www      8718: }
1.99      www      8719: 
                   8720: ###############################################
                   8721: 
1.233     raeburn  8722: =pod
                   8723: 
1.821     raeburn  8724: =item * &show_course()
                   8725: 
                   8726: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8727: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8728: 
                   8729: Inputs:
                   8730: None
                   8731: 
                   8732: Outputs:
                   8733: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8734: 
                   8735: =cut
                   8736: 
                   8737: ###############################################
                   8738: sub show_course {
                   8739:     my $course = !$env{'user.adv'};
                   8740:     if (!$env{'user.adv'}) {
                   8741:         foreach my $env (keys(%env)) {
                   8742:             next if ($env !~ m/^user\.priv\./);
                   8743:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8744:                 $course = 0;
                   8745:                 last;
                   8746:             }
                   8747:         }
                   8748:     }
                   8749:     return $course;
                   8750: }
                   8751: 
                   8752: ###############################################
                   8753: 
                   8754: =pod
                   8755: 
1.542     raeburn  8756: =item * &check_user_status()
1.274     raeburn  8757: 
                   8758: Determines current status of supplied role for a
                   8759: specific user. Roles can be active, previous or future.
                   8760: 
                   8761: Inputs: 
                   8762: user's domain, user's username, course's domain,
1.375     raeburn  8763: course's number, optional section ID.
1.274     raeburn  8764: 
                   8765: Outputs:
                   8766: role status: active, previous or future. 
                   8767: 
                   8768: =cut
                   8769: 
                   8770: sub check_user_status {
1.412     raeburn  8771:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8772:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1202    raeburn  8773:     my @uroles = keys(%userinfo);
1.274     raeburn  8774:     my $srchstr;
                   8775:     my $active_chk = 'none';
1.412     raeburn  8776:     my $now = time;
1.274     raeburn  8777:     if (@uroles > 0) {
1.908     raeburn  8778:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8779:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8780:         } else {
1.412     raeburn  8781:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8782:         }
                   8783:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8784:             my $role_end = 0;
                   8785:             my $role_start = 0;
                   8786:             $active_chk = 'active';
1.412     raeburn  8787:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8788:                 $role_end = $1;
                   8789:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8790:                     $role_start = $1;
1.274     raeburn  8791:                 }
                   8792:             }
                   8793:             if ($role_start > 0) {
1.412     raeburn  8794:                 if ($now < $role_start) {
1.274     raeburn  8795:                     $active_chk = 'future';
                   8796:                 }
                   8797:             }
                   8798:             if ($role_end > 0) {
1.412     raeburn  8799:                 if ($now > $role_end) {
1.274     raeburn  8800:                     $active_chk = 'previous';
                   8801:                 }
                   8802:             }
                   8803:         }
                   8804:     }
                   8805:     return $active_chk;
                   8806: }
                   8807: 
                   8808: ###############################################
                   8809: 
                   8810: =pod
                   8811: 
1.405     albertel 8812: =item * &get_sections()
1.233     raeburn  8813: 
                   8814: Determines all the sections for a course including
                   8815: sections with students and sections containing other roles.
1.419     raeburn  8816: Incoming parameters: 
                   8817: 
                   8818: 1. domain
                   8819: 2. course number 
                   8820: 3. reference to array containing roles for which sections should 
                   8821: be gathered (optional).
                   8822: 4. reference to array containing status types for which sections 
                   8823: should be gathered (optional).
                   8824: 
                   8825: If the third argument is undefined, sections are gathered for any role. 
                   8826: If the fourth argument is undefined, sections are gathered for any status.
                   8827: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8828:  
1.374     raeburn  8829: Returns section hash (keys are section IDs, values are
                   8830: number of users in each section), subject to the
1.419     raeburn  8831: optional roles filter, optional status filter 
1.233     raeburn  8832: 
                   8833: =cut
                   8834: 
                   8835: ###############################################
                   8836: sub get_sections {
1.419     raeburn  8837:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8838:     if (!defined($cdom) || !defined($cnum)) {
                   8839:         my $cid =  $env{'request.course.id'};
                   8840: 
                   8841: 	return if (!defined($cid));
                   8842: 
                   8843:         $cdom = $env{'course.'.$cid.'.domain'};
                   8844:         $cnum = $env{'course.'.$cid.'.num'};
                   8845:     }
                   8846: 
                   8847:     my %sectioncount;
1.419     raeburn  8848:     my $now = time;
1.240     albertel 8849: 
1.1118    raeburn  8850:     my $check_students = 1;
                   8851:     my $only_students = 0;
                   8852:     if (ref($possible_roles) eq 'ARRAY') {
                   8853:         if (grep(/^st$/,@{$possible_roles})) {
                   8854:             if (@{$possible_roles} == 1) {
                   8855:                 $only_students = 1;
                   8856:             }
                   8857:         } else {
                   8858:             $check_students = 0;
                   8859:         }
                   8860:     }
                   8861: 
                   8862:     if ($check_students) { 
1.276     albertel 8863: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8864: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8865: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8866:         my $start_index = &Apache::loncoursedata::CL_START();
                   8867:         my $end_index = &Apache::loncoursedata::CL_END();
                   8868:         my $status;
1.366     albertel 8869: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8870: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8871: 				                     $data->[$status_index],
                   8872:                                                      $data->[$start_index],
                   8873:                                                      $data->[$end_index]);
                   8874:             if ($stu_status eq 'Active') {
                   8875:                 $status = 'active';
                   8876:             } elsif ($end < $now) {
                   8877:                 $status = 'previous';
                   8878:             } elsif ($start > $now) {
                   8879:                 $status = 'future';
                   8880:             } 
                   8881: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8882:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8883:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8884: 		    $sectioncount{$section}++;
                   8885:                 }
1.240     albertel 8886: 	    }
                   8887: 	}
                   8888:     }
1.1118    raeburn  8889:     if ($only_students) {
                   8890:         return %sectioncount;
                   8891:     }
1.240     albertel 8892:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8893:     foreach my $user (sort(keys(%courseroles))) {
                   8894: 	if ($user !~ /^(\w{2})/) { next; }
                   8895: 	my ($role) = ($user =~ /^(\w{2})/);
                   8896: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8897: 	my ($section,$status);
1.240     albertel 8898: 	if ($role eq 'cr' &&
                   8899: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8900: 	    $section=$1;
                   8901: 	}
                   8902: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8903: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8904:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8905:         if ($end == -1 && $start == -1) {
                   8906:             next; #deleted role
                   8907:         }
                   8908:         if (!defined($possible_status)) { 
                   8909:             $sectioncount{$section}++;
                   8910:         } else {
                   8911:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8912:                 $status = 'active';
                   8913:             } elsif ($end < $now) {
                   8914:                 $status = 'future';
                   8915:             } elsif ($start > $now) {
                   8916:                 $status = 'previous';
                   8917:             }
                   8918:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8919:                 $sectioncount{$section}++;
                   8920:             }
                   8921:         }
1.233     raeburn  8922:     }
1.366     albertel 8923:     return %sectioncount;
1.233     raeburn  8924: }
                   8925: 
1.274     raeburn  8926: ###############################################
1.294     raeburn  8927: 
                   8928: =pod
1.405     albertel 8929: 
                   8930: =item * &get_course_users()
                   8931: 
1.275     raeburn  8932: Retrieves usernames:domains for users in the specified course
                   8933: with specific role(s), and access status. 
                   8934: 
                   8935: Incoming parameters:
1.277     albertel 8936: 1. course domain
                   8937: 2. course number
                   8938: 3. access status: users must have - either active, 
1.275     raeburn  8939: previous, future, or all.
1.277     albertel 8940: 4. reference to array of permissible roles
1.288     raeburn  8941: 5. reference to array of section restrictions (optional)
                   8942: 6. reference to results object (hash of hashes).
                   8943: 7. reference to optional userdata hash
1.609     raeburn  8944: 8. reference to optional statushash
1.630     raeburn  8945: 9. flag if privileged users (except those set to unhide in
                   8946:    course settings) should be excluded    
1.609     raeburn  8947: Keys of top level results hash are roles.
1.275     raeburn  8948: Keys of inner hashes are username:domain, with 
                   8949: values set to access type.
1.288     raeburn  8950: Optional userdata hash returns an array with arguments in the 
                   8951: same order as loncoursedata::get_classlist() for student data.
                   8952: 
1.609     raeburn  8953: Optional statushash returns
                   8954: 
1.288     raeburn  8955: Entries for end, start, section and status are blank because
                   8956: of the possibility of multiple values for non-student roles.
                   8957: 
1.275     raeburn  8958: =cut
1.405     albertel 8959: 
1.275     raeburn  8960: ###############################################
1.405     albertel 8961: 
1.275     raeburn  8962: sub get_course_users {
1.630     raeburn  8963:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8964:     my %idx = ();
1.419     raeburn  8965:     my %seclists;
1.288     raeburn  8966: 
                   8967:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8968:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8969:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8970:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8971:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8972:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8973:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8974:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8975: 
1.290     albertel 8976:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8977:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8978:         my $now = time;
1.277     albertel 8979:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8980:             my $match = 0;
1.412     raeburn  8981:             my $secmatch = 0;
1.419     raeburn  8982:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8983:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8984:             if ($section eq '') {
                   8985:                 $section = 'none';
                   8986:             }
1.291     albertel 8987:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8988:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8989:                     $secmatch = 1;
                   8990:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8991:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8992:                         $secmatch = 1;
                   8993:                     }
                   8994:                 } else {  
1.419     raeburn  8995: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8996: 		        $secmatch = 1;
                   8997:                     }
1.290     albertel 8998: 		}
1.412     raeburn  8999:                 if (!$secmatch) {
                   9000:                     next;
                   9001:                 }
1.419     raeburn  9002:             }
1.275     raeburn  9003:             if (defined($$types{'active'})) {
1.288     raeburn  9004:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9005:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9006:                     $match = 1;
1.275     raeburn  9007:                 }
                   9008:             }
                   9009:             if (defined($$types{'previous'})) {
1.609     raeburn  9010:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9011:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9012:                     $match = 1;
1.275     raeburn  9013:                 }
                   9014:             }
                   9015:             if (defined($$types{'future'})) {
1.609     raeburn  9016:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9017:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9018:                     $match = 1;
1.275     raeburn  9019:                 }
                   9020:             }
1.609     raeburn  9021:             if ($match) {
                   9022:                 push(@{$seclists{$student}},$section);
                   9023:                 if (ref($userdata) eq 'HASH') {
                   9024:                     $$userdata{$student} = $$classlist{$student};
                   9025:                 }
                   9026:                 if (ref($statushash) eq 'HASH') {
                   9027:                     $statushash->{$student}{'st'}{$section} = $status;
                   9028:                 }
1.288     raeburn  9029:             }
1.275     raeburn  9030:         }
                   9031:     }
1.412     raeburn  9032:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9033:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9034:         my $now = time;
1.609     raeburn  9035:         my %displaystatus = ( previous => 'Expired',
                   9036:                               active   => 'Active',
                   9037:                               future   => 'Future',
                   9038:                             );
1.1121    raeburn  9039:         my (%nothide,@possdoms);
1.630     raeburn  9040:         if ($hidepriv) {
                   9041:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9042:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9043:                 if ($user !~ /:/) {
                   9044:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9045:                 } else {
                   9046:                     $nothide{$user} = 1;
                   9047:                 }
                   9048:             }
1.1121    raeburn  9049:             my @possdoms = ($cdom);
                   9050:             if ($coursehash{'checkforpriv'}) {
                   9051:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9052:             }
1.630     raeburn  9053:         }
1.439     raeburn  9054:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9055:             my $match = 0;
1.412     raeburn  9056:             my $secmatch = 0;
1.439     raeburn  9057:             my $status;
1.412     raeburn  9058:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9059:             $user =~ s/:$//;
1.439     raeburn  9060:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9061:             if ($end == -1 || $start == -1) {
                   9062:                 next;
                   9063:             }
                   9064:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9065:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9066:                 my ($uname,$udom) = split(/:/,$user);
                   9067:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9068:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9069:                         $secmatch = 1;
                   9070:                     } elsif ($usec eq '') {
1.420     albertel 9071:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9072:                             $secmatch = 1;
                   9073:                         }
                   9074:                     } else {
                   9075:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9076:                             $secmatch = 1;
                   9077:                         }
                   9078:                     }
                   9079:                     if (!$secmatch) {
                   9080:                         next;
                   9081:                     }
1.288     raeburn  9082:                 }
1.419     raeburn  9083:                 if ($usec eq '') {
                   9084:                     $usec = 'none';
                   9085:                 }
1.275     raeburn  9086:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9087:                     if ($hidepriv) {
1.1121    raeburn  9088:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9089:                             (!$nothide{$uname.':'.$udom})) {
                   9090:                             next;
                   9091:                         }
                   9092:                     }
1.503     raeburn  9093:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9094:                         $status = 'previous';
                   9095:                     } elsif ($start > $now) {
                   9096:                         $status = 'future';
                   9097:                     } else {
                   9098:                         $status = 'active';
                   9099:                     }
1.277     albertel 9100:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9101:                         if ($status eq $type) {
1.420     albertel 9102:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9103:                                 push(@{$$users{$role}{$user}},$type);
                   9104:                             }
1.288     raeburn  9105:                             $match = 1;
                   9106:                         }
                   9107:                     }
1.419     raeburn  9108:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9109:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9110: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9111:                         }
1.420     albertel 9112:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9113:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9114:                         }
1.609     raeburn  9115:                         if (ref($statushash) eq 'HASH') {
                   9116:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9117:                         }
1.275     raeburn  9118:                     }
                   9119:                 }
                   9120:             }
                   9121:         }
1.290     albertel 9122:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9123:             if ((defined($cdom)) && (defined($cnum))) {
                   9124:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9125:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9126:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9127:                     next if ($owner eq '');
                   9128:                     my ($ownername,$ownerdom);
                   9129:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9130:                         $ownername = $1;
                   9131:                         $ownerdom = $2;
                   9132:                     } else {
                   9133:                         $ownername = $owner;
                   9134:                         $ownerdom = $cdom;
                   9135:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9136:                     }
                   9137:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9138:                     if (defined($userdata) && 
1.609     raeburn  9139: 			!exists($$userdata{$owner})) {
                   9140: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9141:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9142:                             push(@{$seclists{$owner}},'none');
                   9143:                         }
                   9144:                         if (ref($statushash) eq 'HASH') {
                   9145:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9146:                         }
1.290     albertel 9147: 		    }
1.279     raeburn  9148:                 }
                   9149:             }
                   9150:         }
1.419     raeburn  9151:         foreach my $user (keys(%seclists)) {
                   9152:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9153:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9154:         }
1.275     raeburn  9155:     }
                   9156:     return;
                   9157: }
                   9158: 
1.288     raeburn  9159: sub get_user_info {
                   9160:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9161:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9162: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9163:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9164:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9165:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9166:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9167:     return;
                   9168: }
1.275     raeburn  9169: 
1.472     raeburn  9170: ###############################################
                   9171: 
                   9172: =pod
                   9173: 
                   9174: =item * &get_user_quota()
                   9175: 
1.1134    raeburn  9176: Retrieves quota assigned for storage of user files.
                   9177: Default is to report quota for portfolio files.
1.472     raeburn  9178: 
                   9179: Incoming parameters:
                   9180: 1. user's username
                   9181: 2. user's domain
1.1134    raeburn  9182: 3. quota name - portfolio, author, or course
1.1136    raeburn  9183:    (if no quota name provided, defaults to portfolio).
1.1165    raeburn  9184: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1136    raeburn  9185:    course
1.472     raeburn  9186: 
                   9187: Returns:
1.1163    raeburn  9188: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9189: 2. (Optional) Type of setting: custom or default
                   9190:    (individually assigned or default for user's 
                   9191:    institutional status).
                   9192: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9193:    or student - types as defined in localenroll::inst_usertypes 
                   9194:    for user's domain, which determines default quota for user.
                   9195: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9196: 
                   9197: If a value has been stored in the user's environment, 
1.536     raeburn  9198: it will return that, otherwise it returns the maximal default
1.1134    raeburn  9199: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9200: 
                   9201: =cut
                   9202: 
                   9203: ###############################################
                   9204: 
                   9205: 
                   9206: sub get_user_quota {
1.1136    raeburn  9207:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9208:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9209:     if (!defined($udom)) {
                   9210:         $udom = $env{'user.domain'};
                   9211:     }
                   9212:     if (!defined($uname)) {
                   9213:         $uname = $env{'user.name'};
                   9214:     }
                   9215:     if (($udom eq '' || $uname eq '') ||
                   9216:         ($udom eq 'public') && ($uname eq 'public')) {
                   9217:         $quota = 0;
1.536     raeburn  9218:         $quotatype = 'default';
                   9219:         $defquota = 0; 
1.472     raeburn  9220:     } else {
1.536     raeburn  9221:         my $inststatus;
1.1134    raeburn  9222:         if ($quotaname eq 'course') {
                   9223:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9224:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9225:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9226:             } else {
                   9227:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9228:                 $quota = $cenv{'internal.uploadquota'};
                   9229:             }
1.536     raeburn  9230:         } else {
1.1134    raeburn  9231:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9232:                 if ($quotaname eq 'author') {
                   9233:                     $quota = $env{'environment.authorquota'};
                   9234:                 } else {
                   9235:                     $quota = $env{'environment.portfolioquota'};
                   9236:                 }
                   9237:                 $inststatus = $env{'environment.inststatus'};
                   9238:             } else {
                   9239:                 my %userenv = 
                   9240:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9241:                                          'authorquota','inststatus'],$udom,$uname);
                   9242:                 my ($tmp) = keys(%userenv);
                   9243:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9244:                     if ($quotaname eq 'author') {
                   9245:                         $quota = $userenv{'authorquota'};
                   9246:                     } else {
                   9247:                         $quota = $userenv{'portfolioquota'};
                   9248:                     }
                   9249:                     $inststatus = $userenv{'inststatus'};
                   9250:                 } else {
                   9251:                     undef(%userenv);
                   9252:                 }
                   9253:             }
                   9254:         }
                   9255:         if ($quota eq '' || wantarray) {
                   9256:             if ($quotaname eq 'course') {
                   9257:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1165    raeburn  9258:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') || 
                   9259:                     ($crstype eq 'community') || ($crstype eq 'textbook')) { 
1.1136    raeburn  9260:                     $defquota = $domdefs{$crstype.'quota'};
                   9261:                 }
                   9262:                 if ($defquota eq '') {
                   9263:                     $defquota = 500;
                   9264:                 }
1.1134    raeburn  9265:             } else {
                   9266:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9267:             }
                   9268:             if ($quota eq '') {
                   9269:                 $quota = $defquota;
                   9270:                 $quotatype = 'default';
                   9271:             } else {
                   9272:                 $quotatype = 'custom';
                   9273:             }
1.472     raeburn  9274:         }
                   9275:     }
1.536     raeburn  9276:     if (wantarray) {
                   9277:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9278:     } else {
                   9279:         return $quota;
                   9280:     }
1.472     raeburn  9281: }
                   9282: 
                   9283: ###############################################
                   9284: 
                   9285: =pod
                   9286: 
                   9287: =item * &default_quota()
                   9288: 
1.536     raeburn  9289: Retrieves default quota assigned for storage of user portfolio files,
                   9290: given an (optional) user's institutional status.
1.472     raeburn  9291: 
                   9292: Incoming parameters:
1.1142    raeburn  9293: 
1.472     raeburn  9294: 1. domain
1.536     raeburn  9295: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9296:    status types (e.g., faculty, staff, student etc.)
                   9297:    which apply to the user for whom the default is being retrieved.
                   9298:    If the institutional status string in undefined, the domain
1.1134    raeburn  9299:    default quota will be returned.
                   9300: 3.  quota name - portfolio, author, or course
                   9301:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9302: 
                   9303: Returns:
1.1142    raeburn  9304: 
1.1163    raeburn  9305: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9306: 2. (Optional) institutional type which determined the value of the
                   9307:    default quota.
1.472     raeburn  9308: 
                   9309: If a value has been stored in the domain's configuration db,
                   9310: it will return that, otherwise it returns 20 (for backwards 
                   9311: compatibility with domains which have not set up a configuration
1.1163    raeburn  9312: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9313: 
1.536     raeburn  9314: If the user's status includes multiple types (e.g., staff and student),
                   9315: the largest default quota which applies to the user determines the
                   9316: default quota returned.
                   9317: 
1.472     raeburn  9318: =cut
                   9319: 
                   9320: ###############################################
                   9321: 
                   9322: 
                   9323: sub default_quota {
1.1134    raeburn  9324:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9325:     my ($defquota,$settingstatus);
                   9326:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9327:                                             ['quotas'],$udom);
1.1134    raeburn  9328:     my $key = 'defaultquota';
                   9329:     if ($quotaname eq 'author') {
                   9330:         $key = 'authorquota';
                   9331:     }
1.622     raeburn  9332:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9333:         if ($inststatus ne '') {
1.765     raeburn  9334:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9335:             foreach my $item (@statuses) {
1.1134    raeburn  9336:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9337:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9338:                         if ($defquota eq '') {
1.1134    raeburn  9339:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9340:                             $settingstatus = $item;
1.1134    raeburn  9341:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9342:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9343:                             $settingstatus = $item;
                   9344:                         }
                   9345:                     }
1.1134    raeburn  9346:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9347:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9348:                         if ($defquota eq '') {
                   9349:                             $defquota = $quotahash{'quotas'}{$item};
                   9350:                             $settingstatus = $item;
                   9351:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9352:                             $defquota = $quotahash{'quotas'}{$item};
                   9353:                             $settingstatus = $item;
                   9354:                         }
1.536     raeburn  9355:                     }
                   9356:                 }
                   9357:             }
                   9358:         }
                   9359:         if ($defquota eq '') {
1.1134    raeburn  9360:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9361:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9362:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9363:                 $defquota = $quotahash{'quotas'}{'default'};
                   9364:             }
1.536     raeburn  9365:             $settingstatus = 'default';
1.1139    raeburn  9366:             if ($defquota eq '') {
                   9367:                 if ($quotaname eq 'author') {
                   9368:                     $defquota = 500;
                   9369:                 }
                   9370:             }
1.536     raeburn  9371:         }
                   9372:     } else {
                   9373:         $settingstatus = 'default';
1.1134    raeburn  9374:         if ($quotaname eq 'author') {
                   9375:             $defquota = 500;
                   9376:         } else {
                   9377:             $defquota = 20;
                   9378:         }
1.536     raeburn  9379:     }
                   9380:     if (wantarray) {
                   9381:         return ($defquota,$settingstatus);
1.472     raeburn  9382:     } else {
1.536     raeburn  9383:         return $defquota;
1.472     raeburn  9384:     }
                   9385: }
                   9386: 
1.1135    raeburn  9387: ###############################################
                   9388: 
                   9389: =pod
                   9390: 
1.1136    raeburn  9391: =item * &excess_filesize_warning()
1.1135    raeburn  9392: 
                   9393: Returns warning message if upload of file to authoring space, or copying
1.1136    raeburn  9394: of existing file within authoring space will cause quota for the authoring
1.1146    raeburn  9395: space to be exceeded.
1.1136    raeburn  9396: 
                   9397: Same, if upload of a file directly to a course/community via Course Editor
1.1137    raeburn  9398: will cause quota for uploaded content for the course to be exceeded.
1.1135    raeburn  9399: 
1.1165    raeburn  9400: Inputs: 7 
1.1136    raeburn  9401: 1. username or coursenum
1.1135    raeburn  9402: 2. domain
1.1136    raeburn  9403: 3. context ('author' or 'course')
1.1135    raeburn  9404: 4. filename of file for which action is being requested
                   9405: 5. filesize (kB) of file
                   9406: 6. action being taken: copy or upload.
1.1165    raeburn  9407: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1135    raeburn  9408: 
                   9409: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
1.1142    raeburn  9410:          otherwise return null.
                   9411: 
                   9412: =back
1.1135    raeburn  9413: 
                   9414: =cut
                   9415: 
1.1136    raeburn  9416: sub excess_filesize_warning {
1.1165    raeburn  9417:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1136    raeburn  9418:     my $current_disk_usage = 0;
1.1165    raeburn  9419:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1136    raeburn  9420:     if ($context eq 'author') {
                   9421:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9422:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9423:     } else {
                   9424:         foreach my $subdir ('docs','supplemental') {
                   9425:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9426:         }
                   9427:     }
1.1135    raeburn  9428:     $disk_quota = int($disk_quota * 1000);
                   9429:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1179    bisitz   9430:         return '<p class="LC_warning">'.
1.1135    raeburn  9431:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1179    bisitz   9432:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9433:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1135    raeburn  9434:                             $disk_quota,$current_disk_usage).
                   9435:                '</p>';
                   9436:     }
                   9437:     return;
                   9438: }
                   9439: 
                   9440: ###############################################
                   9441: 
                   9442: 
1.1136    raeburn  9443: 
                   9444: 
1.384     raeburn  9445: sub get_secgrprole_info {
                   9446:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9447:     my %sections_count = &get_sections($cdom,$cnum);
                   9448:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9449:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9450:     my @groups = sort(keys(%curr_groups));
                   9451:     my $allroles = [];
                   9452:     my $rolehash;
                   9453:     my $accesshash = {
                   9454:                      active => 'Currently has access',
                   9455:                      future => 'Will have future access',
                   9456:                      previous => 'Previously had access',
                   9457:                   };
                   9458:     if ($needroles) {
                   9459:         $rolehash = {'all' => 'all'};
1.385     albertel 9460:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9461: 	if (&Apache::lonnet::error(%user_roles)) {
                   9462: 	    undef(%user_roles);
                   9463: 	}
                   9464:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9465:             my ($role)=split(/\:/,$item,2);
                   9466:             if ($role eq 'cr') { next; }
                   9467:             if ($role =~ /^cr/) {
                   9468:                 $$rolehash{$role} = (split('/',$role))[3];
                   9469:             } else {
                   9470:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9471:             }
                   9472:         }
                   9473:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9474:             push(@{$allroles},$key);
                   9475:         }
                   9476:         push (@{$allroles},'st');
                   9477:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9478:     }
                   9479:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9480: }
                   9481: 
1.555     raeburn  9482: sub user_picker {
1.994     raeburn  9483:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9484:     my $currdom = $dom;
                   9485:     my %curr_selected = (
                   9486:                         srchin => 'dom',
1.580     raeburn  9487:                         srchby => 'lastname',
1.555     raeburn  9488:                       );
                   9489:     my $srchterm;
1.625     raeburn  9490:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9491:         if ($srch->{'srchby'} ne '') {
                   9492:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9493:         }
                   9494:         if ($srch->{'srchin'} ne '') {
                   9495:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9496:         }
                   9497:         if ($srch->{'srchtype'} ne '') {
                   9498:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9499:         }
                   9500:         if ($srch->{'srchdomain'} ne '') {
                   9501:             $currdom = $srch->{'srchdomain'};
                   9502:         }
                   9503:         $srchterm = $srch->{'srchterm'};
                   9504:     }
                   9505:     my %lt=&Apache::lonlocal::texthash(
1.573     raeburn  9506:                     'usr'       => 'Search criteria',
1.563     raeburn  9507:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9508:                     'uname'     => 'username',
                   9509:                     'lastname'  => 'last name',
1.555     raeburn  9510:                     'lastfirst' => 'last name, first name',
1.558     albertel 9511:                     'crs'       => 'in this course',
1.576     raeburn  9512:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9513:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9514:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9515:                     'exact'     => 'is',
                   9516:                     'contains'  => 'contains',
1.569     raeburn  9517:                     'begins'    => 'begins with',
1.571     raeburn  9518:                     'youm'      => "You must include some text to search for.",
                   9519:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9520:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9521:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9522:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9523:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9524:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9525:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9526:                                        );
1.563     raeburn  9527:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9528:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9529: 
                   9530:     my @srchins = ('crs','dom','alc','instd');
                   9531: 
                   9532:     foreach my $option (@srchins) {
                   9533:         # FIXME 'alc' option unavailable until 
                   9534:         #       loncreateuser::print_user_query_page()
                   9535:         #       has been completed.
                   9536:         next if ($option eq 'alc');
1.880     raeburn  9537:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9538:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9539:         if ($curr_selected{'srchin'} eq $option) {
                   9540:             $srchinsel .= ' 
                   9541:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9542:         } else {
                   9543:             $srchinsel .= '
                   9544:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9545:         }
1.555     raeburn  9546:     }
1.563     raeburn  9547:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9548: 
                   9549:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9550:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9551:         if ($curr_selected{'srchby'} eq $option) {
                   9552:             $srchbysel .= '
                   9553:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9554:         } else {
                   9555:             $srchbysel .= '
                   9556:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9557:          }
                   9558:     }
                   9559:     $srchbysel .= "\n  </select>\n";
                   9560: 
                   9561:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9562:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9563:         if ($curr_selected{'srchtype'} eq $option) {
                   9564:             $srchtypesel .= '
                   9565:    <option value="'.$option.'" selected="selected">'.$lt{$option}.'</option>';
                   9566:         } else {
                   9567:             $srchtypesel .= '
                   9568:    <option value="'.$option.'">'.$lt{$option}.'</option>';
                   9569:         }
                   9570:     }
                   9571:     $srchtypesel .= "\n  </select>\n";
                   9572: 
1.558     albertel 9573:     my ($newuserscript,$new_user_create);
1.994     raeburn  9574:     my $context_dom = $env{'request.role.domain'};
                   9575:     if ($context eq 'requestcrs') {
                   9576:         if ($env{'form.coursedom'} ne '') { 
                   9577:             $context_dom = $env{'form.coursedom'};
                   9578:         }
                   9579:     }
1.556     raeburn  9580:     if ($forcenewuser) {
1.576     raeburn  9581:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9582:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9583:                 if ($cancreate) {
                   9584:                     $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>';
                   9585:                 } else {
1.799     bisitz   9586:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9587:                     my %usertypetext = (
                   9588:                         official   => 'institutional',
                   9589:                         unofficial => 'non-institutional',
                   9590:                     );
1.799     bisitz   9591:                     $new_user_create = '<p class="LC_warning">'
                   9592:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9593:                                       .' '
                   9594:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9595:                                           ,'<a href="'.$helplink.'">','</a>')
                   9596:                                       .'</p><br />';
1.627     raeburn  9597:                 }
1.576     raeburn  9598:             }
                   9599:         }
                   9600: 
1.556     raeburn  9601:         $newuserscript = <<"ENDSCRIPT";
                   9602: 
1.570     raeburn  9603: function setSearch(createnew,callingForm) {
1.556     raeburn  9604:     if (createnew == 1) {
1.570     raeburn  9605:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9606:             if (callingForm.srchby.options[i].value == 'uname') {
                   9607:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9608:             }
                   9609:         }
1.570     raeburn  9610:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9611:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9612: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9613:             }
                   9614:         }
1.570     raeburn  9615:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9616:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9617:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9618:             }
                   9619:         }
1.570     raeburn  9620:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9621:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9622:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9623:             }
                   9624:         }
                   9625:     }
                   9626: }
                   9627: ENDSCRIPT
1.558     albertel 9628: 
1.556     raeburn  9629:     }
                   9630: 
1.555     raeburn  9631:     my $output = <<"END_BLOCK";
1.556     raeburn  9632: <script type="text/javascript">
1.824     bisitz   9633: // <![CDATA[
1.570     raeburn  9634: function validateEntry(callingForm) {
1.558     albertel 9635: 
1.556     raeburn  9636:     var checkok = 1;
1.558     albertel 9637:     var srchin;
1.570     raeburn  9638:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9639: 	if ( callingForm.srchin[i].checked ) {
                   9640: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9641: 	}
                   9642:     }
                   9643: 
1.570     raeburn  9644:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9645:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9646:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9647:     var srchterm =  callingForm.srchterm.value;
                   9648:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9649:     var msg = "";
                   9650: 
                   9651:     if (srchterm == "") {
                   9652:         checkok = 0;
1.571     raeburn  9653:         msg += "$lt{'youm'}\\n";
1.556     raeburn  9654:     }
                   9655: 
1.569     raeburn  9656:     if (srchtype== 'begins') {
                   9657:         if (srchterm.length < 2) {
                   9658:             checkok = 0;
1.571     raeburn  9659:             msg += "$lt{'thte'}\\n";
1.569     raeburn  9660:         }
                   9661:     }
                   9662: 
1.556     raeburn  9663:     if (srchtype== 'contains') {
                   9664:         if (srchterm.length < 3) {
                   9665:             checkok = 0;
1.571     raeburn  9666:             msg += "$lt{'thet'}\\n";
1.556     raeburn  9667:         }
                   9668:     }
                   9669:     if (srchin == 'instd') {
                   9670:         if (srchdomain == '') {
                   9671:             checkok = 0;
1.571     raeburn  9672:             msg += "$lt{'yomc'}\\n";
1.556     raeburn  9673:         }
                   9674:     }
                   9675:     if (srchin == 'dom') {
                   9676:         if (srchdomain == '') {
                   9677:             checkok = 0;
1.571     raeburn  9678:             msg += "$lt{'ymcd'}\\n";
1.556     raeburn  9679:         }
                   9680:     }
                   9681:     if (srchby == 'lastfirst') {
                   9682:         if (srchterm.indexOf(",") == -1) {
                   9683:             checkok = 0;
1.571     raeburn  9684:             msg += "$lt{'whus'}\\n";
1.556     raeburn  9685:         }
                   9686:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9687:             checkok = 0;
1.571     raeburn  9688:             msg += "$lt{'whse'}\\n";
1.556     raeburn  9689:         }
                   9690:     }
                   9691:     if (checkok == 0) {
1.571     raeburn  9692:         alert("$lt{'thfo'}\\n"+msg);
1.556     raeburn  9693:         return;
                   9694:     }
                   9695:     if (checkok == 1) {
1.570     raeburn  9696:         callingForm.submit();
1.556     raeburn  9697:     }
                   9698: }
                   9699: 
                   9700: $newuserscript
                   9701: 
1.824     bisitz   9702: // ]]>
1.556     raeburn  9703: </script>
1.558     albertel 9704: 
                   9705: $new_user_create
                   9706: 
1.555     raeburn  9707: END_BLOCK
1.558     albertel 9708: 
1.876     raeburn  9709:     $output .= &Apache::lonhtmlcommon::start_pick_box().
                   9710:                &Apache::lonhtmlcommon::row_title($lt{'doma'}).
                   9711:                $domform.
                   9712:                &Apache::lonhtmlcommon::row_closure().
                   9713:                &Apache::lonhtmlcommon::row_title($lt{'usr'}).
                   9714:                $srchbysel.
                   9715:                $srchtypesel. 
                   9716:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9717:                $srchinsel.
                   9718:                &Apache::lonhtmlcommon::row_closure(1). 
                   9719:                &Apache::lonhtmlcommon::end_pick_box().
                   9720:                '<br />';
1.555     raeburn  9721:     return $output;
                   9722: }
                   9723: 
1.612     raeburn  9724: sub user_rule_check {
1.615     raeburn  9725:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.612     raeburn  9726:     my $response;
                   9727:     if (ref($usershash) eq 'HASH') {
                   9728:         foreach my $user (keys(%{$usershash})) {
                   9729:             my ($uname,$udom) = split(/:/,$user);
                   9730:             next if ($udom eq '' || $uname eq '');
1.615     raeburn  9731:             my ($id,$newuser);
1.612     raeburn  9732:             if (ref($usershash->{$user}) eq 'HASH') {
1.615     raeburn  9733:                 $newuser = $usershash->{$user}->{'newuser'};
1.612     raeburn  9734:                 $id = $usershash->{$user}->{'id'};
                   9735:             }
                   9736:             my $inst_response;
                   9737:             if (ref($checks) eq 'HASH') {
                   9738:                 if (defined($checks->{'username'})) {
1.615     raeburn  9739:                     ($inst_response,%{$inst_results->{$user}}) = 
1.612     raeburn  9740:                         &Apache::lonnet::get_instuser($udom,$uname);
                   9741:                 } elsif (defined($checks->{'id'})) {
1.615     raeburn  9742:                     ($inst_response,%{$inst_results->{$user}}) =
1.612     raeburn  9743:                         &Apache::lonnet::get_instuser($udom,undef,$id);
                   9744:                 }
1.615     raeburn  9745:             } else {
                   9746:                 ($inst_response,%{$inst_results->{$user}}) =
                   9747:                     &Apache::lonnet::get_instuser($udom,$uname);
                   9748:                 return;
1.612     raeburn  9749:             }
1.615     raeburn  9750:             if (!$got_rules->{$udom}) {
1.612     raeburn  9751:                 my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9752:                                                   ['usercreation'],$udom);
                   9753:                 if (ref($domconfig{'usercreation'}) eq 'HASH') {
1.615     raeburn  9754:                     foreach my $item ('username','id') {
1.612     raeburn  9755:                         if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9756:                             $$curr_rules{$udom}{$item} = 
                   9757:                                 $domconfig{'usercreation'}{$item.'_rule'};
1.585     raeburn  9758:                         }
                   9759:                     }
                   9760:                 }
1.615     raeburn  9761:                 $got_rules->{$udom} = 1;  
1.585     raeburn  9762:             }
1.612     raeburn  9763:             foreach my $item (keys(%{$checks})) {
                   9764:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9765:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9766:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
                   9767:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,$$curr_rules{$udom}{$item});
                   9768:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9769:                                 if ($rule_check{$rule}) {
                   9770:                                     $$rulematch{$user}{$item} = $rule;
                   9771:                                     if ($inst_response eq 'ok') {
1.615     raeburn  9772:                                         if (ref($inst_results) eq 'HASH') {
                   9773:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9774:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9775:                                                     $$alerts{$item}{$udom}{$uname} = 1;
                   9776:                                                 }
1.612     raeburn  9777:                                             }
                   9778:                                         }
1.615     raeburn  9779:                                     }
                   9780:                                     last;
1.585     raeburn  9781:                                 }
                   9782:                             }
                   9783:                         }
                   9784:                     }
                   9785:                 }
                   9786:             }
                   9787:         }
                   9788:     }
1.612     raeburn  9789:     return;
                   9790: }
                   9791: 
                   9792: sub user_rule_formats {
                   9793:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9794:     my %text = ( 
                   9795:                  'username' => 'Usernames',
                   9796:                  'id'       => 'IDs',
                   9797:                );
                   9798:     my $output;
                   9799:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9800:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9801:         if (@{$ruleorder} > 0) {
1.1102    raeburn  9802:             $output = '<br />'.
                   9803:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9804:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9805:                       ' <ul>';
1.612     raeburn  9806:             foreach my $rule (@{$ruleorder}) {
                   9807:                 if (ref($curr_rules) eq 'ARRAY') {
                   9808:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9809:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9810:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9811:                                         $rules->{$rule}{'desc'}.'</li>';
                   9812:                         }
                   9813:                     }
                   9814:                 }
                   9815:             }
                   9816:             $output .= '</ul>';
                   9817:         }
                   9818:     }
                   9819:     return $output;
                   9820: }
                   9821: 
                   9822: sub instrule_disallow_msg {
1.615     raeburn  9823:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9824:     my $response;
                   9825:     my %text = (
                   9826:                   item   => 'username',
                   9827:                   items  => 'usernames',
                   9828:                   match  => 'matches',
                   9829:                   do     => 'does',
                   9830:                   action => 'a username',
                   9831:                   one    => 'one',
                   9832:                );
                   9833:     if ($count > 1) {
                   9834:         $text{'item'} = 'usernames';
                   9835:         $text{'match'} ='match';
                   9836:         $text{'do'} = 'do';
                   9837:         $text{'action'} = 'usernames',
                   9838:         $text{'one'} = 'ones';
                   9839:     }
                   9840:     if ($checkitem eq 'id') {
                   9841:         $text{'items'} = 'IDs';
                   9842:         $text{'item'} = 'ID';
                   9843:         $text{'action'} = 'an ID';
1.615     raeburn  9844:         if ($count > 1) {
                   9845:             $text{'item'} = 'IDs';
                   9846:             $text{'action'} = 'IDs';
                   9847:         }
1.612     raeburn  9848:     }
1.674     bisitz   9849:     $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  9850:     if ($mode eq 'upload') {
                   9851:         if ($checkitem eq 'username') {
                   9852:             $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'}.");
                   9853:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9854:             $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  9855:         }
1.669     raeburn  9856:     } elsif ($mode eq 'selfcreate') {
                   9857:         if ($checkitem eq 'id') {
                   9858:             $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.");
                   9859:         }
1.615     raeburn  9860:     } else {
                   9861:         if ($checkitem eq 'username') {
                   9862:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9863:         } elsif ($checkitem eq 'id') {
                   9864:             $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.");
                   9865:         }
1.612     raeburn  9866:     }
                   9867:     return $response;
1.585     raeburn  9868: }
                   9869: 
1.624     raeburn  9870: sub personal_data_fieldtitles {
                   9871:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9872:                         id => 'Student/Employee ID',
                   9873:                         permanentemail => 'E-mail address',
                   9874:                         lastname => 'Last Name',
                   9875:                         firstname => 'First Name',
                   9876:                         middlename => 'Middle Name',
                   9877:                         generation => 'Generation',
                   9878:                         gen => 'Generation',
1.765     raeburn  9879:                         inststatus => 'Affiliation',
1.624     raeburn  9880:                    );
                   9881:     return %fieldtitles;
                   9882: }
                   9883: 
1.642     raeburn  9884: sub sorted_inst_types {
                   9885:     my ($dom) = @_;
1.1185    raeburn  9886:     my ($usertypes,$order);
                   9887:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9888:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9889:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9890:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9891:     } else {
                   9892:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9893:     }
1.642     raeburn  9894:     my $othertitle = &mt('All users');
                   9895:     if ($env{'request.course.id'}) {
1.668     raeburn  9896:         $othertitle  = &mt('Any users');
1.642     raeburn  9897:     }
                   9898:     my @types;
                   9899:     if (ref($order) eq 'ARRAY') {
                   9900:         @types = @{$order};
                   9901:     }
                   9902:     if (@types == 0) {
                   9903:         if (ref($usertypes) eq 'HASH') {
                   9904:             @types = sort(keys(%{$usertypes}));
                   9905:         }
                   9906:     }
                   9907:     if (keys(%{$usertypes}) > 0) {
                   9908:         $othertitle = &mt('Other users');
                   9909:     }
                   9910:     return ($othertitle,$usertypes,\@types);
                   9911: }
                   9912: 
1.645     raeburn  9913: sub get_institutional_codes {
                   9914:     my ($settings,$allcourses,$LC_code) = @_;
                   9915: # Get complete list of course sections to update
                   9916:     my @currsections = ();
                   9917:     my @currxlists = ();
                   9918:     my $coursecode = $$settings{'internal.coursecode'};
                   9919: 
                   9920:     if ($$settings{'internal.sectionnums'} ne '') {
                   9921:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9922:     }
                   9923: 
                   9924:     if ($$settings{'internal.crosslistings'} ne '') {
                   9925:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9926:     }
                   9927: 
                   9928:     if (@currxlists > 0) {
                   9929:         foreach (@currxlists) {
                   9930:             if (m/^([^:]+):(\w*)$/) {
                   9931:                 unless (grep/^$1$/,@{$allcourses}) {
                   9932:                     push @{$allcourses},$1;
                   9933:                     $$LC_code{$1} = $2;
                   9934:                 }
                   9935:             }
                   9936:         }
                   9937:     }
                   9938:  
                   9939:     if (@currsections > 0) {
                   9940:         foreach (@currsections) {
                   9941:             if (m/^(\w+):(\w*)$/) {
                   9942:                 my $sec = $coursecode.$1;
                   9943:                 my $lc_sec = $2;
                   9944:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9945:                     push @{$allcourses},$sec;
                   9946:                     $$LC_code{$sec} = $lc_sec;
                   9947:                 }
                   9948:             }
                   9949:         }
                   9950:     }
                   9951:     return;
                   9952: }
                   9953: 
1.971     raeburn  9954: sub get_standard_codeitems {
                   9955:     return ('Year','Semester','Department','Number','Section');
                   9956: }
                   9957: 
1.112     bowersj2 9958: =pod
                   9959: 
1.780     raeburn  9960: =head1 Slot Helpers
                   9961: 
                   9962: =over 4
                   9963: 
                   9964: =item * sorted_slots()
                   9965: 
1.1040    raeburn  9966: Sorts an array of slot names in order of an optional sort key,
                   9967: default sort is by slot start time (earliest first). 
1.780     raeburn  9968: 
                   9969: Inputs:
                   9970: 
                   9971: =over 4
                   9972: 
                   9973: slotsarr  - Reference to array of unsorted slot names.
                   9974: 
                   9975: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9976: 
1.1040    raeburn  9977: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9978: 
1.549     albertel 9979: =back
                   9980: 
1.780     raeburn  9981: Returns:
                   9982: 
                   9983: =over 4
                   9984: 
1.1040    raeburn  9985: sorted   - An array of slot names sorted by a specified sort key 
                   9986:            (default sort key is start time of the slot).
1.780     raeburn  9987: 
                   9988: =back
                   9989: 
                   9990: =cut
                   9991: 
                   9992: 
                   9993: sub sorted_slots {
1.1040    raeburn  9994:     my ($slotsarr,$slots,$sortkey) = @_;
                   9995:     if ($sortkey eq '') {
                   9996:         $sortkey = 'starttime';
                   9997:     }
1.780     raeburn  9998:     my @sorted;
                   9999:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10000:         @sorted =
                   10001:             sort {
                   10002:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10003:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10004:                      }
                   10005:                      if (ref($slots->{$a})) { return -1;}
                   10006:                      if (ref($slots->{$b})) { return 1;}
                   10007:                      return 0;
                   10008:                  } @{$slotsarr};
                   10009:     }
                   10010:     return @sorted;
                   10011: }
                   10012: 
1.1040    raeburn  10013: =pod
                   10014: 
                   10015: =item * get_future_slots()
                   10016: 
                   10017: Inputs:
                   10018: 
                   10019: =over 4
                   10020: 
                   10021: cnum - course number
                   10022: 
                   10023: cdom - course domain
                   10024: 
                   10025: now - current UNIX time
                   10026: 
                   10027: symb - optional symb
                   10028: 
                   10029: =back
                   10030: 
                   10031: Returns:
                   10032: 
                   10033: =over 4
                   10034: 
                   10035: sorted_reservable - ref to array of student_schedulable slots currently 
                   10036:                     reservable, ordered by end date of reservation period.
                   10037: 
                   10038: reservable_now - ref to hash of student_schedulable slots currently
                   10039:                  reservable.
                   10040: 
                   10041:     Keys in inner hash are:
                   10042:     (a) symb: either blank or symb to which slot use is restricted.
                   10043:     (b) endreserve: end date of reservation period. 
                   10044: 
                   10045: sorted_future - ref to array of student_schedulable slots reservable in
                   10046:                 the future, ordered by start date of reservation period.
                   10047: 
                   10048: future_reservable - ref to hash of student_schedulable slots reservable
                   10049:                     in the future.
                   10050: 
                   10051:     Keys in inner hash are:
                   10052:     (a) symb: either blank or symb to which slot use is restricted.
                   10053:     (b) startreserve:  start date of reservation period.
                   10054: 
                   10055: =back
                   10056: 
                   10057: =cut
                   10058: 
                   10059: sub get_future_slots {
                   10060:     my ($cnum,$cdom,$now,$symb) = @_;
                   10061:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10062:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10063:     foreach my $slot (keys(%slots)) {
                   10064:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10065:         if ($symb) {
                   10066:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10067:                      ($slots{$slot}->{'symb'} ne $symb));
                   10068:         }
                   10069:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10070:             ($slots{$slot}->{'endtime'} > $now)) {
                   10071:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10072:                 my $userallowed = 0;
                   10073:                 if ($slots{$slot}->{'allowedsections'}) {
                   10074:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10075:                     if (!defined($env{'request.role.sec'})
                   10076:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10077:                         $userallowed=1;
                   10078:                     } else {
                   10079:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10080:                             $userallowed=1;
                   10081:                         }
                   10082:                     }
                   10083:                     unless ($userallowed) {
                   10084:                         if (defined($env{'request.course.groups'})) {
                   10085:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10086:                             foreach my $group (@groups) {
                   10087:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10088:                                     $userallowed=1;
                   10089:                                     last;
                   10090:                                 }
                   10091:                             }
                   10092:                         }
                   10093:                     }
                   10094:                 }
                   10095:                 if ($slots{$slot}->{'allowedusers'}) {
                   10096:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10097:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10098:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10099:                         $userallowed = 1;
                   10100:                     }
                   10101:                 }
                   10102:                 next unless($userallowed);
                   10103:             }
                   10104:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10105:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10106:             my $symb = $slots{$slot}->{'symb'};
                   10107:             if (($startreserve < $now) &&
                   10108:                 (!$endreserve || $endreserve > $now)) {
                   10109:                 my $lastres = $endreserve;
                   10110:                 if (!$lastres) {
                   10111:                     $lastres = $slots{$slot}->{'starttime'};
                   10112:                 }
                   10113:                 $reservable_now{$slot} = {
                   10114:                                            symb       => $symb,
                   10115:                                            endreserve => $lastres
                   10116:                                          };
                   10117:             } elsif (($startreserve > $now) &&
                   10118:                      (!$endreserve || $endreserve > $startreserve)) {
                   10119:                 $future_reservable{$slot} = {
                   10120:                                               symb         => $symb,
                   10121:                                               startreserve => $startreserve
                   10122:                                             };
                   10123:             }
                   10124:         }
                   10125:     }
                   10126:     my @unsorted_reservable = keys(%reservable_now);
                   10127:     if (@unsorted_reservable > 0) {
                   10128:         @sorted_reservable = 
                   10129:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10130:     }
                   10131:     my @unsorted_future = keys(%future_reservable);
                   10132:     if (@unsorted_future > 0) {
                   10133:         @sorted_future =
                   10134:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10135:     }
                   10136:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10137: }
1.780     raeburn  10138: 
                   10139: =pod
                   10140: 
1.1057    foxr     10141: =back
                   10142: 
1.549     albertel 10143: =head1 HTTP Helpers
                   10144: 
                   10145: =over 4
                   10146: 
1.648     raeburn  10147: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10148: 
1.258     albertel 10149: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10150: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10151: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10152: 
                   10153: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10154: $possible_names is an ref to an array of form element names.  As an example:
                   10155: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10156: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10157: 
                   10158: =cut
1.1       albertel 10159: 
1.6       albertel 10160: sub get_unprocessed_cgi {
1.25      albertel 10161:   my ($query,$possible_names)= @_;
1.26      matthew  10162:   # $Apache::lonxml::debug=1;
1.356     albertel 10163:   foreach my $pair (split(/&/,$query)) {
                   10164:     my ($name, $value) = split(/=/,$pair);
1.369     www      10165:     $name = &unescape($name);
1.25      albertel 10166:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10167:       $value =~ tr/+/ /;
                   10168:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10169:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10170:     }
1.16      harris41 10171:   }
1.6       albertel 10172: }
                   10173: 
1.112     bowersj2 10174: =pod
                   10175: 
1.648     raeburn  10176: =item * &cacheheader() 
1.112     bowersj2 10177: 
                   10178: returns cache-controlling header code
                   10179: 
                   10180: =cut
                   10181: 
1.7       albertel 10182: sub cacheheader {
1.258     albertel 10183:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10184:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10185:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10186:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10187:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10188:     return $output;
1.7       albertel 10189: }
                   10190: 
1.112     bowersj2 10191: =pod
                   10192: 
1.648     raeburn  10193: =item * &no_cache($r) 
1.112     bowersj2 10194: 
                   10195: specifies header code to not have cache
                   10196: 
                   10197: =cut
                   10198: 
1.9       albertel 10199: sub no_cache {
1.216     albertel 10200:     my ($r) = @_;
                   10201:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10202: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10203:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10204:     $r->no_cache(1);
                   10205:     $r->header_out("Expires" => $date);
                   10206:     $r->header_out("Pragma" => "no-cache");
1.123     www      10207: }
                   10208: 
                   10209: sub content_type {
1.181     albertel 10210:     my ($r,$type,$charset) = @_;
1.299     foxr     10211:     if ($r) {
                   10212: 	#  Note that printout.pl calls this with undef for $r.
                   10213: 	&no_cache($r);
                   10214:     }
1.258     albertel 10215:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10216:     unless ($charset) {
                   10217: 	$charset=&Apache::lonlocal::current_encoding;
                   10218:     }
                   10219:     if ($charset) { $type.='; charset='.$charset; }
                   10220:     if ($r) {
                   10221: 	$r->content_type($type);
                   10222:     } else {
                   10223: 	print("Content-type: $type\n\n");
                   10224:     }
1.9       albertel 10225: }
1.25      albertel 10226: 
1.112     bowersj2 10227: =pod
                   10228: 
1.648     raeburn  10229: =item * &add_to_env($name,$value) 
1.112     bowersj2 10230: 
1.258     albertel 10231: adds $name to the %env hash with value
1.112     bowersj2 10232: $value, if $name already exists, the entry is converted to an array
                   10233: reference and $value is added to the array.
                   10234: 
                   10235: =cut
                   10236: 
1.25      albertel 10237: sub add_to_env {
                   10238:   my ($name,$value)=@_;
1.258     albertel 10239:   if (defined($env{$name})) {
                   10240:     if (ref($env{$name})) {
1.25      albertel 10241:       #already have multiple values
1.258     albertel 10242:       push(@{ $env{$name} },$value);
1.25      albertel 10243:     } else {
                   10244:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10245:       my $first=$env{$name};
                   10246:       undef($env{$name});
                   10247:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10248:     }
                   10249:   } else {
1.258     albertel 10250:     $env{$name}=$value;
1.25      albertel 10251:   }
1.31      albertel 10252: }
1.149     albertel 10253: 
                   10254: =pod
                   10255: 
1.648     raeburn  10256: =item * &get_env_multiple($name) 
1.149     albertel 10257: 
1.258     albertel 10258: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10259: values may be defined and end up as an array ref.
                   10260: 
                   10261: returns an array of values
                   10262: 
                   10263: =cut
                   10264: 
                   10265: sub get_env_multiple {
                   10266:     my ($name) = @_;
                   10267:     my @values;
1.258     albertel 10268:     if (defined($env{$name})) {
1.149     albertel 10269:         # exists is it an array
1.258     albertel 10270:         if (ref($env{$name})) {
                   10271:             @values=@{ $env{$name} };
1.149     albertel 10272:         } else {
1.258     albertel 10273:             $values[0]=$env{$name};
1.149     albertel 10274:         }
                   10275:     }
                   10276:     return(@values);
                   10277: }
                   10278: 
1.660     raeburn  10279: sub ask_for_embedded_content {
                   10280:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10281:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1085    raeburn  10282:         %currsubfile,%unused,$rem);
1.1071    raeburn  10283:     my $counter = 0;
                   10284:     my $numnew = 0;
1.987     raeburn  10285:     my $numremref = 0;
                   10286:     my $numinvalid = 0;
                   10287:     my $numpathchg = 0;
                   10288:     my $numexisting = 0;
1.1071    raeburn  10289:     my $numunused = 0;
                   10290:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1156    raeburn  10291:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10292:     my $heading = &mt('Upload embedded files');
                   10293:     my $buttontext = &mt('Upload');
                   10294: 
1.1085    raeburn  10295:     if ($env{'request.course.id'}) {
1.1123    raeburn  10296:         if ($actionurl eq '/adm/dependencies') {
                   10297:             $navmap = Apache::lonnavmaps::navmap->new();
                   10298:         }
                   10299:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10300:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1085    raeburn  10301:     }
1.1123    raeburn  10302:     if (($actionurl eq '/adm/portfolio') || 
                   10303:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10304:         my $current_path='/';
                   10305:         if ($env{'form.currentpath'}) {
                   10306:             $current_path = $env{'form.currentpath'};
                   10307:         }
                   10308:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1123    raeburn  10309:             $udom = $cdom;
                   10310:             $uname = $cnum;
1.984     raeburn  10311:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10312:         } else {
                   10313:             $udom = $env{'user.domain'};
                   10314:             $uname = $env{'user.name'};
                   10315:             $url = '/userfiles/portfolio';
                   10316:         }
1.987     raeburn  10317:         $toplevel = $url.'/';
1.984     raeburn  10318:         $url .= $current_path;
                   10319:         $getpropath = 1;
1.987     raeburn  10320:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10321:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10322:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10323:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10324:         $toplevel = $url;
1.984     raeburn  10325:         if ($rest ne '') {
1.987     raeburn  10326:             $url .= $rest;
                   10327:         }
                   10328:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10329:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10330:             $url = $args->{'docs_url'};
                   10331:             $toplevel = $url;
1.1084    raeburn  10332:             if ($args->{'context'} eq 'paste') {
                   10333:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10334:                 ($path) = 
                   10335:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10336:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10337:                 $fileloc =~ s{^/}{};
                   10338:             }
1.1071    raeburn  10339:         }
1.1084    raeburn  10340:     } elsif ($actionurl eq '/adm/dependencies')  {
1.1071    raeburn  10341:         if ($env{'request.course.id'} ne '') {
                   10342:             if (ref($args) eq 'HASH') {
                   10343:                 $url = $args->{'docs_url'};
                   10344:                 $title = $args->{'docs_title'};
1.1126    raeburn  10345:                 $toplevel = $url; 
                   10346:                 unless ($toplevel =~ m{^/}) {
                   10347:                     $toplevel = "/$url";
                   10348:                 }
1.1085    raeburn  10349:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1126    raeburn  10350:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10351:                     $path = $1;
                   10352:                 } else {
                   10353:                     ($path) =
                   10354:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10355:                 }
1.1195    raeburn  10356:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10357:                     $fileloc = $toplevel;
                   10358:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10359:                     my ($udom,$uname,$fname) =
                   10360:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10361:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10362:                 } else {
                   10363:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10364:                 }
1.1071    raeburn  10365:                 $fileloc =~ s{^/}{};
                   10366:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10367:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10368:             }
1.987     raeburn  10369:         }
1.1123    raeburn  10370:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10371:         $udom = $cdom;
                   10372:         $uname = $cnum;
                   10373:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10374:         $toplevel = $url;
                   10375:         $path = $url;
                   10376:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10377:         $fileloc =~ s{^/}{};
1.987     raeburn  10378:     }
1.1126    raeburn  10379:     foreach my $file (keys(%{$allfiles})) {
                   10380:         my $embed_file;
                   10381:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10382:             $embed_file = $1;
                   10383:         } else {
                   10384:             $embed_file = $file;
                   10385:         }
1.1158    raeburn  10386:         my ($absolutepath,$cleaned_file);
                   10387:         if ($embed_file =~ m{^\w+://}) {
                   10388:             $cleaned_file = $embed_file;
1.1147    raeburn  10389:             $newfiles{$cleaned_file} = 1;
                   10390:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10391:         } else {
1.1158    raeburn  10392:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10393:             if ($embed_file =~ m{^/}) {
                   10394:                 $absolutepath = $embed_file;
                   10395:             }
1.1147    raeburn  10396:             if ($cleaned_file =~ m{/}) {
                   10397:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10398:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10399:                 my $item = $fname;
                   10400:                 if ($path ne '') {
                   10401:                     $item = $path.'/'.$fname;
                   10402:                     $subdependencies{$path}{$fname} = 1;
                   10403:                 } else {
                   10404:                     $dependencies{$item} = 1;
                   10405:                 }
                   10406:                 if ($absolutepath) {
                   10407:                     $mapping{$item} = $absolutepath;
                   10408:                 } else {
                   10409:                     $mapping{$item} = $embed_file;
                   10410:                 }
                   10411:             } else {
                   10412:                 $dependencies{$embed_file} = 1;
                   10413:                 if ($absolutepath) {
1.1147    raeburn  10414:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10415:                 } else {
1.1147    raeburn  10416:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10417:                 }
                   10418:             }
1.984     raeburn  10419:         }
                   10420:     }
1.1071    raeburn  10421:     my $dirptr = 16384;
1.984     raeburn  10422:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10423:         $currsubfile{$path} = {};
1.1123    raeburn  10424:         if (($actionurl eq '/adm/portfolio') || 
                   10425:             ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10426:             my ($sublistref,$listerror) =
                   10427:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10428:             if (ref($sublistref) eq 'ARRAY') {
                   10429:                 foreach my $line (@{$sublistref}) {
                   10430:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10431:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10432:                 }
1.984     raeburn  10433:             }
1.987     raeburn  10434:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10435:             if (opendir(my $dir,$url.'/'.$path)) {
                   10436:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10437:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10438:             }
1.1084    raeburn  10439:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10440:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10441:                   ($args->{'context'} eq 'paste')) ||
                   10442:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10443:             if ($env{'request.course.id'} ne '') {
1.1123    raeburn  10444:                 my $dir;
                   10445:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10446:                     $dir = $fileloc;
                   10447:                 } else {
                   10448:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10449:                 }
1.1071    raeburn  10450:                 if ($dir ne '') {
                   10451:                     my ($sublistref,$listerror) =
                   10452:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10453:                     if (ref($sublistref) eq 'ARRAY') {
                   10454:                         foreach my $line (@{$sublistref}) {
                   10455:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10456:                                 undef,$mtime)=split(/\&/,$line,12);
                   10457:                             unless (($testdir&$dirptr) ||
                   10458:                                     ($file_name =~ /^\.\.?$/)) {
                   10459:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10460:                             }
                   10461:                         }
                   10462:                     }
                   10463:                 }
1.984     raeburn  10464:             }
                   10465:         }
                   10466:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10467:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10468:                 my $item = $path.'/'.$file;
                   10469:                 unless ($mapping{$item} eq $item) {
                   10470:                     $pathchanges{$item} = 1;
                   10471:                 }
                   10472:                 $existing{$item} = 1;
                   10473:                 $numexisting ++;
                   10474:             } else {
                   10475:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10476:             }
                   10477:         }
1.1071    raeburn  10478:         if ($actionurl eq '/adm/dependencies') {
                   10479:             foreach my $path (keys(%currsubfile)) {
                   10480:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10481:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10482:                          unless ($subdependencies{$path}{$file}) {
1.1085    raeburn  10483:                              next if (($rem ne '') &&
                   10484:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10485:                                        (ref($navmap) &&
                   10486:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10487:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10488:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10489:                              $unused{$path.'/'.$file} = 1; 
                   10490:                          }
                   10491:                     }
                   10492:                 }
                   10493:             }
                   10494:         }
1.984     raeburn  10495:     }
1.987     raeburn  10496:     my %currfile;
1.1123    raeburn  10497:     if (($actionurl eq '/adm/portfolio') ||
                   10498:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10499:         my ($dirlistref,$listerror) =
                   10500:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10501:         if (ref($dirlistref) eq 'ARRAY') {
                   10502:             foreach my $line (@{$dirlistref}) {
                   10503:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10504:                 $currfile{$file_name} = 1;
                   10505:             }
1.984     raeburn  10506:         }
1.987     raeburn  10507:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10508:         if (opendir(my $dir,$url)) {
1.987     raeburn  10509:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10510:             map {$currfile{$_} = 1;} @dir_list;
                   10511:         }
1.1084    raeburn  10512:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10513:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1123    raeburn  10514:               ($args->{'context'} eq 'paste')) ||
                   10515:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10516:         if ($env{'request.course.id'} ne '') {
                   10517:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10518:             if ($dir ne '') {
                   10519:                 my ($dirlistref,$listerror) =
                   10520:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10521:                 if (ref($dirlistref) eq 'ARRAY') {
                   10522:                     foreach my $line (@{$dirlistref}) {
                   10523:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10524:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10525:                         unless (($testdir&$dirptr) ||
                   10526:                                 ($file_name =~ /^\.\.?$/)) {
                   10527:                             $currfile{$file_name} = [$size,$mtime];
                   10528:                         }
                   10529:                     }
                   10530:                 }
                   10531:             }
                   10532:         }
1.984     raeburn  10533:     }
                   10534:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10535:         if (exists($currfile{$file})) {
1.987     raeburn  10536:             unless ($mapping{$file} eq $file) {
                   10537:                 $pathchanges{$file} = 1;
                   10538:             }
                   10539:             $existing{$file} = 1;
                   10540:             $numexisting ++;
                   10541:         } else {
1.984     raeburn  10542:             $newfiles{$file} = 1;
                   10543:         }
                   10544:     }
1.1071    raeburn  10545:     foreach my $file (keys(%currfile)) {
                   10546:         unless (($file eq $filename) ||
                   10547:                 ($file eq $filename.'.bak') ||
                   10548:                 ($dependencies{$file})) {
1.1085    raeburn  10549:             if ($actionurl eq '/adm/dependencies') {
1.1126    raeburn  10550:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10551:                     next if (($rem ne '') &&
                   10552:                              (($env{"httpref.$rem".$file} ne '') ||
                   10553:                               (ref($navmap) &&
                   10554:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10555:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10556:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10557:                 }
1.1085    raeburn  10558:             }
1.1071    raeburn  10559:             $unused{$file} = 1;
                   10560:         }
                   10561:     }
1.1084    raeburn  10562:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10563:         ($args->{'context'} eq 'paste')) {
                   10564:         $counter = scalar(keys(%existing));
                   10565:         $numpathchg = scalar(keys(%pathchanges));
1.1123    raeburn  10566:         return ($output,$counter,$numpathchg,\%existing);
                   10567:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") && 
                   10568:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10569:         $counter = scalar(keys(%existing));
                   10570:         $numpathchg = scalar(keys(%pathchanges));
                   10571:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1084    raeburn  10572:     }
1.984     raeburn  10573:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10574:         if ($actionurl eq '/adm/dependencies') {
                   10575:             next if ($embed_file =~ m{^\w+://});
                   10576:         }
1.660     raeburn  10577:         $upload_output .= &start_data_table_row().
1.1123    raeburn  10578:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10579:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10580:         unless ($mapping{$embed_file} eq $embed_file) {
1.1123    raeburn  10581:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10582:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10583:         }
1.1123    raeburn  10584:         $upload_output .= '</td>';
1.1071    raeburn  10585:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1123    raeburn  10586:             $upload_output.='<td align="right">'.
                   10587:                             '<span class="LC_info LC_fontsize_medium">'.
                   10588:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10589:             $numremref++;
1.660     raeburn  10590:         } elsif ($args->{'error_on_invalid_names'}
                   10591:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1123    raeburn  10592:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10593:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10594:             $numinvalid++;
1.660     raeburn  10595:         } else {
1.1123    raeburn  10596:             $upload_output .= '<td>'.
                   10597:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10598:                                                      $embed_file,\%mapping,
1.1071    raeburn  10599:                                                      $allfiles,$codebase,'upload');
                   10600:             $counter ++;
                   10601:             $numnew ++;
1.987     raeburn  10602:         }
                   10603:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10604:     }
                   10605:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10606:         if ($actionurl eq '/adm/dependencies') {
                   10607:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10608:             $modify_output .= &start_data_table_row().
                   10609:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10610:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10611:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10612:                               '<td>'.$size.'</td>'.
                   10613:                               '<td>'.$mtime.'</td>'.
                   10614:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10615:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10616:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10617:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10618:                               &embedded_file_element('upload_embedded',$counter,
                   10619:                                                      $embed_file,\%mapping,
                   10620:                                                      $allfiles,$codebase,'modify').
                   10621:                               '</div></td>'.
                   10622:                               &end_data_table_row()."\n";
                   10623:             $counter ++;
                   10624:         } else {
                   10625:             $upload_output .= &start_data_table_row().
1.1123    raeburn  10626:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10627:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10628:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10629:                               &Apache::loncommon::end_data_table_row()."\n";
                   10630:         }
                   10631:     }
                   10632:     my $delidx = $counter;
                   10633:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10634:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10635:         $delete_output .= &start_data_table_row().
                   10636:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10637:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10638:                           '<td>'.$size.'</td>'.
                   10639:                           '<td>'.$mtime.'</td>'.
                   10640:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10641:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10642:                           &embedded_file_element('upload_embedded',$delidx,
                   10643:                                                  $oldfile,\%mapping,$allfiles,
                   10644:                                                  $codebase,'delete').'</td>'.
                   10645:                           &end_data_table_row()."\n"; 
                   10646:         $numunused ++;
                   10647:         $delidx ++;
1.987     raeburn  10648:     }
                   10649:     if ($upload_output) {
                   10650:         $upload_output = &start_data_table().
                   10651:                          $upload_output.
                   10652:                          &end_data_table()."\n";
                   10653:     }
1.1071    raeburn  10654:     if ($modify_output) {
                   10655:         $modify_output = &start_data_table().
                   10656:                          &start_data_table_header_row().
                   10657:                          '<th>'.&mt('File').'</th>'.
                   10658:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10659:                          '<th>'.&mt('Modified').'</th>'.
                   10660:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10661:                          &end_data_table_header_row().
                   10662:                          $modify_output.
                   10663:                          &end_data_table()."\n";
                   10664:     }
                   10665:     if ($delete_output) {
                   10666:         $delete_output = &start_data_table().
                   10667:                          &start_data_table_header_row().
                   10668:                          '<th>'.&mt('File').'</th>'.
                   10669:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10670:                          '<th>'.&mt('Modified').'</th>'.
                   10671:                          '<th>'.&mt('Delete?').'</th>'.
                   10672:                          &end_data_table_header_row().
                   10673:                          $delete_output.
                   10674:                          &end_data_table()."\n";
                   10675:     }
1.987     raeburn  10676:     my $applies = 0;
                   10677:     if ($numremref) {
                   10678:         $applies ++;
                   10679:     }
                   10680:     if ($numinvalid) {
                   10681:         $applies ++;
                   10682:     }
                   10683:     if ($numexisting) {
                   10684:         $applies ++;
                   10685:     }
1.1071    raeburn  10686:     if ($counter || $numunused) {
1.987     raeburn  10687:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10688:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10689:                   $state.'<h3>'.$heading.'</h3>'; 
                   10690:         if ($actionurl eq '/adm/dependencies') {
                   10691:             if ($numnew) {
                   10692:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10693:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10694:                            $upload_output.'<br />'."\n";
                   10695:             }
                   10696:             if ($numexisting) {
                   10697:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10698:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10699:                            $modify_output.'<br />'."\n";
                   10700:                            $buttontext = &mt('Save changes');
                   10701:             }
                   10702:             if ($numunused) {
                   10703:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10704:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10705:                            $delete_output.'<br />'."\n";
                   10706:                            $buttontext = &mt('Save changes');
                   10707:             }
                   10708:         } else {
                   10709:             $output .= $upload_output.'<br />'."\n";
                   10710:         }
                   10711:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10712:                    $counter.'" />'."\n";
                   10713:         if ($actionurl eq '/adm/dependencies') { 
                   10714:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10715:                        $numnew.'" />'."\n";
                   10716:         } elsif ($actionurl eq '') {
1.987     raeburn  10717:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10718:         }
                   10719:     } elsif ($applies) {
                   10720:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10721:         if ($applies > 1) {
                   10722:             $output .=  
1.1123    raeburn  10723:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10724:             if ($numremref) {
                   10725:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10726:             }
                   10727:             if ($numinvalid) {
                   10728:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10729:             }
                   10730:             if ($numexisting) {
                   10731:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10732:             }
                   10733:             $output .= '</ul><br />';
                   10734:         } elsif ($numremref) {
                   10735:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10736:         } elsif ($numinvalid) {
                   10737:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10738:         } elsif ($numexisting) {
                   10739:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10740:         }
                   10741:         $output .= $upload_output.'<br />';
                   10742:     }
                   10743:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10744:     $chgcount = $counter;
1.987     raeburn  10745:     if (keys(%pathchanges) > 0) {
                   10746:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10747:             if ($counter) {
1.987     raeburn  10748:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10749:                                                   $embed_file,\%mapping,
1.1071    raeburn  10750:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10751:             } else {
                   10752:                 $pathchange_output .= 
                   10753:                     &start_data_table_row().
                   10754:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10755:                     $chgcount.'" checked="checked" /></td>'.
                   10756:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10757:                     '<td>'.$embed_file.
                   10758:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10759:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10760:                     '</td>'.&end_data_table_row();
1.660     raeburn  10761:             }
1.987     raeburn  10762:             $numpathchg ++;
                   10763:             $chgcount ++;
1.660     raeburn  10764:         }
                   10765:     }
1.1127    raeburn  10766:     if (($counter) || ($numunused)) {
1.987     raeburn  10767:         if ($numpathchg) {
                   10768:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10769:                        $numpathchg.'" />'."\n";
                   10770:         }
                   10771:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10772:             ($actionurl eq '/adm/imsimport')) {
                   10773:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10774:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10775:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10776:         } elsif ($actionurl eq '/adm/dependencies') {
                   10777:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10778:         }
1.1123    raeburn  10779:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10780:     } elsif ($numpathchg) {
                   10781:         my %pathchange = ();
                   10782:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10783:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10784:             $output .= '<p>'.&mt('or').'</p>'; 
1.1123    raeburn  10785:         }
1.987     raeburn  10786:     }
1.1071    raeburn  10787:     return ($output,$counter,$numpathchg);
1.987     raeburn  10788: }
                   10789: 
1.1147    raeburn  10790: =pod
                   10791: 
                   10792: =item * clean_path($name)
                   10793: 
                   10794: Performs clean-up of directories, subdirectories and filename in an
                   10795: embedded object, referenced in an HTML file which is being uploaded
                   10796: to a course or portfolio, where 
                   10797: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10798: checked.
                   10799: 
                   10800: Clean-up is similar to replacements in lonnet::clean_filename()
                   10801: except each / between sub-directory and next level is preserved.
                   10802: 
                   10803: =cut
                   10804: 
                   10805: sub clean_path {
                   10806:     my ($embed_file) = @_;
                   10807:     $embed_file =~s{^/+}{};
                   10808:     my @contents;
                   10809:     if ($embed_file =~ m{/}) {
                   10810:         @contents = split(/\//,$embed_file);
                   10811:     } else {
                   10812:         @contents = ($embed_file);
                   10813:     }
                   10814:     my $lastidx = scalar(@contents)-1;
                   10815:     for (my $i=0; $i<=$lastidx; $i++) { 
                   10816:         $contents[$i]=~s{\\}{/}g;
                   10817:         $contents[$i]=~s/\s+/\_/g;
                   10818:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10819:         if ($i == $lastidx) {
                   10820:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10821:         }
                   10822:     }
                   10823:     if ($lastidx > 0) {
                   10824:         return join('/',@contents);
                   10825:     } else {
                   10826:         return $contents[0];
                   10827:     }
                   10828: }
                   10829: 
1.987     raeburn  10830: sub embedded_file_element {
1.1071    raeburn  10831:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10832:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10833:                    (ref($codebase) eq 'HASH'));
                   10834:     my $output;
1.1071    raeburn  10835:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10836:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10837:     }
                   10838:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10839:                &escape($embed_file).'" />';
                   10840:     unless (($context eq 'upload_embedded') && 
                   10841:             ($mapping->{$embed_file} eq $embed_file)) {
                   10842:         $output .='
                   10843:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10844:     }
                   10845:     my $attrib;
                   10846:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10847:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10848:     }
                   10849:     $output .=
                   10850:         "\n\t\t".
                   10851:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10852:         $attrib.'" />';
                   10853:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10854:         $output .=
                   10855:             "\n\t\t".
                   10856:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10857:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10858:     }
1.987     raeburn  10859:     return $output;
1.660     raeburn  10860: }
                   10861: 
1.1071    raeburn  10862: sub get_dependency_details {
                   10863:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10864:     my ($size,$mtime,$showsize,$showmtime);
                   10865:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10866:         if ($embed_file =~ m{/}) {
                   10867:             my ($path,$fname) = split(/\//,$embed_file);
                   10868:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10869:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10870:             }
                   10871:         } else {
                   10872:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10873:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10874:             }
                   10875:         }
                   10876:         $showsize = $size/1024.0;
                   10877:         $showsize = sprintf("%.1f",$showsize);
                   10878:         if ($mtime > 0) {
                   10879:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10880:         }
                   10881:     }
                   10882:     return ($showsize,$showmtime);
                   10883: }
                   10884: 
                   10885: sub ask_embedded_js {
                   10886:     return <<"END";
                   10887: <script type="text/javascript"">
                   10888: // <![CDATA[
                   10889: function toggleBrowse(counter) {
                   10890:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10891:     var fileid = document.getElementById('embedded_item_'+counter);
                   10892:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10893:     if (chkboxid.checked == true) {
                   10894:         uploaddivid.style.display='block';
                   10895:     } else {
                   10896:         uploaddivid.style.display='none';
                   10897:         fileid.value = '';
                   10898:     }
                   10899: }
                   10900: // ]]>
                   10901: </script>
                   10902: 
                   10903: END
                   10904: }
                   10905: 
1.661     raeburn  10906: sub upload_embedded {
                   10907:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10908:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10909:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10910:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10911:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10912:         my $orig_uploaded_filename =
                   10913:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10914:         foreach my $type ('orig','ref','attrib','codebase') {
                   10915:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10916:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10917:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10918:             }
                   10919:         }
1.661     raeburn  10920:         my ($path,$fname) =
                   10921:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10922:         # no path, whole string is fname
                   10923:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10924:         $fname = &Apache::lonnet::clean_filename($fname);
                   10925:         # See if there is anything left
                   10926:         next if ($fname eq '');
                   10927: 
                   10928:         # Check if file already exists as a file or directory.
                   10929:         my ($state,$msg);
                   10930:         if ($context eq 'portfolio') {
                   10931:             my $port_path = $dirpath;
                   10932:             if ($group ne '') {
                   10933:                 $port_path = "groups/$group/$port_path";
                   10934:             }
1.987     raeburn  10935:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10936:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10937:                                               $dir_root,$port_path,$disk_quota,
                   10938:                                               $current_disk_usage,$uname,$udom);
                   10939:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10940:                 || $state eq 'file_locked') {
1.661     raeburn  10941:                 $output .= $msg;
                   10942:                 next;
                   10943:             }
                   10944:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10945:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10946:             if ($state eq 'exists') {
                   10947:                 $output .= $msg;
                   10948:                 next;
                   10949:             }
                   10950:         }
                   10951:         # Check if extension is valid
                   10952:         if (($fname =~ /\.(\w+)$/) &&
                   10953:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1155    bisitz   10954:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10955:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10956:             next;
                   10957:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10958:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10959:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10960:             next;
                   10961:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1120    bisitz   10962:             $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  10963:             next;
                   10964:         }
                   10965:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1123    raeburn  10966:         my $subdir = $path;
                   10967:         $subdir =~ s{/+$}{};
1.661     raeburn  10968:         if ($context eq 'portfolio') {
1.984     raeburn  10969:             my $result;
                   10970:             if ($state eq 'existingfile') {
                   10971:                 $result=
                   10972:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1123    raeburn  10973:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10974:             } else {
1.984     raeburn  10975:                 $result=
                   10976:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10977:                                                     $dirpath.
1.1123    raeburn  10978:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10979:                 if ($result !~ m|^/uploaded/|) {
                   10980:                     $output .= '<span class="LC_error">'
                   10981:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10982:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10983:                                .'</span><br />';
                   10984:                     next;
                   10985:                 } else {
1.987     raeburn  10986:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10987:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10988:                 }
1.661     raeburn  10989:             }
1.1123    raeburn  10990:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
1.1126    raeburn  10991:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10992:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10993:             my $result =
1.1126    raeburn  10994:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10995:             if ($result !~ m|^/uploaded/|) {
                   10996:                 $output .= '<span class="LC_error">'
                   10997:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10998:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10999:                            .'</span><br />';
                   11000:                     next;
                   11001:             } else {
                   11002:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11003:                            $path.$fname.'</span>').'<br />';
1.1125    raeburn  11004:                 if ($context eq 'syllabus') {
                   11005:                     &Apache::lonnet::make_public_indefinitely($result);
                   11006:                 }
1.987     raeburn  11007:             }
1.661     raeburn  11008:         } else {
                   11009: # Save the file
                   11010:             my $target = $env{'form.embedded_item_'.$i};
                   11011:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11012:             my $dest = $fullpath.$fname;
                   11013:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11014:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11015:             my $count;
                   11016:             my $filepath = $dir_root;
1.1027    raeburn  11017:             foreach my $subdir (@parts) {
                   11018:                 $filepath .= "/$subdir";
                   11019:                 if (!-e $filepath) {
1.661     raeburn  11020:                     mkdir($filepath,0770);
                   11021:                 }
                   11022:             }
                   11023:             my $fh;
                   11024:             if (!open($fh,'>'.$dest)) {
                   11025:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11026:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11027:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11028:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11029:                            '</span><br />';
                   11030:             } else {
                   11031:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11032:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11033:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11034:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11035:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11036:                               '</span><br />';
                   11037:                 } else {
1.987     raeburn  11038:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11039:                                $url.'</span>').'<br />';
                   11040:                     unless ($context eq 'testbank') {
                   11041:                         $footer .= &mt('View embedded file: [_1]',
                   11042:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11043:                     }
                   11044:                 }
                   11045:                 close($fh);
                   11046:             }
                   11047:         }
                   11048:         if ($env{'form.embedded_ref_'.$i}) {
                   11049:             $pathchange{$i} = 1;
                   11050:         }
                   11051:     }
                   11052:     if ($output) {
                   11053:         $output = '<p>'.$output.'</p>';
                   11054:     }
                   11055:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11056:     $returnflag = 'ok';
1.1071    raeburn  11057:     my $numpathchgs = scalar(keys(%pathchange));
                   11058:     if ($numpathchgs > 0) {
1.987     raeburn  11059:         if ($context eq 'portfolio') {
                   11060:             $output .= '<p>'.&mt('or').'</p>';
                   11061:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11062:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11063:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11064:             $returnflag = 'modify_orightml';
                   11065:         }
                   11066:     }
1.1071    raeburn  11067:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11068: }
                   11069: 
                   11070: sub modify_html_form {
                   11071:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11072:     my $end = 0;
                   11073:     my $modifyform;
                   11074:     if ($context eq 'upload_embedded') {
                   11075:         return unless (ref($pathchange) eq 'HASH');
                   11076:         if ($env{'form.number_embedded_items'}) {
                   11077:             $end += $env{'form.number_embedded_items'};
                   11078:         }
                   11079:         if ($env{'form.number_pathchange_items'}) {
                   11080:             $end += $env{'form.number_pathchange_items'};
                   11081:         }
                   11082:         if ($end) {
                   11083:             for (my $i=0; $i<$end; $i++) {
                   11084:                 if ($i < $env{'form.number_embedded_items'}) {
                   11085:                     next unless($pathchange->{$i});
                   11086:                 }
                   11087:                 $modifyform .=
                   11088:                     &start_data_table_row().
                   11089:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11090:                     'checked="checked" /></td>'.
                   11091:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11092:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11093:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11094:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11095:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11096:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11097:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11098:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11099:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11100:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11101:                     &end_data_table_row();
1.1071    raeburn  11102:             }
1.987     raeburn  11103:         }
                   11104:     } else {
                   11105:         $modifyform = $pathchgtable;
                   11106:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11107:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11108:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11109:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11110:         }
                   11111:     }
                   11112:     if ($modifyform) {
1.1071    raeburn  11113:         if ($actionurl eq '/adm/dependencies') {
                   11114:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11115:         }
1.987     raeburn  11116:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11117:                '<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".
                   11118:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11119:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11120:                '</ol></p>'."\n".'<p>'.
                   11121:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11122:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11123:                &start_data_table()."\n".
                   11124:                &start_data_table_header_row().
                   11125:                '<th>'.&mt('Change?').'</th>'.
                   11126:                '<th>'.&mt('Current reference').'</th>'.
                   11127:                '<th>'.&mt('Required reference').'</th>'.
                   11128:                &end_data_table_header_row()."\n".
                   11129:                $modifyform.
                   11130:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11131:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11132:                '</form>'."\n";
                   11133:     }
                   11134:     return;
                   11135: }
                   11136: 
                   11137: sub modify_html_refs {
1.1123    raeburn  11138:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11139:     my $container;
                   11140:     if ($context eq 'portfolio') {
                   11141:         $container = $env{'form.container'};
                   11142:     } elsif ($context eq 'coursedoc') {
                   11143:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11144:     } elsif ($context eq 'manage_dependencies') {
                   11145:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11146:         $container = "/$container";
1.1123    raeburn  11147:     } elsif ($context eq 'syllabus') {
                   11148:         $container = $url;
1.987     raeburn  11149:     } else {
1.1027    raeburn  11150:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11151:     }
                   11152:     my (%allfiles,%codebase,$output,$content);
                   11153:     my @changes = &get_env_multiple('form.namechange');
1.1126    raeburn  11154:     unless ((@changes > 0) || ($context eq 'syllabus')) {
1.1071    raeburn  11155:         if (wantarray) {
                   11156:             return ('',0,0); 
                   11157:         } else {
                   11158:             return;
                   11159:         }
                   11160:     }
                   11161:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11162:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11163:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11164:             if (wantarray) {
                   11165:                 return ('',0,0);
                   11166:             } else {
                   11167:                 return;
                   11168:             }
                   11169:         } 
1.987     raeburn  11170:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11171:         if ($content eq '-1') {
                   11172:             if (wantarray) {
                   11173:                 return ('',0,0);
                   11174:             } else {
                   11175:                 return;
                   11176:             }
                   11177:         }
1.987     raeburn  11178:     } else {
1.1071    raeburn  11179:         unless ($container =~ /^\Q$dir_root\E/) {
                   11180:             if (wantarray) {
                   11181:                 return ('',0,0);
                   11182:             } else {
                   11183:                 return;
                   11184:             }
                   11185:         } 
1.987     raeburn  11186:         if (open(my $fh,"<$container")) {
                   11187:             $content = join('', <$fh>);
                   11188:             close($fh);
                   11189:         } else {
1.1071    raeburn  11190:             if (wantarray) {
                   11191:                 return ('',0,0);
                   11192:             } else {
                   11193:                 return;
                   11194:             }
1.987     raeburn  11195:         }
                   11196:     }
                   11197:     my ($count,$codebasecount) = (0,0);
                   11198:     my $mm = new File::MMagic;
                   11199:     my $mime_type = $mm->checktype_contents($content);
                   11200:     if ($mime_type eq 'text/html') {
                   11201:         my $parse_result = 
                   11202:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11203:                                                     \%codebase,\$content);
                   11204:         if ($parse_result eq 'ok') {
                   11205:             foreach my $i (@changes) {
                   11206:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11207:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11208:                 if ($allfiles{$ref}) {
                   11209:                     my $newname =  $orig;
                   11210:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11211:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11212:                     if ($attrib_regexp =~ /:/) {
                   11213:                         $attrib_regexp =~ s/\:/|/g;
                   11214:                     }
                   11215:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11216:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11217:                         $count += $numchg;
1.1123    raeburn  11218:                         $allfiles{$newname} = $allfiles{$ref};
1.1148    raeburn  11219:                         delete($allfiles{$ref});
1.987     raeburn  11220:                     }
                   11221:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11222:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11223:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11224:                         $codebasecount ++;
                   11225:                     }
                   11226:                 }
                   11227:             }
1.1123    raeburn  11228:             my $skiprewrites;
1.987     raeburn  11229:             if ($count || $codebasecount) {
                   11230:                 my $saveresult;
1.1071    raeburn  11231:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1123    raeburn  11232:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11233:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11234:                     if ($url eq $container) {
                   11235:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11236:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11237:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11238:                                             $fname.'</span>').'</p>';
1.987     raeburn  11239:                     } else {
                   11240:                          $output = '<p class="LC_error">'.
                   11241:                                    &mt('Error: update failed for: [_1].',
                   11242:                                    '<span class="LC_filename">'.
                   11243:                                    $container.'</span>').'</p>';
                   11244:                     }
1.1123    raeburn  11245:                     if ($context eq 'syllabus') {
                   11246:                         unless ($saveresult eq 'ok') {
                   11247:                             $skiprewrites = 1;
                   11248:                         }
                   11249:                     }
1.987     raeburn  11250:                 } else {
                   11251:                     if (open(my $fh,">$container")) {
                   11252:                         print $fh $content;
                   11253:                         close($fh);
                   11254:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11255:                                   $count,'<span class="LC_filename">'.
                   11256:                                   $container.'</span>').'</p>';
1.661     raeburn  11257:                     } else {
1.987     raeburn  11258:                          $output = '<p class="LC_error">'.
                   11259:                                    &mt('Error: could not update [_1].',
                   11260:                                    '<span class="LC_filename">'.
                   11261:                                    $container.'</span>').'</p>';
1.661     raeburn  11262:                     }
                   11263:                 }
                   11264:             }
1.1123    raeburn  11265:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11266:                 my ($actionurl,$state);
                   11267:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11268:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11269:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11270:                                               \%codebase,
                   11271:                                               {'context' => 'rewrites',
                   11272:                                                'ignore_remote_references' => 1,});
                   11273:                 if (ref($mapping) eq 'HASH') {
                   11274:                     my $rewrites = 0;
                   11275:                     foreach my $key (keys(%{$mapping})) {
                   11276:                         next if ($key =~ m{^https?://});
                   11277:                         my $ref = $mapping->{$key};
                   11278:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11279:                         my $attrib;
                   11280:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11281:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11282:                         }
                   11283:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11284:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11285:                             $rewrites += $numchg;
                   11286:                         }
                   11287:                     }
                   11288:                     if ($rewrites) {
                   11289:                         my $saveresult; 
                   11290:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11291:                         if ($url eq $container) {
                   11292:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11293:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11294:                                             $count,'<span class="LC_filename">'.
                   11295:                                             $fname.'</span>').'</p>';
                   11296:                         } else {
                   11297:                             $output .= '<p class="LC_error">'.
                   11298:                                        &mt('Error: could not update links in [_1].',
                   11299:                                        '<span class="LC_filename">'.
                   11300:                                        $container.'</span>').'</p>';
                   11301: 
                   11302:                         }
                   11303:                     }
                   11304:                 }
                   11305:             }
1.987     raeburn  11306:         } else {
                   11307:             &logthis('Failed to parse '.$container.
                   11308:                      ' to modify references: '.$parse_result);
1.661     raeburn  11309:         }
                   11310:     }
1.1071    raeburn  11311:     if (wantarray) {
                   11312:         return ($output,$count,$codebasecount);
                   11313:     } else {
                   11314:         return $output;
                   11315:     }
1.661     raeburn  11316: }
                   11317: 
                   11318: sub check_for_existing {
                   11319:     my ($path,$fname,$element) = @_;
                   11320:     my ($state,$msg);
                   11321:     if (-d $path.'/'.$fname) {
                   11322:         $state = 'exists';
                   11323:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11324:     } elsif (-e $path.'/'.$fname) {
                   11325:         $state = 'exists';
                   11326:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11327:     }
                   11328:     if ($state eq 'exists') {
                   11329:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11330:     }
                   11331:     return ($state,$msg);
                   11332: }
                   11333: 
                   11334: sub check_for_upload {
                   11335:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11336:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11337:     my $filesize = length($env{'form.'.$element});
                   11338:     if (!$filesize) {
                   11339:         my $msg = '<span class="LC_error">'.
                   11340:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11341:                       '<span class="LC_filename">'.$fname.'</span>',
                   11342:                       $filesize).'<br />'.
1.1007    raeburn  11343:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11344:                   '</span>';
                   11345:         return ('zero_bytes',$msg);
                   11346:     }
                   11347:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11348:     my $getpropath = 1;
1.1021    raeburn  11349:     my ($dirlistref,$listerror) =
                   11350:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11351:     my $found_file = 0;
                   11352:     my $locked_file = 0;
1.991     raeburn  11353:     my @lockers;
                   11354:     my $navmap;
                   11355:     if ($env{'request.course.id'}) {
                   11356:         $navmap = Apache::lonnavmaps::navmap->new();
                   11357:     }
1.1021    raeburn  11358:     if (ref($dirlistref) eq 'ARRAY') {
                   11359:         foreach my $line (@{$dirlistref}) {
                   11360:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11361:             if ($file_name eq $fname){
                   11362:                 $file_name = $path.$file_name;
                   11363:                 if ($group ne '') {
                   11364:                     $file_name = $group.$file_name;
                   11365:                 }
                   11366:                 $found_file = 1;
                   11367:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11368:                     foreach my $lock (@lockers) {
                   11369:                         if (ref($lock) eq 'ARRAY') {
                   11370:                             my ($symb,$crsid) = @{$lock};
                   11371:                             if ($crsid eq $env{'request.course.id'}) {
                   11372:                                 if (ref($navmap)) {
                   11373:                                     my $res = $navmap->getBySymb($symb);
                   11374:                                     foreach my $part (@{$res->parts()}) { 
                   11375:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11376:                                         unless (($slot_status == $res->RESERVED) ||
                   11377:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11378:                                             $locked_file = 1;
                   11379:                                         }
1.991     raeburn  11380:                                     }
1.1021    raeburn  11381:                                 } else {
                   11382:                                     $locked_file = 1;
1.991     raeburn  11383:                                 }
                   11384:                             } else {
                   11385:                                 $locked_file = 1;
                   11386:                             }
                   11387:                         }
1.1021    raeburn  11388:                    }
                   11389:                 } else {
                   11390:                     my @info = split(/\&/,$rest);
                   11391:                     my $currsize = $info[6]/1000;
                   11392:                     if ($currsize < $filesize) {
                   11393:                         my $extra = $filesize - $currsize;
                   11394:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1179    bisitz   11395:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11396:                                       &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   11397:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11398:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11399:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11400:                             return ('will_exceed_quota',$msg);
                   11401:                         }
1.984     raeburn  11402:                     }
                   11403:                 }
1.661     raeburn  11404:             }
                   11405:         }
                   11406:     }
                   11407:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1179    bisitz   11408:         my $msg = '<p class="LC_warning">'.
                   11409:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
1.1184    raeburn  11410:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11411:         return ('will_exceed_quota',$msg);
                   11412:     } elsif ($found_file) {
                   11413:         if ($locked_file) {
1.1179    bisitz   11414:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11415:             $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   11416:             $msg .= '</p>';
1.661     raeburn  11417:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11418:             return ('file_locked',$msg);
                   11419:         } else {
1.1179    bisitz   11420:             my $msg = '<p class="LC_error">';
1.984     raeburn  11421:             $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   11422:             $msg .= '</p>';
1.984     raeburn  11423:             return ('existingfile',$msg);
1.661     raeburn  11424:         }
                   11425:     }
                   11426: }
                   11427: 
1.987     raeburn  11428: sub check_for_traversal {
                   11429:     my ($path,$url,$toplevel) = @_;
                   11430:     my @parts=split(/\//,$path);
                   11431:     my $cleanpath;
                   11432:     my $fullpath = $url;
                   11433:     for (my $i=0;$i<@parts;$i++) {
                   11434:         next if ($parts[$i] eq '.');
                   11435:         if ($parts[$i] eq '..') {
                   11436:             $fullpath =~ s{([^/]+/)$}{};
                   11437:         } else {
                   11438:             $fullpath .= $parts[$i].'/';
                   11439:         }
                   11440:     }
                   11441:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11442:         $cleanpath = $1;
                   11443:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11444:         my $curr_toprel = $1;
                   11445:         my @parts = split(/\//,$curr_toprel);
                   11446:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11447:         my @urlparts = split(/\//,$url_toprel);
                   11448:         my $doubledots;
                   11449:         my $startdiff = -1;
                   11450:         for (my $i=0; $i<@urlparts; $i++) {
                   11451:             if ($startdiff == -1) {
                   11452:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11453:                     $startdiff = $i;
                   11454:                     $doubledots .= '../';
                   11455:                 }
                   11456:             } else {
                   11457:                 $doubledots .= '../';
                   11458:             }
                   11459:         }
                   11460:         if ($startdiff > -1) {
                   11461:             $cleanpath = $doubledots;
                   11462:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11463:                 $cleanpath .= $parts[$i].'/';
                   11464:             }
                   11465:         }
                   11466:     }
                   11467:     $cleanpath =~ s{(/)$}{};
                   11468:     return $cleanpath;
                   11469: }
1.31      albertel 11470: 
1.1053    raeburn  11471: sub is_archive_file {
                   11472:     my ($mimetype) = @_;
                   11473:     if (($mimetype eq 'application/octet-stream') ||
                   11474:         ($mimetype eq 'application/x-stuffit') ||
                   11475:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11476:         return 1;
                   11477:     }
                   11478:     return;
                   11479: }
                   11480: 
                   11481: sub decompress_form {
1.1065    raeburn  11482:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11483:     my %lt = &Apache::lonlocal::texthash (
                   11484:         this => 'This file is an archive file.',
1.1067    raeburn  11485:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11486:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11487:         youm => 'You may wish to extract its contents.',
                   11488:         extr => 'Extract contents',
1.1067    raeburn  11489:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11490:         proa => 'Process automatically?',
1.1053    raeburn  11491:         yes  => 'Yes',
                   11492:         no   => 'No',
1.1067    raeburn  11493:         fold => 'Title for folder containing movie',
                   11494:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11495:     );
1.1065    raeburn  11496:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11497:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11498:     my $info = &list_archive_contents($fileloc,\@paths);
                   11499:     if (@paths) {
                   11500:         foreach my $path (@paths) {
                   11501:             $path =~ s{^/}{};
1.1067    raeburn  11502:             if ($path =~ m{^([^/]+)/$}) {
                   11503:                 $topdir = $1;
                   11504:             }
1.1065    raeburn  11505:             if ($path =~ m{^([^/]+)/}) {
                   11506:                 $toplevel{$1} = $path;
                   11507:             } else {
                   11508:                 $toplevel{$path} = $path;
                   11509:             }
                   11510:         }
                   11511:     }
1.1067    raeburn  11512:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1164    raeburn  11513:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11514:                         "$topdir/media/",
                   11515:                         "$topdir/media/$topdir.mp4",
                   11516:                         "$topdir/media/FirstFrame.png",
                   11517:                         "$topdir/media/player.swf",
                   11518:                         "$topdir/media/swfobject.js",
                   11519:                         "$topdir/media/expressInstall.swf");
1.1197    raeburn  11520:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1164    raeburn  11521:                          "$topdir/$topdir.mp4",
                   11522:                          "$topdir/$topdir\_config.xml",
                   11523:                          "$topdir/$topdir\_controller.swf",
                   11524:                          "$topdir/$topdir\_embed.css",
                   11525:                          "$topdir/$topdir\_First_Frame.png",
                   11526:                          "$topdir/$topdir\_player.html",
                   11527:                          "$topdir/$topdir\_Thumbnails.png",
                   11528:                          "$topdir/playerProductInstall.swf",
                   11529:                          "$topdir/scripts/",
                   11530:                          "$topdir/scripts/config_xml.js",
                   11531:                          "$topdir/scripts/handlebars.js",
                   11532:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11533:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11534:                          "$topdir/scripts/modernizr.js",
                   11535:                          "$topdir/scripts/player-min.js",
                   11536:                          "$topdir/scripts/swfobject.js",
                   11537:                          "$topdir/skins/",
                   11538:                          "$topdir/skins/configuration_express.xml",
                   11539:                          "$topdir/skins/express_show/",
                   11540:                          "$topdir/skins/express_show/player-min.css",
                   11541:                          "$topdir/skins/express_show/spritesheet.png");
1.1197    raeburn  11542:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11543:                          "$topdir/$topdir.mp4",
                   11544:                          "$topdir/$topdir\_config.xml",
                   11545:                          "$topdir/$topdir\_controller.swf",
                   11546:                          "$topdir/$topdir\_embed.css",
                   11547:                          "$topdir/$topdir\_First_Frame.png",
                   11548:                          "$topdir/$topdir\_player.html",
                   11549:                          "$topdir/$topdir\_Thumbnails.png",
                   11550:                          "$topdir/playerProductInstall.swf",
                   11551:                          "$topdir/scripts/",
                   11552:                          "$topdir/scripts/config_xml.js",
                   11553:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11554:                          "$topdir/skins/",
                   11555:                          "$topdir/skins/configuration_express.xml",
                   11556:                          "$topdir/skins/express_show/",
                   11557:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11558:                          "$topdir/skins/express_show/spritesheet.png",
                   11559:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1164    raeburn  11560:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11561:         if (@diffs == 0) {
1.1164    raeburn  11562:             $is_camtasia = 6;
                   11563:         } else {
1.1197    raeburn  11564:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1164    raeburn  11565:             if (@diffs == 0) {
                   11566:                 $is_camtasia = 8;
1.1197    raeburn  11567:             } else {
                   11568:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11569:                 if (@diffs == 0) {
                   11570:                     $is_camtasia = 8;
                   11571:                 }
1.1164    raeburn  11572:             }
1.1067    raeburn  11573:         }
                   11574:     }
                   11575:     my $output;
                   11576:     if ($is_camtasia) {
                   11577:         $output = <<"ENDCAM";
                   11578: <script type="text/javascript" language="Javascript">
                   11579: // <![CDATA[
                   11580: 
                   11581: function camtasiaToggle() {
                   11582:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11583:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1164    raeburn  11584:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11585:                 document.getElementById('camtasia_titles').style.display='block';
                   11586:             } else {
                   11587:                 document.getElementById('camtasia_titles').style.display='none';
                   11588:             }
                   11589:         }
                   11590:     }
                   11591:     return;
                   11592: }
                   11593: 
                   11594: // ]]>
                   11595: </script>
                   11596: <p>$lt{'camt'}</p>
                   11597: ENDCAM
1.1065    raeburn  11598:     } else {
1.1067    raeburn  11599:         $output = '<p>'.$lt{'this'};
                   11600:         if ($info eq '') {
                   11601:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11602:         } else {
                   11603:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11604:                        '<div><pre>'.$info.'</pre></div>';
                   11605:         }
1.1065    raeburn  11606:     }
1.1067    raeburn  11607:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11608:     my $duplicates;
                   11609:     my $num = 0;
                   11610:     if (ref($dirlist) eq 'ARRAY') {
                   11611:         foreach my $item (@{$dirlist}) {
                   11612:             if (ref($item) eq 'ARRAY') {
                   11613:                 if (exists($toplevel{$item->[0]})) {
                   11614:                     $duplicates .= 
                   11615:                         &start_data_table_row().
                   11616:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11617:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11618:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11619:                         'value="1" />'.&mt('Yes').'</label>'.
                   11620:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11621:                         '<td>'.$item->[0].'</td>';
                   11622:                     if ($item->[2]) {
                   11623:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11624:                     } else {
                   11625:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11626:                     }
                   11627:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11628:                                    '<td>'.
                   11629:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11630:                                    '</td>'.
                   11631:                                    &end_data_table_row();
                   11632:                     $num ++;
                   11633:                 }
                   11634:             }
                   11635:         }
                   11636:     }
                   11637:     my $itemcount;
                   11638:     if (@paths > 0) {
                   11639:         $itemcount = scalar(@paths);
                   11640:     } else {
                   11641:         $itemcount = 1;
                   11642:     }
1.1067    raeburn  11643:     if ($is_camtasia) {
                   11644:         $output .= $lt{'auto'}.'<br />'.
                   11645:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1164    raeburn  11646:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11647:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11648:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11649:                    $lt{'no'}.'</label></span><br />'.
                   11650:                    '<div id="camtasia_titles" style="display:block">'.
                   11651:                    &Apache::lonhtmlcommon::start_pick_box().
                   11652:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11653:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11654:                    &Apache::lonhtmlcommon::row_closure().
                   11655:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11656:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11657:                    &Apache::lonhtmlcommon::row_closure(1).
                   11658:                    &Apache::lonhtmlcommon::end_pick_box().
                   11659:                    '</div>';
                   11660:     }
1.1065    raeburn  11661:     $output .= 
                   11662:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11663:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11664:         "\n";
1.1065    raeburn  11665:     if ($duplicates ne '') {
                   11666:         $output .= '<p><span class="LC_warning">'.
                   11667:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11668:                    &start_data_table().
                   11669:                    &start_data_table_header_row().
                   11670:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11671:                    '<th>'.&mt('Name').'</th>'.
                   11672:                    '<th>'.&mt('Type').'</th>'.
                   11673:                    '<th>'.&mt('Size').'</th>'.
                   11674:                    '<th>'.&mt('Last modified').'</th>'.
                   11675:                    &end_data_table_header_row().
                   11676:                    $duplicates.
                   11677:                    &end_data_table().
                   11678:                    '</p>';
                   11679:     }
1.1067    raeburn  11680:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11681:     if (ref($hiddenelements) eq 'HASH') {
                   11682:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11683:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11684:         }
                   11685:     }
                   11686:     $output .= <<"END";
1.1067    raeburn  11687: <br />
1.1053    raeburn  11688: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11689: </form>
                   11690: $noextract
                   11691: END
                   11692:     return $output;
                   11693: }
                   11694: 
1.1065    raeburn  11695: sub decompression_utility {
                   11696:     my ($program) = @_;
                   11697:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11698:     my $location;
                   11699:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11700:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11701:                          '/usr/sbin/') {
                   11702:             if (-x $dir.$program) {
                   11703:                 $location = $dir.$program;
                   11704:                 last;
                   11705:             }
                   11706:         }
                   11707:     }
                   11708:     return $location;
                   11709: }
                   11710: 
                   11711: sub list_archive_contents {
                   11712:     my ($file,$pathsref) = @_;
                   11713:     my (@cmd,$output);
                   11714:     my $needsregexp;
                   11715:     if ($file =~ /\.zip$/) {
                   11716:         @cmd = (&decompression_utility('unzip'),"-l");
                   11717:         $needsregexp = 1;
                   11718:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11719:              ($file =~ /\.tgz$/)) {
                   11720:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11721:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11722:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11723:     } elsif ($file =~ m|\.tar$|) {
                   11724:         @cmd = (&decompression_utility('tar'),"-tf");
                   11725:     }
                   11726:     if (@cmd) {
                   11727:         undef($!);
                   11728:         undef($@);
                   11729:         if (open(my $fh,"-|", @cmd, $file)) {
                   11730:             while (my $line = <$fh>) {
                   11731:                 $output .= $line;
                   11732:                 chomp($line);
                   11733:                 my $item;
                   11734:                 if ($needsregexp) {
                   11735:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11736:                 } else {
                   11737:                     $item = $line;
                   11738:                 }
                   11739:                 if ($item ne '') {
                   11740:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11741:                         push(@{$pathsref},$item);
                   11742:                     } 
                   11743:                 }
                   11744:             }
                   11745:             close($fh);
                   11746:         }
                   11747:     }
                   11748:     return $output;
                   11749: }
                   11750: 
1.1053    raeburn  11751: sub decompress_uploaded_file {
                   11752:     my ($file,$dir) = @_;
                   11753:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11754:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11755:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11756:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11757:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11758:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11759:     my $decompressed = $env{'cgi.decompressed'};
                   11760:     &Apache::lonnet::delenv('cgi.file');
                   11761:     &Apache::lonnet::delenv('cgi.dir');
                   11762:     &Apache::lonnet::delenv('cgi.decompressed');
                   11763:     return ($decompressed,$result);
                   11764: }
                   11765: 
1.1055    raeburn  11766: sub process_decompression {
                   11767:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11768:     my ($dir,$error,$warning,$output);
1.1180    raeburn  11769:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1120    bisitz   11770:         $error = &mt('Filename not a supported archive file type.').
                   11771:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11772:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11773:     } else {
                   11774:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11775:         if ($docuhome eq 'no_host') {
                   11776:             $error = &mt('Could not determine home server for course.');
                   11777:         } else {
                   11778:             my @ids=&Apache::lonnet::current_machine_ids();
                   11779:             my $currdir = "$dir_root/$destination";
                   11780:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11781:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11782:                        "$dir_root/$destination";
                   11783:             } else {
                   11784:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11785:                        "$dir_root/$docudom/$docuname/$destination";
                   11786:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11787:                     $error = &mt('Archive file not found.');
                   11788:                 }
                   11789:             }
1.1065    raeburn  11790:             my (@to_overwrite,@to_skip);
                   11791:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11792:                 my $total = $env{'form.archive_overwrite_total'};
                   11793:                 for (my $i=0; $i<$total; $i++) {
                   11794:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11795:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11796:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11797:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11798:                     }
                   11799:                 }
                   11800:             }
                   11801:             my $numskip = scalar(@to_skip);
                   11802:             if (($numskip > 0) && 
                   11803:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11804:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11805:             } elsif ($dir eq '') {
1.1055    raeburn  11806:                 $error = &mt('Directory containing archive file unavailable.');
                   11807:             } elsif (!$error) {
1.1065    raeburn  11808:                 my ($decompressed,$display);
                   11809:                 if ($numskip > 0) {
                   11810:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11811:                     mkdir("$dir/$tempdir",0755);
                   11812:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11813:                     ($decompressed,$display) = 
                   11814:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11815:                     foreach my $item (@to_skip) {
                   11816:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11817:                             if (-f "$dir/$tempdir/$item") { 
                   11818:                                 unlink("$dir/$tempdir/$item");
                   11819:                             } elsif (-d "$dir/$tempdir/$item") {
                   11820:                                 system("rm -rf $dir/$tempdir/$item");
                   11821:                             }
                   11822:                         }
                   11823:                     }
                   11824:                     system("mv $dir/$tempdir/* $dir");
                   11825:                     rmdir("$dir/$tempdir");   
                   11826:                 } else {
                   11827:                     ($decompressed,$display) = 
                   11828:                         &decompress_uploaded_file($file,$dir);
                   11829:                 }
1.1055    raeburn  11830:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11831:                     $output = '<p class="LC_info">'.
                   11832:                               &mt('Files extracted successfully from archive.').
                   11833:                               '</p>'."\n";
1.1055    raeburn  11834:                     my ($warning,$result,@contents);
                   11835:                     my ($newdirlistref,$newlisterror) =
                   11836:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11837:                                                  $docuname,1);
                   11838:                     my (%is_dir,%changes,@newitems);
                   11839:                     my $dirptr = 16384;
1.1065    raeburn  11840:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11841:                         foreach my $dir_line (@{$newdirlistref}) {
                   11842:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11843:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11844:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11845:                                 push(@newitems,$item);
                   11846:                                 if ($dirptr&$testdir) {
                   11847:                                     $is_dir{$item} = 1;
                   11848:                                 }
                   11849:                                 $changes{$item} = 1;
                   11850:                             }
                   11851:                         }
                   11852:                     }
                   11853:                     if (keys(%changes) > 0) {
                   11854:                         foreach my $item (sort(@newitems)) {
                   11855:                             if ($changes{$item}) {
                   11856:                                 push(@contents,$item);
                   11857:                             }
                   11858:                         }
                   11859:                     }
                   11860:                     if (@contents > 0) {
1.1067    raeburn  11861:                         my $wantform;
                   11862:                         unless ($env{'form.autoextract_camtasia'}) {
                   11863:                             $wantform = 1;
                   11864:                         }
1.1056    raeburn  11865:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11866:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11867:                                                                 $currdir,\%is_dir,
                   11868:                                                                 \%children,\%parent,
1.1056    raeburn  11869:                                                                 \@contents,\%dirorder,
                   11870:                                                                 \%titles,$wantform);
1.1055    raeburn  11871:                         if ($datatable ne '') {
                   11872:                             $output .= &archive_options_form('decompressed',$datatable,
                   11873:                                                              $count,$hiddenelem);
1.1065    raeburn  11874:                             my $startcount = 6;
1.1055    raeburn  11875:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11876:                                                            \%titles,\%children);
1.1055    raeburn  11877:                         }
1.1067    raeburn  11878:                         if ($env{'form.autoextract_camtasia'}) {
1.1164    raeburn  11879:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11880:                             my %displayed;
                   11881:                             my $total = 1;
                   11882:                             $env{'form.archive_directory'} = [];
                   11883:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11884:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11885:                                 $path =~ s{/$}{};
                   11886:                                 my $item;
                   11887:                                 if ($path ne '') {
                   11888:                                     $item = "$path/$titles{$i}";
                   11889:                                 } else {
                   11890:                                     $item = $titles{$i};
                   11891:                                 }
                   11892:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11893:                                 if ($item eq $contents[0]) {
                   11894:                                     push(@{$env{'form.archive_directory'}},$i);
                   11895:                                     $env{'form.archive_'.$i} = 'display';
                   11896:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11897:                                     $displayed{'folder'} = $i;
1.1164    raeburn  11898:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11899:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) { 
1.1067    raeburn  11900:                                     $env{'form.archive_'.$i} = 'display';
                   11901:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11902:                                     $displayed{'web'} = $i;
                   11903:                                 } else {
1.1164    raeburn  11904:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11905:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11906:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11907:                                         push(@{$env{'form.archive_directory'}},$i);
                   11908:                                     }
                   11909:                                     $env{'form.archive_'.$i} = 'dependency';
                   11910:                                 }
                   11911:                                 $total ++;
                   11912:                             }
                   11913:                             for (my $i=1; $i<$total; $i++) {
                   11914:                                 next if ($i == $displayed{'web'});
                   11915:                                 next if ($i == $displayed{'folder'});
                   11916:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11917:                             }
                   11918:                             $env{'form.phase'} = 'decompress_cleanup';
                   11919:                             $env{'form.archivedelete'} = 1;
                   11920:                             $env{'form.archive_count'} = $total-1;
                   11921:                             $output .=
                   11922:                                 &process_extracted_files('coursedocs',$docudom,
                   11923:                                                          $docuname,$destination,
                   11924:                                                          $dir_root,$hiddenelem);
                   11925:                         }
1.1055    raeburn  11926:                     } else {
                   11927:                         $warning = &mt('No new items extracted from archive file.');
                   11928:                     }
                   11929:                 } else {
                   11930:                     $output = $display;
                   11931:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11932:                 }
                   11933:             }
                   11934:         }
                   11935:     }
                   11936:     if ($error) {
                   11937:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11938:                    $error.'</p>'."\n";
                   11939:     }
                   11940:     if ($warning) {
                   11941:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11942:     }
                   11943:     return $output;
                   11944: }
                   11945: 
                   11946: sub get_extracted {
1.1056    raeburn  11947:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11948:         $titles,$wantform) = @_;
1.1055    raeburn  11949:     my $count = 0;
                   11950:     my $depth = 0;
                   11951:     my $datatable;
1.1056    raeburn  11952:     my @hierarchy;
1.1055    raeburn  11953:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11954:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11955:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11956:     foreach my $item (@{$contents}) {
                   11957:         $count ++;
1.1056    raeburn  11958:         @{$dirorder->{$count}} = @hierarchy;
                   11959:         $titles->{$count} = $item;
1.1055    raeburn  11960:         &archive_hierarchy($depth,$count,$parent,$children);
                   11961:         if ($wantform) {
                   11962:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11963:                                        $currdir,$depth,$count);
                   11964:         }
                   11965:         if ($is_dir->{$item}) {
                   11966:             $depth ++;
1.1056    raeburn  11967:             push(@hierarchy,$count);
                   11968:             $parent->{$depth} = $count;
1.1055    raeburn  11969:             $datatable .=
                   11970:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11971:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11972:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11973:             $depth --;
1.1056    raeburn  11974:             pop(@hierarchy);
1.1055    raeburn  11975:         }
                   11976:     }
                   11977:     return ($count,$datatable);
                   11978: }
                   11979: 
                   11980: sub recurse_extracted_archive {
1.1056    raeburn  11981:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11982:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11983:     my $result='';
1.1056    raeburn  11984:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11985:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11986:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11987:         return $result;
                   11988:     }
                   11989:     my $dirptr = 16384;
                   11990:     my ($newdirlistref,$newlisterror) =
                   11991:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11992:     if (ref($newdirlistref) eq 'ARRAY') {
                   11993:         foreach my $dir_line (@{$newdirlistref}) {
                   11994:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11995:             unless ($item =~ /^\.+$/) {
                   11996:                 $$count ++;
1.1056    raeburn  11997:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11998:                 $titles->{$$count} = $item;
1.1055    raeburn  11999:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12000: 
1.1055    raeburn  12001:                 my $is_dir;
                   12002:                 if ($dirptr&$testdir) {
                   12003:                     $is_dir = 1;
                   12004:                 }
                   12005:                 if ($wantform) {
                   12006:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12007:                 }
                   12008:                 if ($is_dir) {
                   12009:                     $$depth ++;
1.1056    raeburn  12010:                     push(@{$hierarchy},$$count);
                   12011:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12012:                     $result .=
                   12013:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12014:                                                    $docuname,$depth,$count,
1.1056    raeburn  12015:                                                    $hierarchy,$dirorder,$children,
                   12016:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12017:                     $$depth --;
1.1056    raeburn  12018:                     pop(@{$hierarchy});
1.1055    raeburn  12019:                 }
                   12020:             }
                   12021:         }
                   12022:     }
                   12023:     return $result;
                   12024: }
                   12025: 
                   12026: sub archive_hierarchy {
                   12027:     my ($depth,$count,$parent,$children) =@_;
                   12028:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12029:         if (exists($parent->{$depth})) {
                   12030:              $children->{$parent->{$depth}} .= $count.':';
                   12031:         }
                   12032:     }
                   12033:     return;
                   12034: }
                   12035: 
                   12036: sub archive_row {
                   12037:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12038:     my ($name) = ($item =~ m{([^/]+)$});
                   12039:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12040:                                        'display'    => 'Add as file',
1.1055    raeburn  12041:                                        'dependency' => 'Include as dependency',
                   12042:                                        'discard'    => 'Discard',
                   12043:                                       );
                   12044:     if ($is_dir) {
1.1059    raeburn  12045:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12046:     }
1.1056    raeburn  12047:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12048:     my $offset = 0;
1.1055    raeburn  12049:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12050:         $offset ++;
1.1065    raeburn  12051:         if ($action ne 'display') {
                   12052:             $offset ++;
                   12053:         }  
1.1055    raeburn  12054:         $output .= '<td><span class="LC_nobreak">'.
                   12055:                    '<label><input type="radio" name="archive_'.$count.
                   12056:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12057:         my $text = $choices{$action};
                   12058:         if ($is_dir) {
                   12059:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12060:             if ($action eq 'display') {
1.1059    raeburn  12061:                 $text = &mt('Add as folder');
1.1055    raeburn  12062:             }
1.1056    raeburn  12063:         } else {
                   12064:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12065: 
                   12066:         }
                   12067:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12068:         if ($action eq 'dependency') {
                   12069:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12070:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12071:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12072:                        '<option value=""></option>'."\n".
                   12073:                        '</select>'."\n".
                   12074:                        '</div>';
1.1059    raeburn  12075:         } elsif ($action eq 'display') {
                   12076:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12077:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12078:                        '</div>';
1.1055    raeburn  12079:         }
1.1056    raeburn  12080:         $output .= '</td>';
1.1055    raeburn  12081:     }
                   12082:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12083:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12084:     for (my $i=0; $i<$depth; $i++) {
                   12085:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12086:     }
                   12087:     if ($is_dir) {
                   12088:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12089:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12090:     } else {
                   12091:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12092:     }
                   12093:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12094:                &end_data_table_row();
                   12095:     return $output;
                   12096: }
                   12097: 
                   12098: sub archive_options_form {
1.1065    raeburn  12099:     my ($form,$display,$count,$hiddenelem) = @_;
                   12100:     my %lt = &Apache::lonlocal::texthash(
                   12101:                perm => 'Permanently remove archive file?',
                   12102:                hows => 'How should each extracted item be incorporated in the course?',
                   12103:                cont => 'Content actions for all',
                   12104:                addf => 'Add as folder/file',
                   12105:                incd => 'Include as dependency for a displayed file',
                   12106:                disc => 'Discard',
                   12107:                no   => 'No',
                   12108:                yes  => 'Yes',
                   12109:                save => 'Save',
                   12110:     );
                   12111:     my $output = <<"END";
                   12112: <form name="$form" method="post" action="">
                   12113: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12114: <label>
                   12115:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12116: </label>
                   12117: &nbsp;
                   12118: <label>
                   12119:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12120: </span>
                   12121: </p>
                   12122: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12123: <br />$lt{'hows'}
                   12124: <div class="LC_columnSection">
                   12125:   <fieldset>
                   12126:     <legend>$lt{'cont'}</legend>
                   12127:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12128:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12129:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12130:   </fieldset>
                   12131: </div>
                   12132: END
                   12133:     return $output.
1.1055    raeburn  12134:            &start_data_table()."\n".
1.1065    raeburn  12135:            $display."\n".
1.1055    raeburn  12136:            &end_data_table()."\n".
                   12137:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12138:            $hiddenelem.
1.1065    raeburn  12139:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12140:            '</form>';
                   12141: }
                   12142: 
                   12143: sub archive_javascript {
1.1056    raeburn  12144:     my ($startcount,$numitems,$titles,$children) = @_;
                   12145:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12146:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12147:     my $scripttag = <<START;
                   12148: <script type="text/javascript">
                   12149: // <![CDATA[
                   12150: 
                   12151: function checkAll(form,prefix) {
                   12152:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12153:     for (var i=0; i < form.elements.length; i++) {
                   12154:         var id = form.elements[i].id;
                   12155:         if ((id != '') && (id != undefined)) {
                   12156:             if (idstr.test(id)) {
                   12157:                 if (form.elements[i].type == 'radio') {
                   12158:                     form.elements[i].checked = true;
1.1056    raeburn  12159:                     var nostart = i-$startcount;
1.1059    raeburn  12160:                     var offset = nostart%7;
                   12161:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12162:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12163:                 }
                   12164:             }
                   12165:         }
                   12166:     }
                   12167: }
                   12168: 
                   12169: function propagateCheck(form,count) {
                   12170:     if (count > 0) {
1.1059    raeburn  12171:         var startelement = $startcount + ((count-1) * 7);
                   12172:         for (var j=1; j<6; j++) {
                   12173:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12174:                 var item = startelement + j; 
                   12175:                 if (form.elements[item].type == 'radio') {
                   12176:                     if (form.elements[item].checked) {
                   12177:                         containerCheck(form,count,j);
                   12178:                         break;
                   12179:                     }
1.1055    raeburn  12180:                 }
                   12181:             }
                   12182:         }
                   12183:     }
                   12184: }
                   12185: 
                   12186: numitems = $numitems
1.1056    raeburn  12187: var titles = new Array(numitems);
                   12188: var parents = new Array(numitems);
1.1055    raeburn  12189: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12190:     parents[i] = new Array;
1.1055    raeburn  12191: }
1.1059    raeburn  12192: var maintitle = '$maintitle';
1.1055    raeburn  12193: 
                   12194: START
                   12195: 
1.1056    raeburn  12196:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12197:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12198:         for (my $i=0; $i<@contents; $i ++) {
                   12199:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12200:         }
                   12201:     }
                   12202: 
1.1056    raeburn  12203:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12204:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12205:     }
                   12206: 
1.1055    raeburn  12207:     $scripttag .= <<END;
                   12208: 
                   12209: function containerCheck(form,count,offset) {
                   12210:     if (count > 0) {
1.1056    raeburn  12211:         dependencyCheck(form,count,offset);
1.1059    raeburn  12212:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12213:         form.elements[item].checked = true;
                   12214:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12215:             if (parents[count].length > 0) {
                   12216:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12217:                     containerCheck(form,parents[count][j],offset);
                   12218:                 }
                   12219:             }
                   12220:         }
                   12221:     }
                   12222: }
                   12223: 
                   12224: function dependencyCheck(form,count,offset) {
                   12225:     if (count > 0) {
1.1059    raeburn  12226:         var chosen = (offset+$startcount)+7*(count-1);
                   12227:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12228:         var currtype = form.elements[depitem].type;
                   12229:         if (form.elements[chosen].value == 'dependency') {
                   12230:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12231:             form.elements[depitem].options.length = 0;
                   12232:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1085    raeburn  12233:             for (var i=1; i<=numitems; i++) {
                   12234:                 if (i == count) {
                   12235:                     continue;
                   12236:                 }
1.1059    raeburn  12237:                 var startelement = $startcount + (i-1) * 7;
                   12238:                 for (var j=1; j<6; j++) {
                   12239:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12240:                         var item = startelement + j;
                   12241:                         if (form.elements[item].type == 'radio') {
                   12242:                             if (form.elements[item].checked) {
                   12243:                                 if (form.elements[item].value == 'display') {
                   12244:                                     var n = form.elements[depitem].options.length;
                   12245:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12246:                                 }
                   12247:                             }
                   12248:                         }
                   12249:                     }
                   12250:                 }
                   12251:             }
                   12252:         } else {
                   12253:             document.getElementById('arc_depon_'+count).style.display='none';
                   12254:             form.elements[depitem].options.length = 0;
                   12255:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12256:         }
1.1059    raeburn  12257:         titleCheck(form,count,offset);
1.1056    raeburn  12258:     }
                   12259: }
                   12260: 
                   12261: function propagateSelect(form,count,offset) {
                   12262:     if (count > 0) {
1.1065    raeburn  12263:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12264:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12265:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12266:             if (parents[count].length > 0) {
                   12267:                 for (var j=0; j<parents[count].length; j++) {
                   12268:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12269:                 }
                   12270:             }
                   12271:         }
                   12272:     }
                   12273: }
1.1056    raeburn  12274: 
                   12275: function containerSelect(form,count,offset,picked) {
                   12276:     if (count > 0) {
1.1065    raeburn  12277:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12278:         if (form.elements[item].type == 'radio') {
                   12279:             if (form.elements[item].value == 'dependency') {
                   12280:                 if (form.elements[item+1].type == 'select-one') {
                   12281:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12282:                         if (form.elements[item+1].options[i].value == picked) {
                   12283:                             form.elements[item+1].selectedIndex = i;
                   12284:                             break;
                   12285:                         }
                   12286:                     }
                   12287:                 }
                   12288:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12289:                     if (parents[count].length > 0) {
                   12290:                         for (var j=0; j<parents[count].length; j++) {
                   12291:                             containerSelect(form,parents[count][j],offset,picked);
                   12292:                         }
                   12293:                     }
                   12294:                 }
                   12295:             }
                   12296:         }
                   12297:     }
                   12298: }
                   12299: 
1.1059    raeburn  12300: function titleCheck(form,count,offset) {
                   12301:     if (count > 0) {
                   12302:         var chosen = (offset+$startcount)+7*(count-1);
                   12303:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12304:         var currtype = form.elements[depitem].type;
                   12305:         if (form.elements[chosen].value == 'display') {
                   12306:             document.getElementById('arc_title_'+count).style.display='block';
                   12307:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12308:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12309:             }
                   12310:         } else {
                   12311:             document.getElementById('arc_title_'+count).style.display='none';
                   12312:             if (currtype == 'text') { 
                   12313:                 document.getElementById('archive_title_'+count).value='';
                   12314:             }
                   12315:         }
                   12316:     }
                   12317:     return;
                   12318: }
                   12319: 
1.1055    raeburn  12320: // ]]>
                   12321: </script>
                   12322: END
                   12323:     return $scripttag;
                   12324: }
                   12325: 
                   12326: sub process_extracted_files {
1.1067    raeburn  12327:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12328:     my $numitems = $env{'form.archive_count'};
                   12329:     return unless ($numitems);
                   12330:     my @ids=&Apache::lonnet::current_machine_ids();
                   12331:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12332:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12333:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12334:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12335:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12336:         $pathtocheck = "$dir_root/$destination";
                   12337:         $dir = $dir_root;
                   12338:         $ishome = 1;
                   12339:     } else {
                   12340:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12341:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12342:         $dir = "$dir_root/$docudom/$docuname";    
                   12343:     }
                   12344:     my $currdir = "$dir_root/$destination";
                   12345:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12346:     if ($env{'form.folderpath'}) {
                   12347:         my @items = split('&',$env{'form.folderpath'});
                   12348:         $folders{'0'} = $items[-2];
1.1099    raeburn  12349:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12350:             $containers{'0'}='page';
                   12351:         } else {  
                   12352:             $containers{'0'}='sequence';
                   12353:         }
1.1055    raeburn  12354:     }
                   12355:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12356:     if ($numitems) {
                   12357:         for (my $i=1; $i<=$numitems; $i++) {
                   12358:             my $path = $env{'form.archive_content_'.$i};
                   12359:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12360:                 my $item = $1;
                   12361:                 $toplevelitems{$item} = $i;
                   12362:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12363:                     $is_dir{$item} = 1;
                   12364:                 }
                   12365:             }
                   12366:         }
                   12367:     }
1.1067    raeburn  12368:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12369:     if (keys(%toplevelitems) > 0) {
                   12370:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12371:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12372:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12373:     }
1.1066    raeburn  12374:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12375:     if ($numitems) {
                   12376:         for (my $i=1; $i<=$numitems; $i++) {
1.1086    raeburn  12377:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12378:             my $path = $env{'form.archive_content_'.$i};
                   12379:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12380:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12381:                     if ($prefix ne '' && $path ne '') {
                   12382:                         if (-e $prefix.$path) {
1.1066    raeburn  12383:                             if ((@archdirs > 0) && 
                   12384:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12385:                                 $todeletedir{$prefix.$path} = 1;
                   12386:                             } else {
                   12387:                                 $todelete{$prefix.$path} = 1;
                   12388:                             }
1.1055    raeburn  12389:                         }
                   12390:                     }
                   12391:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12392:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12393:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12394:                     $docstitle = $env{'form.archive_title_'.$i};
                   12395:                     if ($docstitle eq '') {
                   12396:                         $docstitle = $title;
                   12397:                     }
1.1055    raeburn  12398:                     $outer = 0;
1.1056    raeburn  12399:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12400:                         if (@{$dirorder{$i}} > 0) {
                   12401:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12402:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12403:                                     $outer = $item;
                   12404:                                     last;
                   12405:                                 }
                   12406:                             }
                   12407:                         }
                   12408:                     }
                   12409:                     my ($errtext,$fatal) = 
                   12410:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12411:                                                '/'.$folders{$outer}.'.'.
                   12412:                                                $containers{$outer});
                   12413:                     next if ($fatal);
                   12414:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12415:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12416:                             $mapinner{$i} = time;
1.1055    raeburn  12417:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12418:                             $containers{$i} = 'sequence';
                   12419:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12420:                                       $folders{$i}.'.'.$containers{$i};
                   12421:                             my $newidx = &LONCAPA::map::getresidx();
                   12422:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12423:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12424:                             push(@LONCAPA::map::order,$newidx);
                   12425:                             my ($outtext,$errtext) =
                   12426:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12427:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12428:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12429:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12430:                             unless ($errtext) {
                   12431:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12432:                             }
1.1055    raeburn  12433:                         }
                   12434:                     } else {
                   12435:                         if ($context eq 'coursedocs') {
                   12436:                             my $newidx=&LONCAPA::map::getresidx();
                   12437:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12438:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12439:                                       $title;
                   12440:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12441:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12442:                             }
                   12443:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12444:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12445:                             }
                   12446:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12447:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12448:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12449:                                 unless ($ishome) {
                   12450:                                     my $fetch = "$newdest{$i}/$title";
                   12451:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12452:                                     $prompttofetch{$fetch} = 1;
                   12453:                                 }
1.1055    raeburn  12454:                             }
                   12455:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12456:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12457:                             push(@LONCAPA::map::order, $newidx);
                   12458:                             my ($outtext,$errtext)=
                   12459:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12460:                                                         $docuname.'/'.$folders{$outer}.
1.1087    raeburn  12461:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12462:                             unless ($errtext) {
                   12463:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12464:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12465:                                 }
                   12466:                             }
1.1055    raeburn  12467:                         }
                   12468:                     }
1.1086    raeburn  12469:                 }
                   12470:             } else {
                   12471:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12472:             }
                   12473:         }
                   12474:         for (my $i=1; $i<=$numitems; $i++) {
                   12475:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12476:             my $path = $env{'form.archive_content_'.$i};
                   12477:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12478:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12479:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12480:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12481:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12482:                         my ($itemidx,$fullpath,$relpath);
                   12483:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12484:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12485:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1086    raeburn  12486:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12487:                                     $itemidx = $j;
1.1056    raeburn  12488:                                 }
                   12489:                             }
1.1086    raeburn  12490:                         }
                   12491:                         if ($itemidx eq '') {
                   12492:                             $itemidx =  0;
                   12493:                         } 
                   12494:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12495:                             if ($mapinner{$referrer{$i}}) {
                   12496:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12497:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12498:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12499:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12500:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12501:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12502:                                             if (!-e $fullpath) {
                   12503:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12504:                                             }
                   12505:                                         }
1.1086    raeburn  12506:                                     } else {
                   12507:                                         last;
1.1056    raeburn  12508:                                     }
1.1086    raeburn  12509:                                 }
                   12510:                             }
                   12511:                         } elsif ($newdest{$referrer{$i}}) {
                   12512:                             $fullpath = $newdest{$referrer{$i}};
                   12513:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12514:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12515:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12516:                                     last;
                   12517:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12518:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12519:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12520:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12521:                                         if (!-e $fullpath) {
                   12522:                                             mkdir($fullpath,0755);
1.1056    raeburn  12523:                                         }
                   12524:                                     }
1.1086    raeburn  12525:                                 } else {
                   12526:                                     last;
1.1056    raeburn  12527:                                 }
1.1055    raeburn  12528:                             }
                   12529:                         }
1.1086    raeburn  12530:                         if ($fullpath ne '') {
                   12531:                             if (-e "$prefix$path") {
                   12532:                                 system("mv $prefix$path $fullpath/$title");
                   12533:                             }
                   12534:                             if (-e "$fullpath/$title") {
                   12535:                                 my $showpath;
                   12536:                                 if ($relpath ne '') {
                   12537:                                     $showpath = "$relpath/$title";
                   12538:                                 } else {
                   12539:                                     $showpath = "/$title";
                   12540:                                 } 
                   12541:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12542:                             } 
                   12543:                             unless ($ishome) {
                   12544:                                 my $fetch = "$fullpath/$title";
                   12545:                                 $fetch =~ s/^\Q$prefix$dir\E//; 
                   12546:                                 $prompttofetch{$fetch} = 1;
                   12547:                             }
                   12548:                         }
1.1055    raeburn  12549:                     }
1.1086    raeburn  12550:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12551:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12552:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12553:                 }
                   12554:             } else {
                   12555:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />'; 
                   12556:             }
                   12557:         }
                   12558:         if (keys(%todelete)) {
                   12559:             foreach my $key (keys(%todelete)) {
                   12560:                 unlink($key);
1.1066    raeburn  12561:             }
                   12562:         }
                   12563:         if (keys(%todeletedir)) {
                   12564:             foreach my $key (keys(%todeletedir)) {
                   12565:                 rmdir($key);
                   12566:             }
                   12567:         }
                   12568:         foreach my $dir (sort(keys(%is_dir))) {
                   12569:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12570:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12571:             }
                   12572:         }
1.1067    raeburn  12573:         if ($result ne '') {
                   12574:             $output .= '<ul>'."\n".
                   12575:                        $result."\n".
                   12576:                        '</ul>';
                   12577:         }
                   12578:         unless ($ishome) {
                   12579:             my $replicationfail;
                   12580:             foreach my $item (keys(%prompttofetch)) {
                   12581:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12582:                 unless ($fetchresult eq 'ok') {
                   12583:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12584:                 }
                   12585:             }
                   12586:             if ($replicationfail) {
                   12587:                 $output .= '<p class="LC_error">'.
                   12588:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12589:                            $replicationfail.
                   12590:                            '</ul></p>';
                   12591:             }
                   12592:         }
1.1055    raeburn  12593:     } else {
                   12594:         $warning = &mt('No items found in archive.');
                   12595:     }
                   12596:     if ($error) {
                   12597:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12598:                    $error.'</p>'."\n";
                   12599:     }
                   12600:     if ($warning) {
                   12601:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12602:     }
                   12603:     return $output;
                   12604: }
                   12605: 
1.1066    raeburn  12606: sub cleanup_empty_dirs {
                   12607:     my ($path) = @_;
                   12608:     if (($path ne '') && (-d $path)) {
                   12609:         if (opendir(my $dirh,$path)) {
                   12610:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12611:             my $numitems = 0;
                   12612:             foreach my $item (@dircontents) {
                   12613:                 if (-d "$path/$item") {
1.1111    raeburn  12614:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12615:                     if (-e "$path/$item") {
                   12616:                         $numitems ++;
                   12617:                     }
                   12618:                 } else {
                   12619:                     $numitems ++;
                   12620:                 }
                   12621:             }
                   12622:             if ($numitems == 0) {
                   12623:                 rmdir($path);
                   12624:             }
                   12625:             closedir($dirh);
                   12626:         }
                   12627:     }
                   12628:     return;
                   12629: }
                   12630: 
1.41      ng       12631: =pod
1.45      matthew  12632: 
1.1162    raeburn  12633: =item * &get_folder_hierarchy()
1.1068    raeburn  12634: 
                   12635: Provides hierarchy of names of folders/sub-folders containing the current
                   12636: item,
                   12637: 
                   12638: Inputs: 3
                   12639:      - $navmap - navmaps object
                   12640: 
                   12641:      - $map - url for map (either the trigger itself, or map containing
                   12642:                            the resource, which is the trigger).
                   12643: 
                   12644:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12645: 
                   12646: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12647: 
                   12648: =cut
                   12649: 
                   12650: sub get_folder_hierarchy {
                   12651:     my ($navmap,$map,$showitem) = @_;
                   12652:     my @pathitems;
                   12653:     if (ref($navmap)) {
                   12654:         my $mapres = $navmap->getResourceByUrl($map);
                   12655:         if (ref($mapres)) {
                   12656:             my $pcslist = $mapres->map_hierarchy();
                   12657:             if ($pcslist ne '') {
                   12658:                 my @pcs = split(/,/,$pcslist);
                   12659:                 foreach my $pc (@pcs) {
                   12660:                     if ($pc == 1) {
1.1129    raeburn  12661:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12662:                     } else {
                   12663:                         my $res = $navmap->getByMapPc($pc);
                   12664:                         if (ref($res)) {
                   12665:                             my $title = $res->compTitle();
                   12666:                             $title =~ s/\W+/_/g;
                   12667:                             if ($title ne '') {
                   12668:                                 push(@pathitems,$title);
                   12669:                             }
                   12670:                         }
                   12671:                     }
                   12672:                 }
                   12673:             }
1.1071    raeburn  12674:             if ($showitem) {
                   12675:                 if ($mapres->{ID} eq '0.0') {
1.1129    raeburn  12676:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12677:                 } else {
                   12678:                     my $maptitle = $mapres->compTitle();
                   12679:                     $maptitle =~ s/\W+/_/g;
                   12680:                     if ($maptitle ne '') {
                   12681:                         push(@pathitems,$maptitle);
                   12682:                     }
1.1068    raeburn  12683:                 }
                   12684:             }
                   12685:         }
                   12686:     }
                   12687:     return @pathitems;
                   12688: }
                   12689: 
                   12690: =pod
                   12691: 
1.1015    raeburn  12692: =item * &get_turnedin_filepath()
                   12693: 
                   12694: Determines path in a user's portfolio file for storage of files uploaded
                   12695: to a specific essayresponse or dropbox item.
                   12696: 
                   12697: Inputs: 3 required + 1 optional.
                   12698: $symb is symb for resource, $uname and $udom are for current user (required).
                   12699: $caller is optional (can be "submission", if routine is called when storing
                   12700: an upoaded file when "Submit Answer" button was pressed).
                   12701: 
                   12702: Returns array containing $path and $multiresp. 
                   12703: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12704: than one file upload item.  Callers of routine should append partid as a 
                   12705: subdirectory to $path in cases where $multiresp is 1.
                   12706: 
                   12707: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12708: 
                   12709: =cut
                   12710: 
                   12711: sub get_turnedin_filepath {
                   12712:     my ($symb,$uname,$udom,$caller) = @_;
                   12713:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12714:     my $turnindir;
                   12715:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12716:     $turnindir = $userhash{'turnindir'};
                   12717:     my ($path,$multiresp);
                   12718:     if ($turnindir eq '') {
                   12719:         if ($caller eq 'submission') {
                   12720:             $turnindir = &mt('turned in');
                   12721:             $turnindir =~ s/\W+/_/g;
                   12722:             my %newhash = (
                   12723:                             'turnindir' => $turnindir,
                   12724:                           );
                   12725:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12726:         }
                   12727:     }
                   12728:     if ($turnindir ne '') {
                   12729:         $path = '/'.$turnindir.'/';
                   12730:         my ($multipart,$turnin,@pathitems);
                   12731:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12732:         if (defined($navmap)) {
                   12733:             my $mapres = $navmap->getResourceByUrl($map);
                   12734:             if (ref($mapres)) {
                   12735:                 my $pcslist = $mapres->map_hierarchy();
                   12736:                 if ($pcslist ne '') {
                   12737:                     foreach my $pc (split(/,/,$pcslist)) {
                   12738:                         my $res = $navmap->getByMapPc($pc);
                   12739:                         if (ref($res)) {
                   12740:                             my $title = $res->compTitle();
                   12741:                             $title =~ s/\W+/_/g;
                   12742:                             if ($title ne '') {
1.1149    raeburn  12743:                                 if (($pc > 1) && (length($title) > 12)) {
                   12744:                                     $title = substr($title,0,12);
                   12745:                                 }
1.1015    raeburn  12746:                                 push(@pathitems,$title);
                   12747:                             }
                   12748:                         }
                   12749:                     }
                   12750:                 }
                   12751:                 my $maptitle = $mapres->compTitle();
                   12752:                 $maptitle =~ s/\W+/_/g;
                   12753:                 if ($maptitle ne '') {
1.1149    raeburn  12754:                     if (length($maptitle) > 12) {
                   12755:                         $maptitle = substr($maptitle,0,12);
                   12756:                     }
1.1015    raeburn  12757:                     push(@pathitems,$maptitle);
                   12758:                 }
                   12759:                 unless ($env{'request.state'} eq 'construct') {
                   12760:                     my $res = $navmap->getBySymb($symb);
                   12761:                     if (ref($res)) {
                   12762:                         my $partlist = $res->parts();
                   12763:                         my $totaluploads = 0;
                   12764:                         if (ref($partlist) eq 'ARRAY') {
                   12765:                             foreach my $part (@{$partlist}) {
                   12766:                                 my @types = $res->responseType($part);
                   12767:                                 my @ids = $res->responseIds($part);
                   12768:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12769:                                     if ($types[$i] eq 'essay') {
                   12770:                                         my $partid = $part.'_'.$ids[$i];
                   12771:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12772:                                             $totaluploads ++;
                   12773:                                         }
                   12774:                                     }
                   12775:                                 }
                   12776:                             }
                   12777:                             if ($totaluploads > 1) {
                   12778:                                 $multiresp = 1;
                   12779:                             }
                   12780:                         }
                   12781:                     }
                   12782:                 }
                   12783:             } else {
                   12784:                 return;
                   12785:             }
                   12786:         } else {
                   12787:             return;
                   12788:         }
                   12789:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12790:         $restitle =~ s/\W+/_/g;
                   12791:         if ($restitle eq '') {
                   12792:             $restitle = ($resurl =~ m{/[^/]+$});
                   12793:             if ($restitle eq '') {
                   12794:                 $restitle = time;
                   12795:             }
                   12796:         }
1.1149    raeburn  12797:         if (length($restitle) > 12) {
                   12798:             $restitle = substr($restitle,0,12);
                   12799:         }
1.1015    raeburn  12800:         push(@pathitems,$restitle);
                   12801:         $path .= join('/',@pathitems);
                   12802:     }
                   12803:     return ($path,$multiresp);
                   12804: }
                   12805: 
                   12806: =pod
                   12807: 
1.464     albertel 12808: =back
1.41      ng       12809: 
1.112     bowersj2 12810: =head1 CSV Upload/Handling functions
1.38      albertel 12811: 
1.41      ng       12812: =over 4
                   12813: 
1.648     raeburn  12814: =item * &upfile_store($r)
1.41      ng       12815: 
                   12816: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12817: needs $env{'form.upfile'}
1.41      ng       12818: returns $datatoken to be put into hidden field
                   12819: 
                   12820: =cut
1.31      albertel 12821: 
                   12822: sub upfile_store {
                   12823:     my $r=shift;
1.258     albertel 12824:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12825:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12826:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12827:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12828: 
1.258     albertel 12829:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12830: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12831:     {
1.158     raeburn  12832:         my $datafile = $r->dir_config('lonDaemons').
                   12833:                            '/tmp/'.$datatoken.'.tmp';
                   12834:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12835:             print $fh $env{'form.upfile'};
1.158     raeburn  12836:             close($fh);
                   12837:         }
1.31      albertel 12838:     }
                   12839:     return $datatoken;
                   12840: }
                   12841: 
1.56      matthew  12842: =pod
                   12843: 
1.648     raeburn  12844: =item * &load_tmp_file($r)
1.41      ng       12845: 
                   12846: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12847: needs $env{'form.datatoken'},
                   12848: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12849: 
                   12850: =cut
1.31      albertel 12851: 
                   12852: sub load_tmp_file {
                   12853:     my $r=shift;
                   12854:     my @studentdata=();
                   12855:     {
1.158     raeburn  12856:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12857:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12858:         if ( open(my $fh,"<$studentfile") ) {
                   12859:             @studentdata=<$fh>;
                   12860:             close($fh);
                   12861:         }
1.31      albertel 12862:     }
1.258     albertel 12863:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12864: }
                   12865: 
1.56      matthew  12866: =pod
                   12867: 
1.648     raeburn  12868: =item * &upfile_record_sep()
1.41      ng       12869: 
                   12870: Separate uploaded file into records
                   12871: returns array of records,
1.258     albertel 12872: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12873: 
                   12874: =cut
1.31      albertel 12875: 
                   12876: sub upfile_record_sep {
1.258     albertel 12877:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12878:     } else {
1.248     albertel 12879: 	my @records;
1.258     albertel 12880: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12881: 	    if ($line=~/^\s*$/) { next; }
                   12882: 	    push(@records,$line);
                   12883: 	}
                   12884: 	return @records;
1.31      albertel 12885:     }
                   12886: }
                   12887: 
1.56      matthew  12888: =pod
                   12889: 
1.648     raeburn  12890: =item * &record_sep($record)
1.41      ng       12891: 
1.258     albertel 12892: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12893: 
                   12894: =cut
                   12895: 
1.263     www      12896: sub takeleft {
                   12897:     my $index=shift;
                   12898:     return substr('0000'.$index,-4,4);
                   12899: }
                   12900: 
1.31      albertel 12901: sub record_sep {
                   12902:     my $record=shift;
                   12903:     my %components=();
1.258     albertel 12904:     if ($env{'form.upfiletype'} eq 'xml') {
                   12905:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12906:         my $i=0;
1.356     albertel 12907:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12908:             $field=~s/^(\"|\')//;
                   12909:             $field=~s/(\"|\')$//;
1.263     www      12910:             $components{&takeleft($i)}=$field;
1.31      albertel 12911:             $i++;
                   12912:         }
1.258     albertel 12913:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12914:         my $i=0;
1.356     albertel 12915:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12916:             $field=~s/^(\"|\')//;
                   12917:             $field=~s/(\"|\')$//;
1.263     www      12918:             $components{&takeleft($i)}=$field;
1.31      albertel 12919:             $i++;
                   12920:         }
                   12921:     } else {
1.561     www      12922:         my $separator=',';
1.480     banghart 12923:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12924:             $separator=';';
1.480     banghart 12925:         }
1.31      albertel 12926:         my $i=0;
1.561     www      12927: # the character we are looking for to indicate the end of a quote or a record 
                   12928:         my $looking_for=$separator;
                   12929: # do not add the characters to the fields
                   12930:         my $ignore=0;
                   12931: # we just encountered a separator (or the beginning of the record)
                   12932:         my $just_found_separator=1;
                   12933: # store the field we are working on here
                   12934:         my $field='';
                   12935: # work our way through all characters in record
                   12936:         foreach my $character ($record=~/(.)/g) {
                   12937:             if ($character eq $looking_for) {
                   12938:                if ($character ne $separator) {
                   12939: # Found the end of a quote, again looking for separator
                   12940:                   $looking_for=$separator;
                   12941:                   $ignore=1;
                   12942:                } else {
                   12943: # Found a separator, store away what we got
                   12944:                   $components{&takeleft($i)}=$field;
                   12945: 	          $i++;
                   12946:                   $just_found_separator=1;
                   12947:                   $ignore=0;
                   12948:                   $field='';
                   12949:                }
                   12950:                next;
                   12951:             }
                   12952: # single or double quotation marks after a separator indicate beginning of a quote
                   12953: # we are now looking for the end of the quote and need to ignore separators
                   12954:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12955:                $looking_for=$character;
                   12956:                next;
                   12957:             }
                   12958: # ignore would be true after we reached the end of a quote
                   12959:             if ($ignore) { next; }
                   12960:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12961:             $field.=$character;
                   12962:             $just_found_separator=0; 
1.31      albertel 12963:         }
1.561     www      12964: # catch the very last entry, since we never encountered the separator
                   12965:         $components{&takeleft($i)}=$field;
1.31      albertel 12966:     }
                   12967:     return %components;
                   12968: }
                   12969: 
1.144     matthew  12970: ######################################################
                   12971: ######################################################
                   12972: 
1.56      matthew  12973: =pod
                   12974: 
1.648     raeburn  12975: =item * &upfile_select_html()
1.41      ng       12976: 
1.144     matthew  12977: Return HTML code to select a file from the users machine and specify 
                   12978: the file type.
1.41      ng       12979: 
                   12980: =cut
                   12981: 
1.144     matthew  12982: ######################################################
                   12983: ######################################################
1.31      albertel 12984: sub upfile_select_html {
1.144     matthew  12985:     my %Types = (
                   12986:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12987:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12988:                  space => &mt('Space separated'),
                   12989:                  tab   => &mt('Tabulator separated'),
                   12990: #                 xml   => &mt('HTML/XML'),
                   12991:                  );
                   12992:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12993:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12994:     foreach my $type (sort(keys(%Types))) {
                   12995:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12996:     }
                   12997:     $Str .= "</select>\n";
                   12998:     return $Str;
1.31      albertel 12999: }
                   13000: 
1.301     albertel 13001: sub get_samples {
                   13002:     my ($records,$toget) = @_;
                   13003:     my @samples=({});
                   13004:     my $got=0;
                   13005:     foreach my $rec (@$records) {
                   13006: 	my %temp = &record_sep($rec);
                   13007: 	if (! grep(/\S/, values(%temp))) { next; }
                   13008: 	if (%temp) {
                   13009: 	    $samples[$got]=\%temp;
                   13010: 	    $got++;
                   13011: 	    if ($got == $toget) { last; }
                   13012: 	}
                   13013:     }
                   13014:     return \@samples;
                   13015: }
                   13016: 
1.144     matthew  13017: ######################################################
                   13018: ######################################################
                   13019: 
1.56      matthew  13020: =pod
                   13021: 
1.648     raeburn  13022: =item * &csv_print_samples($r,$records)
1.41      ng       13023: 
                   13024: Prints a table of sample values from each column uploaded $r is an
                   13025: Apache Request ref, $records is an arrayref from
                   13026: &Apache::loncommon::upfile_record_sep
                   13027: 
                   13028: =cut
                   13029: 
1.144     matthew  13030: ######################################################
                   13031: ######################################################
1.31      albertel 13032: sub csv_print_samples {
                   13033:     my ($r,$records) = @_;
1.662     bisitz   13034:     my $samples = &get_samples($records,5);
1.301     albertel 13035: 
1.594     raeburn  13036:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13037:               &start_data_table_header_row());
1.356     albertel 13038:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13039:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13040:     $r->print(&end_data_table_header_row());
1.301     albertel 13041:     foreach my $hash (@$samples) {
1.594     raeburn  13042: 	$r->print(&start_data_table_row());
1.356     albertel 13043: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13044: 	    $r->print('<td>');
1.356     albertel 13045: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13046: 	    $r->print('</td>');
                   13047: 	}
1.594     raeburn  13048: 	$r->print(&end_data_table_row());
1.31      albertel 13049:     }
1.594     raeburn  13050:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13051: }
                   13052: 
1.144     matthew  13053: ######################################################
                   13054: ######################################################
                   13055: 
1.56      matthew  13056: =pod
                   13057: 
1.648     raeburn  13058: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13059: 
                   13060: Prints a table to create associations between values and table columns.
1.144     matthew  13061: 
1.41      ng       13062: $r is an Apache Request ref,
                   13063: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13064: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13065: 
                   13066: =cut
                   13067: 
1.144     matthew  13068: ######################################################
                   13069: ######################################################
1.31      albertel 13070: sub csv_print_select_table {
                   13071:     my ($r,$records,$d) = @_;
1.301     albertel 13072:     my $i=0;
                   13073:     my $samples = &get_samples($records,1);
1.144     matthew  13074:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13075: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13076:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13077:               '<th>'.&mt('Column').'</th>'.
                   13078:               &end_data_table_header_row()."\n");
1.356     albertel 13079:     foreach my $array_ref (@$d) {
                   13080: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13081: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13082: 
1.875     bisitz   13083: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13084: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13085: 	$r->print('<option value="none"></option>');
1.356     albertel 13086: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13087: 	    $r->print('<option value="'.$sample.'"'.
                   13088:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13089:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13090: 	}
1.594     raeburn  13091: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13092: 	$i++;
                   13093:     }
1.594     raeburn  13094:     $r->print(&end_data_table());
1.31      albertel 13095:     $i--;
                   13096:     return $i;
                   13097: }
1.56      matthew  13098: 
1.144     matthew  13099: ######################################################
                   13100: ######################################################
                   13101: 
1.56      matthew  13102: =pod
1.31      albertel 13103: 
1.648     raeburn  13104: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13105: 
                   13106: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13107: 
                   13108: $r is an Apache Request ref,
                   13109: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13110: $d is an array of 2 element arrays (internal name, displayed name)
                   13111: 
                   13112: =cut
                   13113: 
1.144     matthew  13114: ######################################################
                   13115: ######################################################
1.31      albertel 13116: sub csv_samples_select_table {
                   13117:     my ($r,$records,$d) = @_;
                   13118:     my $i=0;
1.144     matthew  13119:     #
1.662     bisitz   13120:     my $max_samples = 5;
                   13121:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13122:     $r->print(&start_data_table().
                   13123:               &start_data_table_header_row().'<th>'.
                   13124:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13125:               &end_data_table_header_row());
1.301     albertel 13126: 
                   13127:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13128: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13129: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13130: 	foreach my $option (@$d) {
                   13131: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13132: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13133:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13134:                       $display.'</option>');
1.31      albertel 13135: 	}
                   13136: 	$r->print('</select></td><td>');
1.662     bisitz   13137: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13138: 	    if (defined($samples->[$line]{$key})) { 
                   13139: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13140: 	    }
                   13141: 	}
1.594     raeburn  13142: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13143: 	$i++;
                   13144:     }
1.594     raeburn  13145:     $r->print(&end_data_table());
1.31      albertel 13146:     $i--;
                   13147:     return($i);
1.115     matthew  13148: }
                   13149: 
1.144     matthew  13150: ######################################################
                   13151: ######################################################
                   13152: 
1.115     matthew  13153: =pod
                   13154: 
1.648     raeburn  13155: =item * &clean_excel_name($name)
1.115     matthew  13156: 
                   13157: Returns a replacement for $name which does not contain any illegal characters.
                   13158: 
                   13159: =cut
                   13160: 
1.144     matthew  13161: ######################################################
                   13162: ######################################################
1.115     matthew  13163: sub clean_excel_name {
                   13164:     my ($name) = @_;
                   13165:     $name =~ s/[:\*\?\/\\]//g;
                   13166:     if (length($name) > 31) {
                   13167:         $name = substr($name,0,31);
                   13168:     }
                   13169:     return $name;
1.25      albertel 13170: }
1.84      albertel 13171: 
1.85      albertel 13172: =pod
                   13173: 
1.648     raeburn  13174: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13175: 
                   13176: Returns either 1 or undef
                   13177: 
                   13178: 1 if the part is to be hidden, undef if it is to be shown
                   13179: 
                   13180: Arguments are:
                   13181: 
                   13182: $id the id of the part to be checked
                   13183: $symb, optional the symb of the resource to check
                   13184: $udom, optional the domain of the user to check for
                   13185: $uname, optional the username of the user to check for
                   13186: 
                   13187: =cut
1.84      albertel 13188: 
                   13189: sub check_if_partid_hidden {
                   13190:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13191:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13192: 					 $symb,$udom,$uname);
1.141     albertel 13193:     my $truth=1;
                   13194:     #if the string starts with !, then the list is the list to show not hide
                   13195:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13196:     my @hiddenlist=split(/,/,$hiddenparts);
                   13197:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13198: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13199:     }
1.141     albertel 13200:     return !$truth;
1.84      albertel 13201: }
1.127     matthew  13202: 
1.138     matthew  13203: 
                   13204: ############################################################
                   13205: ############################################################
                   13206: 
                   13207: =pod
                   13208: 
1.157     matthew  13209: =back 
                   13210: 
1.138     matthew  13211: =head1 cgi-bin script and graphing routines
                   13212: 
1.157     matthew  13213: =over 4
                   13214: 
1.648     raeburn  13215: =item * &get_cgi_id()
1.138     matthew  13216: 
                   13217: Inputs: none
                   13218: 
                   13219: Returns an id which can be used to pass environment variables
                   13220: to various cgi-bin scripts.  These environment variables will
                   13221: be removed from the users environment after a given time by
                   13222: the routine &Apache::lonnet::transfer_profile_to_env.
                   13223: 
                   13224: =cut
                   13225: 
                   13226: ############################################################
                   13227: ############################################################
1.152     albertel 13228: my $uniq=0;
1.136     matthew  13229: sub get_cgi_id {
1.154     albertel 13230:     $uniq=($uniq+1)%100000;
1.280     albertel 13231:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13232: }
                   13233: 
1.127     matthew  13234: ############################################################
                   13235: ############################################################
                   13236: 
                   13237: =pod
                   13238: 
1.648     raeburn  13239: =item * &DrawBarGraph()
1.127     matthew  13240: 
1.138     matthew  13241: Facilitates the plotting of data in a (stacked) bar graph.
                   13242: Puts plot definition data into the users environment in order for 
                   13243: graph.png to plot it.  Returns an <img> tag for the plot.
                   13244: The bars on the plot are labeled '1','2',...,'n'.
                   13245: 
                   13246: Inputs:
                   13247: 
                   13248: =over 4
                   13249: 
                   13250: =item $Title: string, the title of the plot
                   13251: 
                   13252: =item $xlabel: string, text describing the X-axis of the plot
                   13253: 
                   13254: =item $ylabel: string, text describing the Y-axis of the plot
                   13255: 
                   13256: =item $Max: scalar, the maximum Y value to use in the plot
                   13257: If $Max is < any data point, the graph will not be rendered.
                   13258: 
1.140     matthew  13259: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13260: they are plotted.  If undefined, default values will be used.
                   13261: 
1.178     matthew  13262: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13263: 
1.138     matthew  13264: =item @Values: An array of array references.  Each array reference holds data
                   13265: to be plotted in a stacked bar chart.
                   13266: 
1.239     matthew  13267: =item If the final element of @Values is a hash reference the key/value
                   13268: pairs will be added to the graph definition.
                   13269: 
1.138     matthew  13270: =back
                   13271: 
                   13272: Returns:
                   13273: 
                   13274: An <img> tag which references graph.png and the appropriate identifying
                   13275: information for the plot.
                   13276: 
1.127     matthew  13277: =cut
                   13278: 
                   13279: ############################################################
                   13280: ############################################################
1.134     matthew  13281: sub DrawBarGraph {
1.178     matthew  13282:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13283:     #
                   13284:     if (! defined($colors)) {
                   13285:         $colors = ['#33ff00', 
                   13286:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13287:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13288:                   ]; 
                   13289:     }
1.228     matthew  13290:     my $extra_settings = {};
                   13291:     if (ref($Values[-1]) eq 'HASH') {
                   13292:         $extra_settings = pop(@Values);
                   13293:     }
1.127     matthew  13294:     #
1.136     matthew  13295:     my $identifier = &get_cgi_id();
                   13296:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13297:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13298:         return '';
                   13299:     }
1.225     matthew  13300:     #
                   13301:     my @Labels;
                   13302:     if (defined($labels)) {
                   13303:         @Labels = @$labels;
                   13304:     } else {
                   13305:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13306:             push (@Labels,$i+1);
                   13307:         }
                   13308:     }
                   13309:     #
1.129     matthew  13310:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13311:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13312:     my %ValuesHash;
                   13313:     my $NumSets=1;
                   13314:     foreach my $array (@Values) {
                   13315:         next if (! ref($array));
1.136     matthew  13316:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13317:             join(',',@$array);
1.129     matthew  13318:     }
1.127     matthew  13319:     #
1.136     matthew  13320:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13321:     if ($NumBars < 3) {
                   13322:         $width = 120+$NumBars*32;
1.220     matthew  13323:         $xskip = 1;
1.225     matthew  13324:         $bar_width = 30;
                   13325:     } elsif ($NumBars < 5) {
                   13326:         $width = 120+$NumBars*20;
                   13327:         $xskip = 1;
                   13328:         $bar_width = 20;
1.220     matthew  13329:     } elsif ($NumBars < 10) {
1.136     matthew  13330:         $width = 120+$NumBars*15;
                   13331:         $xskip = 1;
                   13332:         $bar_width = 15;
                   13333:     } elsif ($NumBars <= 25) {
                   13334:         $width = 120+$NumBars*11;
                   13335:         $xskip = 5;
                   13336:         $bar_width = 8;
                   13337:     } elsif ($NumBars <= 50) {
                   13338:         $width = 120+$NumBars*8;
                   13339:         $xskip = 5;
                   13340:         $bar_width = 4;
                   13341:     } else {
                   13342:         $width = 120+$NumBars*8;
                   13343:         $xskip = 5;
                   13344:         $bar_width = 4;
                   13345:     }
                   13346:     #
1.137     matthew  13347:     $Max = 1 if ($Max < 1);
                   13348:     if ( int($Max) < $Max ) {
                   13349:         $Max++;
                   13350:         $Max = int($Max);
                   13351:     }
1.127     matthew  13352:     $Title  = '' if (! defined($Title));
                   13353:     $xlabel = '' if (! defined($xlabel));
                   13354:     $ylabel = '' if (! defined($ylabel));
1.369     www      13355:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13356:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13357:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13358:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13359:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13360:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13361:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13362:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13363:     $ValuesHash{$id.'.height'}   = $height;
                   13364:     $ValuesHash{$id.'.width'}    = $width;
                   13365:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13366:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13367:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13368:     #
1.228     matthew  13369:     # Deal with other parameters
                   13370:     while (my ($key,$value) = each(%$extra_settings)) {
                   13371:         $ValuesHash{$id.'.'.$key} = $value;
                   13372:     }
                   13373:     #
1.646     raeburn  13374:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13375:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13376: }
                   13377: 
                   13378: ############################################################
                   13379: ############################################################
                   13380: 
                   13381: =pod
                   13382: 
1.648     raeburn  13383: =item * &DrawXYGraph()
1.137     matthew  13384: 
1.138     matthew  13385: Facilitates the plotting of data in an XY graph.
                   13386: Puts plot definition data into the users environment in order for 
                   13387: graph.png to plot it.  Returns an <img> tag for the plot.
                   13388: 
                   13389: Inputs:
                   13390: 
                   13391: =over 4
                   13392: 
                   13393: =item $Title: string, the title of the plot
                   13394: 
                   13395: =item $xlabel: string, text describing the X-axis of the plot
                   13396: 
                   13397: =item $ylabel: string, text describing the Y-axis of the plot
                   13398: 
                   13399: =item $Max: scalar, the maximum Y value to use in the plot
                   13400: If $Max is < any data point, the graph will not be rendered.
                   13401: 
                   13402: =item $colors: Array ref containing the hex color codes for the data to be 
                   13403: plotted in.  If undefined, default values will be used.
                   13404: 
                   13405: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13406: 
                   13407: =item $Ydata: Array ref containing Array refs.  
1.185     www      13408: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13409: 
                   13410: =item %Values: hash indicating or overriding any default values which are 
                   13411: passed to graph.png.  
                   13412: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13413: 
                   13414: =back
                   13415: 
                   13416: Returns:
                   13417: 
                   13418: An <img> tag which references graph.png and the appropriate identifying
                   13419: information for the plot.
                   13420: 
1.137     matthew  13421: =cut
                   13422: 
                   13423: ############################################################
                   13424: ############################################################
                   13425: sub DrawXYGraph {
                   13426:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13427:     #
                   13428:     # Create the identifier for the graph
                   13429:     my $identifier = &get_cgi_id();
                   13430:     my $id = 'cgi.'.$identifier;
                   13431:     #
                   13432:     $Title  = '' if (! defined($Title));
                   13433:     $xlabel = '' if (! defined($xlabel));
                   13434:     $ylabel = '' if (! defined($ylabel));
                   13435:     my %ValuesHash = 
                   13436:         (
1.369     www      13437:          $id.'.title'  => &escape($Title),
                   13438:          $id.'.xlabel' => &escape($xlabel),
                   13439:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13440:          $id.'.y_max_value'=> $Max,
                   13441:          $id.'.labels'     => join(',',@$Xlabels),
                   13442:          $id.'.PlotType'   => 'XY',
                   13443:          );
                   13444:     #
                   13445:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13446:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13447:     }
                   13448:     #
                   13449:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13450:         return '';
                   13451:     }
                   13452:     my $NumSets=1;
1.138     matthew  13453:     foreach my $array (@{$Ydata}){
1.137     matthew  13454:         next if (! ref($array));
                   13455:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13456:     }
1.138     matthew  13457:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13458:     #
                   13459:     # Deal with other parameters
                   13460:     while (my ($key,$value) = each(%Values)) {
                   13461:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13462:     }
                   13463:     #
1.646     raeburn  13464:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13465:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13466: }
                   13467: 
                   13468: ############################################################
                   13469: ############################################################
                   13470: 
                   13471: =pod
                   13472: 
1.648     raeburn  13473: =item * &DrawXYYGraph()
1.138     matthew  13474: 
                   13475: Facilitates the plotting of data in an XY graph with two Y axes.
                   13476: Puts plot definition data into the users environment in order for 
                   13477: graph.png to plot it.  Returns an <img> tag for the plot.
                   13478: 
                   13479: Inputs:
                   13480: 
                   13481: =over 4
                   13482: 
                   13483: =item $Title: string, the title of the plot
                   13484: 
                   13485: =item $xlabel: string, text describing the X-axis of the plot
                   13486: 
                   13487: =item $ylabel: string, text describing the Y-axis of the plot
                   13488: 
                   13489: =item $colors: Array ref containing the hex color codes for the data to be 
                   13490: plotted in.  If undefined, default values will be used.
                   13491: 
                   13492: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13493: 
                   13494: =item $Ydata1: The first data set
                   13495: 
                   13496: =item $Min1: The minimum value of the left Y-axis
                   13497: 
                   13498: =item $Max1: The maximum value of the left Y-axis
                   13499: 
                   13500: =item $Ydata2: The second data set
                   13501: 
                   13502: =item $Min2: The minimum value of the right Y-axis
                   13503: 
                   13504: =item $Max2: The maximum value of the left Y-axis
                   13505: 
                   13506: =item %Values: hash indicating or overriding any default values which are 
                   13507: passed to graph.png.  
                   13508: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13509: 
                   13510: =back
                   13511: 
                   13512: Returns:
                   13513: 
                   13514: An <img> tag which references graph.png and the appropriate identifying
                   13515: information for the plot.
1.136     matthew  13516: 
                   13517: =cut
                   13518: 
                   13519: ############################################################
                   13520: ############################################################
1.137     matthew  13521: sub DrawXYYGraph {
                   13522:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13523:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13524:     #
                   13525:     # Create the identifier for the graph
                   13526:     my $identifier = &get_cgi_id();
                   13527:     my $id = 'cgi.'.$identifier;
                   13528:     #
                   13529:     $Title  = '' if (! defined($Title));
                   13530:     $xlabel = '' if (! defined($xlabel));
                   13531:     $ylabel = '' if (! defined($ylabel));
                   13532:     my %ValuesHash = 
                   13533:         (
1.369     www      13534:          $id.'.title'  => &escape($Title),
                   13535:          $id.'.xlabel' => &escape($xlabel),
                   13536:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13537:          $id.'.labels' => join(',',@$Xlabels),
                   13538:          $id.'.PlotType' => 'XY',
                   13539:          $id.'.NumSets' => 2,
1.137     matthew  13540:          $id.'.two_axes' => 1,
                   13541:          $id.'.y1_max_value' => $Max1,
                   13542:          $id.'.y1_min_value' => $Min1,
                   13543:          $id.'.y2_max_value' => $Max2,
                   13544:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13545:          );
                   13546:     #
1.137     matthew  13547:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13548:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13549:     }
                   13550:     #
                   13551:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13552:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13553:         return '';
                   13554:     }
                   13555:     my $NumSets=1;
1.137     matthew  13556:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13557:         next if (! ref($array));
                   13558:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13559:     }
                   13560:     #
                   13561:     # Deal with other parameters
                   13562:     while (my ($key,$value) = each(%Values)) {
                   13563:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13564:     }
                   13565:     #
1.646     raeburn  13566:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13567:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13568: }
                   13569: 
                   13570: ############################################################
                   13571: ############################################################
                   13572: 
                   13573: =pod
                   13574: 
1.157     matthew  13575: =back 
                   13576: 
1.139     matthew  13577: =head1 Statistics helper routines?  
                   13578: 
                   13579: Bad place for them but what the hell.
                   13580: 
1.157     matthew  13581: =over 4
                   13582: 
1.648     raeburn  13583: =item * &chartlink()
1.139     matthew  13584: 
                   13585: Returns a link to the chart for a specific student.  
                   13586: 
                   13587: Inputs:
                   13588: 
                   13589: =over 4
                   13590: 
                   13591: =item $linktext: The text of the link
                   13592: 
                   13593: =item $sname: The students username
                   13594: 
                   13595: =item $sdomain: The students domain
                   13596: 
                   13597: =back
                   13598: 
1.157     matthew  13599: =back
                   13600: 
1.139     matthew  13601: =cut
                   13602: 
                   13603: ############################################################
                   13604: ############################################################
                   13605: sub chartlink {
                   13606:     my ($linktext, $sname, $sdomain) = @_;
                   13607:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13608:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13609:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13610:        '">'.$linktext.'</a>';
1.153     matthew  13611: }
                   13612: 
                   13613: #######################################################
                   13614: #######################################################
                   13615: 
                   13616: =pod
                   13617: 
                   13618: =head1 Course Environment Routines
1.157     matthew  13619: 
                   13620: =over 4
1.153     matthew  13621: 
1.648     raeburn  13622: =item * &restore_course_settings()
1.153     matthew  13623: 
1.648     raeburn  13624: =item * &store_course_settings()
1.153     matthew  13625: 
                   13626: Restores/Store indicated form parameters from the course environment.
                   13627: Will not overwrite existing values of the form parameters.
                   13628: 
                   13629: Inputs: 
                   13630: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13631: 
                   13632: a hash ref describing the data to be stored.  For example:
                   13633:    
                   13634: %Save_Parameters = ('Status' => 'scalar',
                   13635:     'chartoutputmode' => 'scalar',
                   13636:     'chartoutputdata' => 'scalar',
                   13637:     'Section' => 'array',
1.373     raeburn  13638:     'Group' => 'array',
1.153     matthew  13639:     'StudentData' => 'array',
                   13640:     'Maps' => 'array');
                   13641: 
                   13642: Returns: both routines return nothing
                   13643: 
1.631     raeburn  13644: =back
                   13645: 
1.153     matthew  13646: =cut
                   13647: 
                   13648: #######################################################
                   13649: #######################################################
                   13650: sub store_course_settings {
1.496     albertel 13651:     return &store_settings($env{'request.course.id'},@_);
                   13652: }
                   13653: 
                   13654: sub store_settings {
1.153     matthew  13655:     # save to the environment
                   13656:     # appenv the same items, just to be safe
1.300     albertel 13657:     my $udom  = $env{'user.domain'};
                   13658:     my $uname = $env{'user.name'};
1.496     albertel 13659:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13660:     my %SaveHash;
                   13661:     my %AppHash;
                   13662:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13663:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13664:         my $envname = 'environment.'.$basename;
1.258     albertel 13665:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13666:             # Save this value away
                   13667:             if ($type eq 'scalar' &&
1.258     albertel 13668:                 (! exists($env{$envname}) || 
                   13669:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13670:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13671:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13672:             } elsif ($type eq 'array') {
                   13673:                 my $stored_form;
1.258     albertel 13674:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13675:                     $stored_form = join(',',
                   13676:                                         map {
1.369     www      13677:                                             &escape($_);
1.258     albertel 13678:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13679:                 } else {
                   13680:                     $stored_form = 
1.369     www      13681:                         &escape($env{'form.'.$setting});
1.153     matthew  13682:                 }
                   13683:                 # Determine if the array contents are the same.
1.258     albertel 13684:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13685:                     $SaveHash{$basename} = $stored_form;
                   13686:                     $AppHash{$envname}   = $stored_form;
                   13687:                 }
                   13688:             }
                   13689:         }
                   13690:     }
                   13691:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13692:                                           $udom,$uname);
1.153     matthew  13693:     if ($put_result !~ /^(ok|delayed)/) {
                   13694:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13695:                                  'got error:'.$put_result);
                   13696:     }
                   13697:     # Make sure these settings stick around in this session, too
1.646     raeburn  13698:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13699:     return;
                   13700: }
                   13701: 
                   13702: sub restore_course_settings {
1.499     albertel 13703:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13704: }
                   13705: 
                   13706: sub restore_settings {
                   13707:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13708:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13709:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13710:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13711:             '.'.$setting;
1.258     albertel 13712:         if (exists($env{$envname})) {
1.153     matthew  13713:             if ($type eq 'scalar') {
1.258     albertel 13714:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13715:             } elsif ($type eq 'array') {
1.258     albertel 13716:                 $env{'form.'.$setting} = [ 
1.153     matthew  13717:                                            map { 
1.369     www      13718:                                                &unescape($_); 
1.258     albertel 13719:                                            } split(',',$env{$envname})
1.153     matthew  13720:                                            ];
                   13721:             }
                   13722:         }
                   13723:     }
1.127     matthew  13724: }
                   13725: 
1.618     raeburn  13726: #######################################################
                   13727: #######################################################
                   13728: 
                   13729: =pod
                   13730: 
                   13731: =head1 Domain E-mail Routines  
                   13732: 
                   13733: =over 4
                   13734: 
1.648     raeburn  13735: =item * &build_recipient_list()
1.618     raeburn  13736: 
1.1144    raeburn  13737: Build recipient lists for following types of e-mail:
1.766     raeburn  13738: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1144    raeburn  13739: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13740: module change checking, student/employee ID conflict checks, as
                   13741: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13742: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13743: 
                   13744: Inputs:
1.619     raeburn  13745: defmail (scalar - email address of default recipient), 
1.1144    raeburn  13746: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13747: requestsmail, updatesmail, or idconflictsmail).
                   13748: 
1.619     raeburn  13749: defdom (domain for which to retrieve configuration settings),
1.1144    raeburn  13750: 
1.619     raeburn  13751: origmail (scalar - email address of recipient from loncapa.conf, 
                   13752: i.e., predates configuration by DC via domainprefs.pm 
1.618     raeburn  13753: 
1.655     raeburn  13754: Returns: comma separated list of addresses to which to send e-mail.
                   13755: 
                   13756: =back
1.618     raeburn  13757: 
                   13758: =cut
                   13759: 
                   13760: ############################################################
                   13761: ############################################################
                   13762: sub build_recipient_list {
1.619     raeburn  13763:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13764:     my @recipients;
                   13765:     my $otheremails;
                   13766:     my %domconfig =
                   13767:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13768:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13769:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13770:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13771:                 my @contacts = ('adminemail','supportemail');
                   13772:                 foreach my $item (@contacts) {
                   13773:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13774:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13775:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13776:                             push(@recipients,$addr);
                   13777:                         }
1.619     raeburn  13778:                     }
1.766     raeburn  13779:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13780:                 }
                   13781:             }
1.766     raeburn  13782:         } elsif ($origmail ne '') {
                   13783:             push(@recipients,$origmail);
1.618     raeburn  13784:         }
1.619     raeburn  13785:     } elsif ($origmail ne '') {
                   13786:         push(@recipients,$origmail);
1.618     raeburn  13787:     }
1.688     raeburn  13788:     if (defined($defmail)) {
                   13789:         if ($defmail ne '') {
                   13790:             push(@recipients,$defmail);
                   13791:         }
1.618     raeburn  13792:     }
                   13793:     if ($otheremails) {
1.619     raeburn  13794:         my @others;
                   13795:         if ($otheremails =~ /,/) {
                   13796:             @others = split(/,/,$otheremails);
1.618     raeburn  13797:         } else {
1.619     raeburn  13798:             push(@others,$otheremails);
                   13799:         }
                   13800:         foreach my $addr (@others) {
                   13801:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13802:                 push(@recipients,$addr);
                   13803:             }
1.618     raeburn  13804:         }
                   13805:     }
1.619     raeburn  13806:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13807:     return $recipientlist;
                   13808: }
                   13809: 
1.127     matthew  13810: ############################################################
                   13811: ############################################################
1.154     albertel 13812: 
1.655     raeburn  13813: =pod
                   13814: 
                   13815: =head1 Course Catalog Routines
                   13816: 
                   13817: =over 4
                   13818: 
                   13819: =item * &gather_categories()
                   13820: 
                   13821: Converts category definitions - keys of categories hash stored in  
                   13822: coursecategories in configuration.db on the primary library server in a 
                   13823: domain - to an array.  Also generates javascript and idx hash used to 
                   13824: generate Domain Coordinator interface for editing Course Categories.
                   13825: 
                   13826: Inputs:
1.663     raeburn  13827: 
1.655     raeburn  13828: categories (reference to hash of category definitions).
1.663     raeburn  13829: 
1.655     raeburn  13830: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13831:       categories and subcategories).
1.663     raeburn  13832: 
1.655     raeburn  13833: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13834:       editing Course Categories).
1.663     raeburn  13835: 
1.655     raeburn  13836: jsarray (reference to array of categories used to create Javascript arrays for
                   13837:          Domain Coordinator interface for editing Course Categories).
                   13838: 
                   13839: Returns: nothing
                   13840: 
                   13841: Side effects: populates cats, idx and jsarray. 
                   13842: 
                   13843: =cut
                   13844: 
                   13845: sub gather_categories {
                   13846:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13847:     my %counters;
                   13848:     my $num = 0;
                   13849:     foreach my $item (keys(%{$categories})) {
                   13850:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13851:         if ($container eq '' && $depth == 0) {
                   13852:             $cats->[$depth][$categories->{$item}] = $cat;
                   13853:         } else {
                   13854:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13855:         }
                   13856:         my ($escitem,$tail) = split(/:/,$item,2);
                   13857:         if ($counters{$tail} eq '') {
                   13858:             $counters{$tail} = $num;
                   13859:             $num ++;
                   13860:         }
                   13861:         if (ref($idx) eq 'HASH') {
                   13862:             $idx->{$item} = $counters{$tail};
                   13863:         }
                   13864:         if (ref($jsarray) eq 'ARRAY') {
                   13865:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13866:         }
                   13867:     }
                   13868:     return;
                   13869: }
                   13870: 
                   13871: =pod
                   13872: 
                   13873: =item * &extract_categories()
                   13874: 
                   13875: Used to generate breadcrumb trails for course categories.
                   13876: 
                   13877: Inputs:
1.663     raeburn  13878: 
1.655     raeburn  13879: categories (reference to hash of category definitions).
1.663     raeburn  13880: 
1.655     raeburn  13881: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13882:       categories and subcategories).
1.663     raeburn  13883: 
1.655     raeburn  13884: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13885: 
1.655     raeburn  13886: allitems (reference to hash - key is category key 
                   13887:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13888: 
1.655     raeburn  13889: idx (reference to hash of counters used in Domain Coordinator interface for
                   13890:       editing Course Categories).
1.663     raeburn  13891: 
1.655     raeburn  13892: jsarray (reference to array of categories used to create Javascript arrays for
                   13893:          Domain Coordinator interface for editing Course Categories).
                   13894: 
1.665     raeburn  13895: subcats (reference to hash of arrays containing all subcategories within each 
                   13896:          category, -recursive)
                   13897: 
1.655     raeburn  13898: Returns: nothing
                   13899: 
                   13900: Side effects: populates trails and allitems hash references.
                   13901: 
                   13902: =cut
                   13903: 
                   13904: sub extract_categories {
1.665     raeburn  13905:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13906:     if (ref($categories) eq 'HASH') {
                   13907:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13908:         if (ref($cats->[0]) eq 'ARRAY') {
                   13909:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13910:                 my $name = $cats->[0][$i];
                   13911:                 my $item = &escape($name).'::0';
                   13912:                 my $trailstr;
                   13913:                 if ($name eq 'instcode') {
                   13914:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13915:                 } elsif ($name eq 'communities') {
                   13916:                     $trailstr = &mt('Communities');
1.655     raeburn  13917:                 } else {
                   13918:                     $trailstr = $name;
                   13919:                 }
                   13920:                 if ($allitems->{$item} eq '') {
                   13921:                     push(@{$trails},$trailstr);
                   13922:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13923:                 }
                   13924:                 my @parents = ($name);
                   13925:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13926:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13927:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13928:                         if (ref($subcats) eq 'HASH') {
                   13929:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13930:                         }
                   13931:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13932:                     }
                   13933:                 } else {
                   13934:                     if (ref($subcats) eq 'HASH') {
                   13935:                         $subcats->{$item} = [];
1.655     raeburn  13936:                     }
                   13937:                 }
                   13938:             }
                   13939:         }
                   13940:     }
                   13941:     return;
                   13942: }
                   13943: 
                   13944: =pod
                   13945: 
1.1162    raeburn  13946: =item * &recurse_categories()
1.655     raeburn  13947: 
                   13948: Recursively used to generate breadcrumb trails for course categories.
                   13949: 
                   13950: Inputs:
1.663     raeburn  13951: 
1.655     raeburn  13952: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13953:       categories and subcategories).
1.663     raeburn  13954: 
1.655     raeburn  13955: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13956: 
                   13957: category (current course category, for which breadcrumb trail is being generated).
                   13958: 
                   13959: trails (reference to array of breadcrumb trails for each category).
                   13960: 
1.655     raeburn  13961: allitems (reference to hash - key is category key
                   13962:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13963: 
1.655     raeburn  13964: parents (array containing containers directories for current category, 
                   13965:          back to top level). 
                   13966: 
                   13967: Returns: nothing
                   13968: 
                   13969: Side effects: populates trails and allitems hash references
                   13970: 
                   13971: =cut
                   13972: 
                   13973: sub recurse_categories {
1.665     raeburn  13974:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13975:     my $shallower = $depth - 1;
                   13976:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13977:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13978:             my $name = $cats->[$depth]{$category}[$k];
                   13979:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13980:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13981:             if ($allitems->{$item} eq '') {
                   13982:                 push(@{$trails},$trailstr);
                   13983:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13984:             }
                   13985:             my $deeper = $depth+1;
                   13986:             push(@{$parents},$category);
1.665     raeburn  13987:             if (ref($subcats) eq 'HASH') {
                   13988:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13989:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13990:                     my $higher;
                   13991:                     if ($j > 0) {
                   13992:                         $higher = &escape($parents->[$j]).':'.
                   13993:                                   &escape($parents->[$j-1]).':'.$j;
                   13994:                     } else {
                   13995:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13996:                     }
                   13997:                     push(@{$subcats->{$higher}},$subcat);
                   13998:                 }
                   13999:             }
                   14000:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   14001:                                 $subcats);
1.655     raeburn  14002:             pop(@{$parents});
                   14003:         }
                   14004:     } else {
                   14005:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14006:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14007:         if ($allitems->{$item} eq '') {
                   14008:             push(@{$trails},$trailstr);
                   14009:             $allitems->{$item} = scalar(@{$trails})-1;
                   14010:         }
                   14011:     }
                   14012:     return;
                   14013: }
                   14014: 
1.663     raeburn  14015: =pod
                   14016: 
1.1162    raeburn  14017: =item * &assign_categories_table()
1.663     raeburn  14018: 
                   14019: Create a datatable for display of hierarchical categories in a domain,
                   14020: with checkboxes to allow a course to be categorized. 
                   14021: 
                   14022: Inputs:
                   14023: 
                   14024: cathash - reference to hash of categories defined for the domain (from
                   14025:           configuration.db)
                   14026: 
                   14027: currcat - scalar with an & separated list of categories assigned to a course. 
                   14028: 
1.919     raeburn  14029: type    - scalar contains course type (Course or Community).
                   14030: 
1.663     raeburn  14031: Returns: $output (markup to be displayed) 
                   14032: 
                   14033: =cut
                   14034: 
                   14035: sub assign_categories_table {
1.919     raeburn  14036:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  14037:     my $output;
                   14038:     if (ref($cathash) eq 'HASH') {
                   14039:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   14040:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   14041:         $maxdepth = scalar(@cats);
                   14042:         if (@cats > 0) {
                   14043:             my $itemcount = 0;
                   14044:             if (ref($cats[0]) eq 'ARRAY') {
                   14045:                 my @currcategories;
                   14046:                 if ($currcat ne '') {
                   14047:                     @currcategories = split('&',$currcat);
                   14048:                 }
1.919     raeburn  14049:                 my $table;
1.663     raeburn  14050:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14051:                     my $parent = $cats[0][$i];
1.919     raeburn  14052:                     next if ($parent eq 'instcode');
                   14053:                     if ($type eq 'Community') {
                   14054:                         next unless ($parent eq 'communities');
                   14055:                     } else {
                   14056:                         next if ($parent eq 'communities');
                   14057:                     }
1.663     raeburn  14058:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14059:                     my $item = &escape($parent).'::0';
                   14060:                     my $checked = '';
                   14061:                     if (@currcategories > 0) {
                   14062:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14063:                             $checked = ' checked="checked"';
1.663     raeburn  14064:                         }
                   14065:                     }
1.919     raeburn  14066:                     my $parent_title = $parent;
                   14067:                     if ($parent eq 'communities') {
                   14068:                         $parent_title = &mt('Communities');
                   14069:                     }
                   14070:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14071:                               '<input type="checkbox" name="usecategory" value="'.
                   14072:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   14073:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14074:                     my $depth = 1;
                   14075:                     push(@path,$parent);
1.919     raeburn  14076:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  14077:                     pop(@path);
1.919     raeburn  14078:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14079:                     $itemcount ++;
                   14080:                 }
1.919     raeburn  14081:                 if ($itemcount) {
                   14082:                     $output = &Apache::loncommon::start_data_table().
                   14083:                               $table.
                   14084:                               &Apache::loncommon::end_data_table();
                   14085:                 }
1.663     raeburn  14086:             }
                   14087:         }
                   14088:     }
                   14089:     return $output;
                   14090: }
                   14091: 
                   14092: =pod
                   14093: 
1.1162    raeburn  14094: =item * &assign_category_rows()
1.663     raeburn  14095: 
                   14096: Create a datatable row for display of nested categories in a domain,
                   14097: with checkboxes to allow a course to be categorized,called recursively.
                   14098: 
                   14099: Inputs:
                   14100: 
                   14101: itemcount - track row number for alternating colors
                   14102: 
                   14103: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14104:       categories and subcategories.
                   14105: 
                   14106: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14107: 
                   14108: parent - parent of current category item
                   14109: 
                   14110: path - Array containing all categories back up through the hierarchy from the
                   14111:        current category to the top level.
                   14112: 
                   14113: currcategories - reference to array of current categories assigned to the course
                   14114: 
                   14115: Returns: $output (markup to be displayed).
                   14116: 
                   14117: =cut
                   14118: 
                   14119: sub assign_category_rows {
                   14120:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   14121:     my ($text,$name,$item,$chgstr);
                   14122:     if (ref($cats) eq 'ARRAY') {
                   14123:         my $maxdepth = scalar(@{$cats});
                   14124:         if (ref($cats->[$depth]) eq 'HASH') {
                   14125:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14126:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14127:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1145    raeburn  14128:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14129:                 for (my $j=0; $j<$numchildren; $j++) {
                   14130:                     $name = $cats->[$depth]{$parent}[$j];
                   14131:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14132:                     my $deeper = $depth+1;
                   14133:                     my $checked = '';
                   14134:                     if (ref($currcategories) eq 'ARRAY') {
                   14135:                         if (@{$currcategories} > 0) {
                   14136:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14137:                                 $checked = ' checked="checked"';
1.663     raeburn  14138:                             }
                   14139:                         }
                   14140:                     }
1.664     raeburn  14141:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14142:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  14143:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   14144:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14145:                              '</td><td>';
1.663     raeburn  14146:                     if (ref($path) eq 'ARRAY') {
                   14147:                         push(@{$path},$name);
                   14148:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   14149:                         pop(@{$path});
                   14150:                     }
                   14151:                     $text .= '</td></tr>';
                   14152:                 }
                   14153:                 $text .= '</table></td>';
                   14154:             }
                   14155:         }
                   14156:     }
                   14157:     return $text;
                   14158: }
                   14159: 
1.1181    raeburn  14160: =pod
                   14161: 
                   14162: =back
                   14163: 
                   14164: =cut
                   14165: 
1.655     raeburn  14166: ############################################################
                   14167: ############################################################
                   14168: 
                   14169: 
1.443     albertel 14170: sub commit_customrole {
1.664     raeburn  14171:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14172:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14173:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14174:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14175:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14176:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14177:                  '</b><br />';
                   14178:     return $output;
                   14179: }
                   14180: 
                   14181: sub commit_standardrole {
1.1116    raeburn  14182:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14183:     my ($output,$logmsg,$linefeed);
                   14184:     if ($context eq 'auto') {
                   14185:         $linefeed = "\n";
                   14186:     } else {
                   14187:         $linefeed = "<br />\n";
                   14188:     }  
1.443     albertel 14189:     if ($three eq 'st') {
1.541     raeburn  14190:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1116    raeburn  14191:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14192:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14193:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14194:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14195:         } else {
1.541     raeburn  14196:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14197:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14198:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14199:             if ($context eq 'auto') {
                   14200:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14201:             } else {
                   14202:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14203:                &mt('Add to classlist').': <b>ok</b>';
                   14204:             }
                   14205:             $output .= $linefeed;
1.443     albertel 14206:         }
                   14207:     } else {
                   14208:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14209:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14210:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14211:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14212:         if ($context eq 'auto') {
                   14213:             $output .= $result.$linefeed;
                   14214:         } else {
                   14215:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14216:         }
1.443     albertel 14217:     }
                   14218:     return $output;
                   14219: }
                   14220: 
                   14221: sub commit_studentrole {
1.1116    raeburn  14222:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14223:         $credits) = @_;
1.626     raeburn  14224:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14225:     if ($context eq 'auto') {
                   14226:         $linefeed = "\n";
                   14227:     } else {
                   14228:         $linefeed = '<br />'."\n";
                   14229:     }
1.443     albertel 14230:     if (defined($one) && defined($two)) {
                   14231:         my $cid=$one.'_'.$two;
                   14232:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14233:         my $secchange = 0;
                   14234:         my $expire_role_result;
                   14235:         my $modify_section_result;
1.628     raeburn  14236:         if ($oldsec ne '-1') { 
                   14237:             if ($oldsec ne $sec) {
1.443     albertel 14238:                 $secchange = 1;
1.628     raeburn  14239:                 my $now = time;
1.443     albertel 14240:                 my $uurl='/'.$cid;
                   14241:                 $uurl=~s/\_/\//g;
                   14242:                 if ($oldsec) {
                   14243:                     $uurl.='/'.$oldsec;
                   14244:                 }
1.626     raeburn  14245:                 $oldsecurl = $uurl;
1.628     raeburn  14246:                 $expire_role_result = 
1.652     raeburn  14247:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14248:                 if ($env{'request.course.sec'} ne '') { 
                   14249:                     if ($expire_role_result eq 'refused') {
                   14250:                         my @roles = ('st');
                   14251:                         my @statuses = ('previous');
                   14252:                         my @roledoms = ($one);
                   14253:                         my $withsec = 1;
                   14254:                         my %roleshash = 
                   14255:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14256:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14257:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14258:                             my ($oldstart,$oldend) = 
                   14259:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14260:                             if ($oldend > 0 && $oldend <= $now) {
                   14261:                                 $expire_role_result = 'ok';
                   14262:                             }
                   14263:                         }
                   14264:                     }
                   14265:                 }
1.443     albertel 14266:                 $result = $expire_role_result;
                   14267:             }
                   14268:         }
                   14269:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1116    raeburn  14270:             $modify_section_result = 
                   14271:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14272:                                                            undef,undef,undef,$sec,
                   14273:                                                            $end,$start,'','',$cid,
                   14274:                                                            '',$context,$credits);
1.443     albertel 14275:             if ($modify_section_result =~ /^ok/) {
                   14276:                 if ($secchange == 1) {
1.628     raeburn  14277:                     if ($sec eq '') {
                   14278:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14279:                     } else {
                   14280:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14281:                     }
1.443     albertel 14282:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14283:                     if ($sec eq '') {
                   14284:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14285:                     } else {
                   14286:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14287:                     }
1.443     albertel 14288:                 } else {
1.628     raeburn  14289:                     if ($sec eq '') {
                   14290:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14291:                     } else {
                   14292:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14293:                     }
1.443     albertel 14294:                 }
                   14295:             } else {
1.1115    raeburn  14296:                 if ($secchange) { 
1.628     raeburn  14297:                     $$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;
                   14298:                 } else {
                   14299:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14300:                 }
1.443     albertel 14301:             }
                   14302:             $result = $modify_section_result;
                   14303:         } elsif ($secchange == 1) {
1.628     raeburn  14304:             if ($oldsec eq '') {
1.1103    raeburn  14305:                 $$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  14306:             } else {
                   14307:                 $$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;
                   14308:             }
1.626     raeburn  14309:             if ($expire_role_result eq 'refused') {
                   14310:                 my $newsecurl = '/'.$cid;
                   14311:                 $newsecurl =~ s/\_/\//g;
                   14312:                 if ($sec ne '') {
                   14313:                     $newsecurl.='/'.$sec;
                   14314:                 }
                   14315:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14316:                     if ($sec eq '') {
                   14317:                         $$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;
                   14318:                     } else {
                   14319:                         $$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;
                   14320:                     }
                   14321:                 }
                   14322:             }
1.443     albertel 14323:         }
                   14324:     } else {
1.626     raeburn  14325:         $$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 14326:         $result = "error: incomplete course id\n";
                   14327:     }
                   14328:     return $result;
                   14329: }
                   14330: 
1.1108    raeburn  14331: sub show_role_extent {
                   14332:     my ($scope,$context,$role) = @_;
                   14333:     $scope =~ s{^/}{};
                   14334:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14335:     push(@courseroles,'co');
                   14336:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14337:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14338:         $scope =~ s{/}{_};
                   14339:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14340:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14341:         my ($audom,$auname) = split(/\//,$scope);
                   14342:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14343:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14344:     } else {
                   14345:         $scope =~ s{/$}{};
                   14346:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14347:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14348:     }
                   14349: }
                   14350: 
1.443     albertel 14351: ############################################################
                   14352: ############################################################
                   14353: 
1.566     albertel 14354: sub check_clone {
1.578     raeburn  14355:     my ($args,$linefeed) = @_;
1.566     albertel 14356:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14357:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14358:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14359:     my $clonemsg;
                   14360:     my $can_clone = 0;
1.944     raeburn  14361:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14362:     if ($lctype ne 'community') {
                   14363:         $lctype = 'course';
                   14364:     }
1.566     albertel 14365:     if ($clonehome eq 'no_host') {
1.944     raeburn  14366:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14367:             $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'});
                   14368:         } else {
                   14369:             $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'});
                   14370:         }     
1.566     albertel 14371:     } else {
                   14372: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14373:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14374:             if ($clonedesc{'type'} ne 'Community') {
                   14375:                  $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'});
                   14376:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14377:             }
                   14378:         }
1.882     raeburn  14379: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14380:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14381: 	    $can_clone = 1;
                   14382: 	} else {
                   14383: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners'],
                   14384: 						 $args->{'clonedomain'},$args->{'clonecourse'});
                   14385: 	    my @cloners = split(/,/,$clonehash{'cloners'});
1.578     raeburn  14386:             if (grep(/^\*$/,@cloners)) {
                   14387:                 $can_clone = 1;
                   14388:             } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14389:                 $can_clone = 1;
                   14390:             } else {
1.908     raeburn  14391:                 my $ccrole = 'cc';
1.944     raeburn  14392:                 if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14393:                     $ccrole = 'co';
                   14394:                 }
1.578     raeburn  14395: 	        my %roleshash =
                   14396: 		    &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14397: 					 $args->{'ccdomain'},
1.908     raeburn  14398:                                          'userroles',['active'],[$ccrole],
1.578     raeburn  14399: 					 [$args->{'clonedomain'}]);
1.908     raeburn  14400: 	        if (($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) || (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners))) {
1.942     raeburn  14401:                     $can_clone = 1;
                   14402:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},$args->{'ccuname'},$args->{'ccdomain'})) {
                   14403:                     $can_clone = 1;
                   14404:                 } else {
1.944     raeburn  14405:                     if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14406:                         $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'});
                   14407:                     } else {
                   14408:                         $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'});
                   14409:                     }
1.578     raeburn  14410: 	        }
1.566     albertel 14411: 	    }
1.578     raeburn  14412:         }
1.566     albertel 14413:     }
                   14414:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14415: }
                   14416: 
1.444     albertel 14417: sub construct_course {
1.1166    raeburn  14418:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14419:     my $outcome;
1.541     raeburn  14420:     my $linefeed =  '<br />'."\n";
                   14421:     if ($context eq 'auto') {
                   14422:         $linefeed = "\n";
                   14423:     }
1.566     albertel 14424: 
                   14425: #
                   14426: # Are we cloning?
                   14427: #
                   14428:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14429:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14430: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14431: 	if ($context ne 'auto') {
1.578     raeburn  14432:             if ($clonemsg ne '') {
                   14433: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14434:             }
1.566     albertel 14435: 	}
                   14436: 	$outcome .= $clonemsg.$linefeed;
                   14437: 
                   14438:         if (!$can_clone) {
                   14439: 	    return (0,$outcome);
                   14440: 	}
                   14441:     }
                   14442: 
1.444     albertel 14443: #
                   14444: # Open course
                   14445: #
                   14446:     my $crstype = lc($args->{'crstype'});
                   14447:     my %cenv=();
                   14448:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14449:                                              $args->{'cdescr'},
                   14450:                                              $args->{'curl'},
                   14451:                                              $args->{'course_home'},
                   14452:                                              $args->{'nonstandard'},
                   14453:                                              $args->{'crscode'},
                   14454:                                              $args->{'ccuname'}.':'.
                   14455:                                              $args->{'ccdomain'},
1.882     raeburn  14456:                                              $args->{'crstype'},
1.885     raeburn  14457:                                              $cnum,$context,$category);
1.444     albertel 14458: 
                   14459:     # Note: The testing routines depend on this being output; see 
                   14460:     # Utils::Course. This needs to at least be output as a comment
                   14461:     # if anyone ever decides to not show this, and Utils::Course::new
                   14462:     # will need to be suitably modified.
1.541     raeburn  14463:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14464:     if ($$courseid =~ /^error:/) {
                   14465:         return (0,$outcome);
                   14466:     }
                   14467: 
1.444     albertel 14468: #
                   14469: # Check if created correctly
                   14470: #
1.479     albertel 14471:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14472:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14473:     if ($crsuhome eq 'no_host') {
                   14474:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14475:         return (0,$outcome);
                   14476:     }
1.541     raeburn  14477:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14478: 
1.444     albertel 14479: #
1.566     albertel 14480: # Do the cloning
                   14481: #   
                   14482:     if ($can_clone && $cloneid) {
                   14483: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14484: 	if ($context ne 'auto') {
                   14485: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14486: 	}
                   14487: 	$outcome .= $clonemsg.$linefeed;
                   14488: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14489: # Copy all files
1.637     www      14490: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14491: # Restore URL
1.566     albertel 14492: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14493: # Restore title
1.566     albertel 14494: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14495: # Restore creation date, creator and creation context.
                   14496:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14497:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14498:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14499: # Mark as cloned
1.566     albertel 14500: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14501: # Need to clone grading mode
                   14502:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14503:         $cenv{'grading'}=$newenv{'grading'};
                   14504: # Do not clone these environment entries
                   14505:         &Apache::lonnet::del('environment',
                   14506:                   ['default_enrollment_start_date',
                   14507:                    'default_enrollment_end_date',
                   14508:                    'question.email',
                   14509:                    'policy.email',
                   14510:                    'comment.email',
                   14511:                    'pch.users.denied',
1.725     raeburn  14512:                    'plc.users.denied',
                   14513:                    'hidefromcat',
1.1121    raeburn  14514:                    'checkforpriv',
1.1166    raeburn  14515:                    'categories',
                   14516:                    'internal.uniquecode'],
1.638     www      14517:                    $$crsudom,$$crsunum);
1.1170    raeburn  14518:         if ($args->{'textbook'}) {
                   14519:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14520:         }
1.444     albertel 14521:     }
1.566     albertel 14522: 
1.444     albertel 14523: #
                   14524: # Set environment (will override cloned, if existing)
                   14525: #
                   14526:     my @sections = ();
                   14527:     my @xlists = ();
                   14528:     if ($args->{'crstype'}) {
                   14529:         $cenv{'type'}=$args->{'crstype'};
                   14530:     }
                   14531:     if ($args->{'crsid'}) {
                   14532:         $cenv{'courseid'}=$args->{'crsid'};
                   14533:     }
                   14534:     if ($args->{'crscode'}) {
                   14535:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14536:     }
                   14537:     if ($args->{'crsquota'} ne '') {
                   14538:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14539:     } else {
                   14540:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14541:     }
                   14542:     if ($args->{'ccuname'}) {
                   14543:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14544:                                         ':'.$args->{'ccdomain'};
                   14545:     } else {
                   14546:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14547:     }
1.1116    raeburn  14548:     if ($args->{'defaultcredits'}) {
                   14549:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14550:     }
1.444     albertel 14551:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14552:     if ($args->{'crssections'}) {
                   14553:         $cenv{'internal.sectionnums'} = '';
                   14554:         if ($args->{'crssections'} =~ m/,/) {
                   14555:             @sections = split/,/,$args->{'crssections'};
                   14556:         } else {
                   14557:             $sections[0] = $args->{'crssections'};
                   14558:         }
                   14559:         if (@sections > 0) {
                   14560:             foreach my $item (@sections) {
                   14561:                 my ($sec,$gp) = split/:/,$item;
                   14562:                 my $class = $args->{'crscode'}.$sec;
                   14563:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14564:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14565:                 unless ($addcheck eq 'ok') {
                   14566:                     push @badclasses, $class;
                   14567:                 }
                   14568:             }
                   14569:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14570:         }
                   14571:     }
                   14572: # do not hide course coordinator from staff listing, 
                   14573: # even if privileged
                   14574:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1121    raeburn  14575: # add course coordinator's domain to domains to check for privileged users
                   14576: # if different to course domain
                   14577:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14578:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14579:     }
1.444     albertel 14580: # add crosslistings
                   14581:     if ($args->{'crsxlist'}) {
                   14582:         $cenv{'internal.crosslistings'}='';
                   14583:         if ($args->{'crsxlist'} =~ m/,/) {
                   14584:             @xlists = split/,/,$args->{'crsxlist'};
                   14585:         } else {
                   14586:             $xlists[0] = $args->{'crsxlist'};
                   14587:         }
                   14588:         if (@xlists > 0) {
                   14589:             foreach my $item (@xlists) {
                   14590:                 my ($xl,$gp) = split/:/,$item;
                   14591:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14592:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14593:                 unless ($addcheck eq 'ok') {
                   14594:                     push @badclasses, $xl;
                   14595:                 }
                   14596:             }
                   14597:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14598:         }
                   14599:     }
                   14600:     if ($args->{'autoadds'}) {
                   14601:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14602:     }
                   14603:     if ($args->{'autodrops'}) {
                   14604:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14605:     }
                   14606: # check for notification of enrollment changes
                   14607:     my @notified = ();
                   14608:     if ($args->{'notify_owner'}) {
                   14609:         if ($args->{'ccuname'} ne '') {
                   14610:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14611:         }
                   14612:     }
                   14613:     if ($args->{'notify_dc'}) {
                   14614:         if ($uname ne '') { 
1.630     raeburn  14615:             push(@notified,$uname.':'.$udom);
1.444     albertel 14616:         }
                   14617:     }
                   14618:     if (@notified > 0) {
                   14619:         my $notifylist;
                   14620:         if (@notified > 1) {
                   14621:             $notifylist = join(',',@notified);
                   14622:         } else {
                   14623:             $notifylist = $notified[0];
                   14624:         }
                   14625:         $cenv{'internal.notifylist'} = $notifylist;
                   14626:     }
                   14627:     if (@badclasses > 0) {
                   14628:         my %lt=&Apache::lonlocal::texthash(
                   14629:                 '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',
                   14630:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14631:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14632:         );
1.541     raeburn  14633:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14634:                            ' ('.$lt{'adby'}.')';
                   14635:         if ($context eq 'auto') {
                   14636:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14637:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14638:             foreach my $item (@badclasses) {
                   14639:                 if ($context eq 'auto') {
                   14640:                     $outcome .= " - $item\n";
                   14641:                 } else {
                   14642:                     $outcome .= "<li>$item</li>\n";
                   14643:                 }
                   14644:             }
                   14645:             if ($context eq 'auto') {
                   14646:                 $outcome .= $linefeed;
                   14647:             } else {
1.566     albertel 14648:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14649:             }
                   14650:         } 
1.444     albertel 14651:     }
                   14652:     if ($args->{'no_end_date'}) {
                   14653:         $args->{'endaccess'} = 0;
                   14654:     }
                   14655:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14656:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14657:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14658:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14659:     if ($args->{'showphotos'}) {
                   14660:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14661:     }
                   14662:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14663:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14664:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14665:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14666:             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'); 
                   14667:             if ($context eq 'auto') {
                   14668:                 $outcome .= $krb_msg;
                   14669:             } else {
1.566     albertel 14670:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14671:             }
                   14672:             $outcome .= $linefeed;
1.444     albertel 14673:         }
                   14674:     }
                   14675:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14676:        if ($args->{'setpolicy'}) {
                   14677:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14678:        }
                   14679:        if ($args->{'setcontent'}) {
                   14680:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14681:        }
                   14682:     }
                   14683:     if ($args->{'reshome'}) {
                   14684: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14685: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14686:     }
                   14687: #
                   14688: # course has keyed access
                   14689: #
                   14690:     if ($args->{'setkeys'}) {
                   14691:        $cenv{'keyaccess'}='yes';
                   14692:     }
                   14693: # if specified, key authority is not course, but user
                   14694: # only active if keyaccess is yes
                   14695:     if ($args->{'keyauth'}) {
1.487     albertel 14696: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14697: 	$user = &LONCAPA::clean_username($user);
                   14698: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14699: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14700: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14701: 	}
                   14702:     }
                   14703: 
1.1166    raeburn  14704: #
1.1167    raeburn  14705: #  generate and store uniquecode (available to course requester), if course should have one.
1.1166    raeburn  14706: #
                   14707:     if ($args->{'uniquecode'}) {
                   14708:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14709:         if ($code) {
                   14710:             $cenv{'internal.uniquecode'} = $code;
1.1167    raeburn  14711:             my %crsinfo =
                   14712:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14713:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14714:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14715:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14716:             } 
1.1166    raeburn  14717:             if (ref($coderef)) {
                   14718:                 $$coderef = $code;
                   14719:             }
                   14720:         }
                   14721:     }
                   14722: 
1.444     albertel 14723:     if ($args->{'disresdis'}) {
                   14724:         $cenv{'pch.roles.denied'}='st';
                   14725:     }
                   14726:     if ($args->{'disablechat'}) {
                   14727:         $cenv{'plc.roles.denied'}='st';
                   14728:     }
                   14729: 
                   14730:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14731:     # course
                   14732:     $cenv{'course.helper.not.run'} = 1;
                   14733:     #
                   14734:     # Use new Randomseed
                   14735:     #
                   14736:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14737:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14738:     #
                   14739:     # The encryption code and receipt prefix for this course
                   14740:     #
                   14741:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14742:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14743:     #
                   14744:     # By default, use standard grading
                   14745:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14746: 
1.541     raeburn  14747:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14748:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14749: #
                   14750: # Open all assignments
                   14751: #
                   14752:     if ($args->{'openall'}) {
                   14753:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14754:        my %storecontent = ($storeunder         => time,
                   14755:                            $storeunder.'.type' => 'date_start');
                   14756:        
                   14757:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14758:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14759:    }
                   14760: #
                   14761: # Set first page
                   14762: #
                   14763:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14764: 	    || ($cloneid)) {
1.445     albertel 14765: 	use LONCAPA::map;
1.444     albertel 14766: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14767: 
                   14768: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14769:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14770: 
1.444     albertel 14771:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14772:         my $title; my $url;
                   14773:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14774: 	    $title=&mt('Syllabus');
1.444     albertel 14775:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14776:         } else {
1.963     raeburn  14777:             $title=&mt('Table of Contents');
1.444     albertel 14778:             $url='/adm/navmaps';
                   14779:         }
1.445     albertel 14780: 
                   14781:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14782: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14783: 
                   14784: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14785:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14786:     }
1.566     albertel 14787: 
                   14788:     return (1,$outcome);
1.444     albertel 14789: }
                   14790: 
1.1166    raeburn  14791: sub make_unique_code {
                   14792:     my ($cdom,$cnum) = @_;
                   14793:     # get lock on uniquecodes db
                   14794:     my $lockhash = {
                   14795:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14796:                                                   ':'.$env{'user.domain'},
                   14797:                    };
                   14798:     my $tries = 0;
                   14799:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14800:     my ($code,$error);
                   14801:   
                   14802:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14803:         $tries ++;
                   14804:         sleep 1;
                   14805:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14806:     }
                   14807:     if ($gotlock eq 'ok') {
                   14808:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14809:         my $gotcode;
                   14810:         my $attempts = 0;
                   14811:         while ((!$gotcode) && ($attempts < 100)) {
                   14812:             $code = &generate_code();
                   14813:             if (!exists($currcodes{$code})) {
                   14814:                 $gotcode = 1;
                   14815:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14816:                     $error = 'nostore';
                   14817:                 }
                   14818:             }
                   14819:             $attempts ++;
                   14820:         }
                   14821:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14822:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14823:     } else {
                   14824:         $error = 'nolock';
                   14825:     }
                   14826:     return ($code,$error);
                   14827: }
                   14828: 
                   14829: sub generate_code {
                   14830:     my $code;
                   14831:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14832:     for (my $i=0; $i<6; $i++) {
                   14833:         my $lettnum = int (rand 2);
                   14834:         my $item = '';
                   14835:         if ($lettnum) {
                   14836:             $item = $letts[int( rand(18) )];
                   14837:         } else {
                   14838:             $item = 1+int( rand(8) );
                   14839:         }
                   14840:         $code .= $item;
                   14841:     }
                   14842:     return $code;
                   14843: }
                   14844: 
1.444     albertel 14845: ############################################################
                   14846: ############################################################
                   14847: 
1.953     droeschl 14848: #SD
                   14849: # only Community and Course, or anything else?
1.378     raeburn  14850: sub course_type {
                   14851:     my ($cid) = @_;
                   14852:     if (!defined($cid)) {
                   14853:         $cid = $env{'request.course.id'};
                   14854:     }
1.404     albertel 14855:     if (defined($env{'course.'.$cid.'.type'})) {
                   14856:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14857:     } else {
                   14858:         return 'Course';
1.377     raeburn  14859:     }
                   14860: }
1.156     albertel 14861: 
1.406     raeburn  14862: sub group_term {
                   14863:     my $crstype = &course_type();
                   14864:     my %names = (
                   14865:                   'Course' => 'group',
1.865     raeburn  14866:                   'Community' => 'group',
1.406     raeburn  14867:                 );
                   14868:     return $names{$crstype};
                   14869: }
                   14870: 
1.902     raeburn  14871: sub course_types {
1.1165    raeburn  14872:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14873:     my %typename = (
                   14874:                          official   => 'Official course',
                   14875:                          unofficial => 'Unofficial course',
                   14876:                          community  => 'Community',
1.1165    raeburn  14877:                          textbook   => 'Textbook course',
1.902     raeburn  14878:                    );
                   14879:     return (\@types,\%typename);
                   14880: }
                   14881: 
1.156     albertel 14882: sub icon {
                   14883:     my ($file)=@_;
1.505     albertel 14884:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14885:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14886:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14887:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14888: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14889: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14890: 	            $curfext.".gif") {
                   14891: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14892: 		$curfext.".gif";
                   14893: 	}
                   14894:     }
1.249     albertel 14895:     return &lonhttpdurl($iconname);
1.154     albertel 14896: } 
1.84      albertel 14897: 
1.575     albertel 14898: sub lonhttpdurl {
1.692     www      14899: #
                   14900: # Had been used for "small fry" static images on separate port 8080.
                   14901: # Modify here if lightweight http functionality desired again.
                   14902: # Currently eliminated due to increasing firewall issues.
                   14903: #
1.575     albertel 14904:     my ($url)=@_;
1.692     www      14905:     return $url;
1.215     albertel 14906: }
                   14907: 
1.213     albertel 14908: sub connection_aborted {
                   14909:     my ($r)=@_;
                   14910:     $r->print(" ");$r->rflush();
                   14911:     my $c = $r->connection;
                   14912:     return $c->aborted();
                   14913: }
                   14914: 
1.221     foxr     14915: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14916: #    strings as 'strings'.
                   14917: sub escape_single {
1.221     foxr     14918:     my ($input) = @_;
1.223     albertel 14919:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14920:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14921:     return $input;
                   14922: }
1.223     albertel 14923: 
1.222     foxr     14924: #  Same as escape_single, but escape's "'s  This 
                   14925: #  can be used for  "strings"
                   14926: sub escape_double {
                   14927:     my ($input) = @_;
                   14928:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14929:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14930:     return $input;
                   14931: }
1.223     albertel 14932:  
1.222     foxr     14933: #   Escapes the last element of a full URL.
                   14934: sub escape_url {
                   14935:     my ($url)   = @_;
1.238     raeburn  14936:     my @urlslices = split(/\//, $url,-1);
1.369     www      14937:     my $lastitem = &escape(pop(@urlslices));
1.1203    raeburn  14938:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14939: }
1.462     albertel 14940: 
1.820     raeburn  14941: sub compare_arrays {
                   14942:     my ($arrayref1,$arrayref2) = @_;
                   14943:     my (@difference,%count);
                   14944:     @difference = ();
                   14945:     %count = ();
                   14946:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14947:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14948:         foreach my $element (keys(%count)) {
                   14949:             if ($count{$element} == 1) {
                   14950:                 push(@difference,$element);
                   14951:             }
                   14952:         }
                   14953:     }
                   14954:     return @difference;
                   14955: }
                   14956: 
1.817     bisitz   14957: # -------------------------------------------------------- Initialize user login
1.462     albertel 14958: sub init_user_environment {
1.463     albertel 14959:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14960:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14961: 
                   14962:     my $public=($username eq 'public' && $domain eq 'public');
                   14963: 
                   14964: # See if old ID present, if so, remove
                   14965: 
1.1062    raeburn  14966:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14967:     my $now=time;
                   14968: 
                   14969:     if ($public) {
                   14970: 	my $max_public=100;
                   14971: 	my $oldest;
                   14972: 	my $oldest_time=0;
                   14973: 	for(my $next=1;$next<=$max_public;$next++) {
                   14974: 	    if (-e $lonids."/publicuser_$next.id") {
                   14975: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14976: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14977: 		    $oldest_time=$mtime;
                   14978: 		    $oldest=$next;
                   14979: 		}
                   14980: 	    } else {
                   14981: 		$cookie="publicuser_$next";
                   14982: 		last;
                   14983: 	    }
                   14984: 	}
                   14985: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14986:     } else {
1.463     albertel 14987: 	# if this isn't a robot, kill any existing non-robot sessions
                   14988: 	if (!$args->{'robot'}) {
                   14989: 	    opendir(DIR,$lonids);
                   14990: 	    while ($filename=readdir(DIR)) {
                   14991: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14992: 		    unlink($lonids.'/'.$filename);
                   14993: 		}
1.462     albertel 14994: 	    }
1.463     albertel 14995: 	    closedir(DIR);
1.1204    raeburn  14996: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   14997:             my $namespace = 'nohist_courseeditor';
                   14998:             my $lockingkey = 'paste'."\0".'locked_num';
                   14999:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15000:                                                 $domain,$username);
                   15001:             if (exists($lockhash{$lockingkey})) {
                   15002:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15003:                 unless ($delresult eq 'ok') {
                   15004:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15005:                 }
                   15006:             }
1.462     albertel 15007: 	}
                   15008: # Give them a new cookie
1.463     albertel 15009: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15010: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15011: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15012:     
                   15013: # Initialize roles
                   15014: 
1.1062    raeburn  15015: 	($userroles,$firstaccenv,$timerintenv) = 
                   15016:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15017:     }
                   15018: # ------------------------------------ Check browser type and MathML capability
                   15019: 
1.1194    raeburn  15020:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15021:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15022: 
                   15023: # ------------------------------------------------------------- Get environment
                   15024: 
                   15025:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15026:     my ($tmp) = keys(%userenv);
                   15027:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15028:     } else {
                   15029: 	undef(%userenv);
                   15030:     }
                   15031:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15032: 	$form->{'interface'}=$userenv{'interface'};
                   15033:     }
                   15034:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15035: 
                   15036: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15037:     foreach my $option ('interface','localpath','localres') {
                   15038:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15039:     }
                   15040: # --------------------------------------------------------- Write first profile
                   15041: 
                   15042:     {
                   15043: 	my %initial_env = 
                   15044: 	    ("user.name"          => $username,
                   15045: 	     "user.domain"        => $domain,
                   15046: 	     "user.home"          => $authhost,
                   15047: 	     "browser.type"       => $clientbrowser,
                   15048: 	     "browser.version"    => $clientversion,
                   15049: 	     "browser.mathml"     => $clientmathml,
                   15050: 	     "browser.unicode"    => $clientunicode,
                   15051: 	     "browser.os"         => $clientos,
1.1137    raeburn  15052:              "browser.mobile"     => $clientmobile,
1.1141    raeburn  15053:              "browser.info"       => $clientinfo,
1.1194    raeburn  15054:              "browser.osversion"  => $clientosversion,
1.462     albertel 15055: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15056: 	     "request.course.fn"  => '',
                   15057: 	     "request.course.uri" => '',
                   15058: 	     "request.course.sec" => '',
                   15059: 	     "request.role"       => 'cm',
                   15060: 	     "request.role.adv"   => $env{'user.adv'},
                   15061: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15062: 
                   15063:         if ($form->{'localpath'}) {
                   15064: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15065: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15066:         }
                   15067: 	
                   15068: 	if ($form->{'interface'}) {
                   15069: 	    $form->{'interface'}=~s/\W//gs;
                   15070: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15071: 	    $env{'browser.interface'}=$form->{'interface'};
                   15072: 	}
                   15073: 
1.1157    raeburn  15074:         if ($form->{'iptoken'}) {
                   15075:             my $lonhost = $r->dir_config('lonHostID');
                   15076:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15077:             $env{'user.noloadbalance'} = $lonhost;
                   15078:         }
                   15079: 
1.981     raeburn  15080:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  15081:         my %domdef;
                   15082:         unless ($domain eq 'public') {
                   15083:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   15084:         }
1.980     raeburn  15085: 
1.1081    raeburn  15086:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  15087:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  15088:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15089:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  15090:         }
                   15091: 
1.1165    raeburn  15092:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  15093:             $userenv{'canrequest.'.$crstype} =
                   15094:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  15095:                                                   'reload','requestcourses',
                   15096:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  15097:         }
                   15098: 
1.1092    raeburn  15099:         $userenv{'canrequest.author'} =
                   15100:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15101:                                         'reload','requestauthor',
                   15102:                                         \%userenv,\%domdef,\%is_adv);
                   15103:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15104:                                              $domain,$username);
                   15105:         my $reqstatus = $reqauthor{'author_status'};
                   15106:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') { 
                   15107:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   15108:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15109:                                                   $reqauthor{'author'}{'timestamp'};
                   15110:             }
                   15111:         }
                   15112: 
1.462     albertel 15113: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15114: 
1.462     albertel 15115: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15116: 		 &GDBM_WRCREAT(),0640)) {
                   15117: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15118: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15119: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15120:             if (ref($firstaccenv) eq 'HASH') {
                   15121:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15122:             }
                   15123:             if (ref($timerintenv) eq 'HASH') {
                   15124:                 &_add_to_env(\%disk_env,$timerintenv);
                   15125:             }
1.463     albertel 15126: 	    if (ref($args->{'extra_env'})) {
                   15127: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15128: 	    }
1.462     albertel 15129: 	    untie(%disk_env);
                   15130: 	} else {
1.705     tempelho 15131: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15132: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15133: 	    return 'error: '.$!;
                   15134: 	}
                   15135:     }
                   15136:     $env{'request.role'}='cm';
                   15137:     $env{'request.role.adv'}=$env{'user.adv'};
                   15138:     $env{'browser.type'}=$clientbrowser;
                   15139: 
                   15140:     return $cookie;
                   15141: 
                   15142: }
                   15143: 
                   15144: sub _add_to_env {
                   15145:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15146:     if (ref($env_data) eq 'HASH') {
                   15147:         while (my ($key,$value) = each(%$env_data)) {
                   15148: 	    $idf->{$prefix.$key} = $value;
                   15149: 	    $env{$prefix.$key}   = $value;
                   15150:         }
1.462     albertel 15151:     }
                   15152: }
                   15153: 
1.685     tempelho 15154: # --- Get the symbolic name of a problem and the url
                   15155: sub get_symb {
                   15156:     my ($request,$silent) = @_;
1.726     raeburn  15157:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15158:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15159:     if ($symb eq '') {
                   15160:         if (!$silent) {
1.1071    raeburn  15161:             if (ref($request)) { 
                   15162:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15163:             }
1.685     tempelho 15164:             return ();
                   15165:         }
                   15166:     }
                   15167:     &Apache::lonenc::check_decrypt(\$symb);
                   15168:     return ($symb);
                   15169: }
                   15170: 
                   15171: # --------------------------------------------------------------Get annotation
                   15172: 
                   15173: sub get_annotation {
                   15174:     my ($symb,$enc) = @_;
                   15175: 
                   15176:     my $key = $symb;
                   15177:     if (!$enc) {
                   15178:         $key =
                   15179:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15180:     }
                   15181:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15182:     return $annotation{$key};
                   15183: }
                   15184: 
                   15185: sub clean_symb {
1.731     raeburn  15186:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15187: 
                   15188:     &Apache::lonenc::check_decrypt(\$symb);
                   15189:     my $enc = $env{'request.enc'};
1.731     raeburn  15190:     if ($delete_enc) {
1.730     raeburn  15191:         delete($env{'request.enc'});
                   15192:     }
1.685     tempelho 15193: 
                   15194:     return ($symb,$enc);
                   15195: }
1.462     albertel 15196: 
1.1181    raeburn  15197: ############################################################
                   15198: ############################################################
                   15199: 
                   15200: =pod
                   15201: 
                   15202: =head1 Routines for building display used to search for courses
                   15203: 
                   15204: 
                   15205: =over 4
                   15206: 
                   15207: =item * &build_filters()
                   15208: 
                   15209: Create markup for a table used to set filters to use when selecting
1.1182    raeburn  15210: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15211: and quotacheck.pl
                   15212: 
1.1181    raeburn  15213: 
                   15214: Inputs:
                   15215: 
                   15216: filterlist - anonymous array of fields to include as potential filters 
                   15217: 
                   15218: crstype - course type
                   15219: 
                   15220: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15221:               to pop-open a course selector (will contain "extra element"). 
                   15222: 
                   15223: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15224: 
                   15225: filter - anonymous hash of criteria and their values
                   15226: 
                   15227: action - form action
                   15228: 
                   15229: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15230: 
1.1182    raeburn  15231: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
1.1181    raeburn  15232: 
                   15233: cloneruname - username of owner of new course who wants to clone
                   15234: 
                   15235: clonerudom - domain of owner of new course who wants to clone
                   15236: 
                   15237: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community) 
                   15238: 
                   15239: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15240: 
                   15241: codedom - domain
                   15242: 
                   15243: formname - value of form element named "form". 
                   15244: 
                   15245: fixeddom - domain, if fixed.
                   15246: 
                   15247: prevphase - value to assign to form element named "phase" when going back to the previous screen  
                   15248: 
                   15249: cnameelement - name of form element in form on opener page which will receive title of selected course 
                   15250: 
                   15251: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15252: 
                   15253: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15254: 
                   15255: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15256: 
                   15257: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15258: 
                   15259: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15260: 
1.1182    raeburn  15261: 
1.1181    raeburn  15262: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15263: 
1.1182    raeburn  15264: 
1.1181    raeburn  15265: Side Effects: None
                   15266: 
                   15267: =cut
                   15268: 
                   15269: # ---------------------------------------------- search for courses based on last activity etc.
                   15270: 
                   15271: sub build_filters {
                   15272:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15273:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15274:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15275:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15276:         $clonetext,$clonewarning) = @_;
1.1182    raeburn  15277:     my ($list,$jscript);
1.1181    raeburn  15278:     my $onchange = 'javascript:updateFilters(this)';
                   15279:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15280:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15281:         $typeselectform,$instcodetitle);
                   15282:     if ($formname eq '') {
                   15283:         $formname = $caller;
                   15284:     }
                   15285:     foreach my $item (@{$filterlist}) {
                   15286:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15287:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15288:             if ($item eq 'domainfilter') {
                   15289:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15290:             } elsif ($item eq 'coursefilter') {
                   15291:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15292:             } elsif ($item eq 'ownerfilter') {
                   15293:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15294:             } elsif ($item eq 'ownerdomfilter') {
                   15295:                 $filter->{'ownerdomfilter'} =
                   15296:                     &LONCAPA::clean_domain($filter->{$item});
                   15297:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15298:                                                        'ownerdomfilter',1);
                   15299:             } elsif ($item eq 'personfilter') {
                   15300:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15301:             } elsif ($item eq 'persondomfilter') {
                   15302:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15303:                                                         'persondomfilter',1);
                   15304:             } else {
                   15305:                 $filter->{$item} =~ s/\W//g;
                   15306:             }
                   15307:             if (!$filter->{$item}) {
                   15308:                 $filter->{$item} = '';
                   15309:             }
                   15310:         }
                   15311:         if ($item eq 'domainfilter') {
                   15312:             my $allow_blank = 1;
                   15313:             if ($formname eq 'portform') {
                   15314:                 $allow_blank=0;
                   15315:             } elsif ($formname eq 'studentform') {
                   15316:                 $allow_blank=0;
                   15317:             }
                   15318:             if ($fixeddom) {
                   15319:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15320:                                     ' value="'.$codedom.'" />'.
                   15321:                                     &Apache::lonnet::domain($codedom,'description');
                   15322:             } else {
                   15323:                 $domainselectform = &select_dom_form($filter->{$item},
                   15324:                                                      'domainfilter',
                   15325:                                                       $allow_blank,'',$onchange);
                   15326:             }
                   15327:         } else {
                   15328:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15329:         }
                   15330:     }
                   15331: 
                   15332:     # last course activity filter and selection
                   15333:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15334: 
                   15335:     # course created filter and selection
                   15336:     if (exists($filter->{'createdfilter'})) {
                   15337:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15338:     }
                   15339: 
                   15340:     my %lt = &Apache::lonlocal::texthash(
                   15341:                 'cac' => "$crstype Activity",
                   15342:                 'ccr' => "$crstype Created",
                   15343:                 'cde' => "$crstype Title",
                   15344:                 'cdo' => "$crstype Domain",
                   15345:                 'ins' => 'Institutional Code',
                   15346:                 'inc' => 'Institutional Categorization',
                   15347:                 'cow' => "$crstype Owner/Co-owner",
                   15348:                 'cop' => "$crstype Personnel Includes",
                   15349:                 'cog' => 'Type',
                   15350:              );
                   15351: 
                   15352:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15353:         my $typeval = 'Course';
                   15354:         if ($crstype eq 'Community') {
                   15355:             $typeval = 'Community';
                   15356:         }
                   15357:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15358:     } else {
                   15359:         $typeselectform =  '<select name="type" size="1"';
                   15360:         if ($onchange) {
                   15361:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15362:         }
                   15363:         $typeselectform .= '>'."\n";
                   15364:         foreach my $posstype ('Course','Community') {
                   15365:             $typeselectform.='<option value="'.$posstype.'"'.
                   15366:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15367:         }
                   15368:         $typeselectform.="</select>";
                   15369:     }
                   15370: 
                   15371:     my ($cloneableonlyform,$cloneabletitle);
                   15372:     if (exists($filter->{'cloneableonly'})) {
                   15373:         my $cloneableon = '';
                   15374:         my $cloneableoff = ' checked="checked"';
                   15375:         if ($filter->{'cloneableonly'}) {
                   15376:             $cloneableon = $cloneableoff;
                   15377:             $cloneableoff = '';
                   15378:         }
                   15379:         $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>';
                   15380:         if ($formname eq 'ccrs') {
1.1187    bisitz   15381:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1181    raeburn  15382:         } else {
                   15383:             $cloneabletitle = &mt('Cloneable by you');
                   15384:         }
                   15385:     }
                   15386:     my $officialjs;
                   15387:     if ($crstype eq 'Course') {
                   15388:         if (exists($filter->{'instcodefilter'})) {
1.1182    raeburn  15389: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15390: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15391:             if ($codedom) { 
1.1181    raeburn  15392:                 $officialjs = 1;
                   15393:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15394:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15395:                                                                   $officialjs,$codetitlesref);
                   15396:                 if ($jscript) {
1.1182    raeburn  15397:                     $jscript = '<script type="text/javascript">'."\n".
                   15398:                                '// <![CDATA['."\n".
                   15399:                                $jscript."\n".
                   15400:                                '// ]]>'."\n".
                   15401:                                '</script>'."\n";
1.1181    raeburn  15402:                 }
                   15403:             }
                   15404:             if ($instcodeform eq '') {
                   15405:                 $instcodeform =
                   15406:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15407:                     $list->{'instcodefilter'}.'" />';
                   15408:                 $instcodetitle = $lt{'ins'};
                   15409:             } else {
                   15410:                 $instcodetitle = $lt{'inc'};
                   15411:             }
                   15412:             if ($fixeddom) {
                   15413:                 $instcodetitle .= '<br />('.$codedom.')';
                   15414:             }
                   15415:         }
                   15416:     }
                   15417:     my $output = qq|
                   15418: <form method="post" name="filterpicker" action="$action">
                   15419: <input type="hidden" name="form" value="$formname" />
                   15420: |;
                   15421:     if ($formname eq 'modifycourse') {
                   15422:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15423:                    '<input type="hidden" name="prevphase" value="'.
                   15424:                    $prevphase.'" />'."\n";
1.1198    musolffc 15425:     } elsif ($formname eq 'quotacheck') {
                   15426:         $output .= qq|
                   15427: <input type="hidden" name="sortby" value="" />
                   15428: <input type="hidden" name="sortorder" value="" />
                   15429: |;
                   15430:     } else {
1.1181    raeburn  15431:         my $name_input;
                   15432:         if ($cnameelement ne '') {
                   15433:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15434:                           $cnameelement.'" />';
                   15435:         }
                   15436:         $output .= qq|
1.1182    raeburn  15437: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15438: <input type="hidden" name="cdomelement" value="$cdomelement" />
1.1181    raeburn  15439: $name_input
                   15440: $roleelement
                   15441: $multelement
                   15442: $typeelement
                   15443: |;
                   15444:         if ($formname eq 'portform') {
                   15445:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15446:         }
                   15447:     }
                   15448:     if ($fixeddom) {
                   15449:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15450:     }
                   15451:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15452:     if ($sincefilterform) {
                   15453:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15454:                   .$sincefilterform
                   15455:                   .&Apache::lonhtmlcommon::row_closure();
                   15456:     }
                   15457:     if ($createdfilterform) {
                   15458:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15459:                   .$createdfilterform
                   15460:                   .&Apache::lonhtmlcommon::row_closure();
                   15461:     }
                   15462:     if ($domainselectform) {
                   15463:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15464:                   .$domainselectform
                   15465:                   .&Apache::lonhtmlcommon::row_closure();
                   15466:     }
                   15467:     if ($typeselectform) {
                   15468:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15469:             $output .= $typeselectform;
                   15470:         } else {
                   15471:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15472:                       .$typeselectform
                   15473:                       .&Apache::lonhtmlcommon::row_closure();
                   15474:         }
                   15475:     }
                   15476:     if ($instcodeform) {
                   15477:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15478:                   .$instcodeform
                   15479:                   .&Apache::lonhtmlcommon::row_closure();
                   15480:     }
                   15481:     if (exists($filter->{'ownerfilter'})) {
                   15482:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15483:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15484:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15485:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15486:                    $ownerdomselectform.'</td></tr></table>'.
                   15487:                    &Apache::lonhtmlcommon::row_closure();
                   15488:     }
                   15489:     if (exists($filter->{'personfilter'})) {
                   15490:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15491:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15492:                    '<input type="text" name="personfilter" size="20" value="'.
                   15493:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15494:                    $persondomselectform.'</td></tr></table>'.
                   15495:                    &Apache::lonhtmlcommon::row_closure();
                   15496:     }
                   15497:     if (exists($filter->{'coursefilter'})) {
                   15498:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15499:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15500:                   .$list->{'coursefilter'}.'" />'
                   15501:                   .&Apache::lonhtmlcommon::row_closure();
                   15502:     }
                   15503:     if ($cloneableonlyform) {
                   15504:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15505:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15506:     }
                   15507:     if (exists($filter->{'descriptfilter'})) {
                   15508:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15509:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15510:                   .$list->{'descriptfilter'}.'" />'
                   15511:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15512:     }
                   15513:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15514:                '<input type="hidden" name="updater" value="" />'."\n".
                   15515:                '<input type="submit" name="gosearch" value="'.
                   15516:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15517:     return $jscript.$clonewarning.$output;
                   15518: }
                   15519: 
                   15520: =pod 
                   15521: 
                   15522: =item * &timebased_select_form()
                   15523: 
1.1182    raeburn  15524: Create markup for a dropdown list used to select a time-based
1.1181    raeburn  15525: filter e.g., Course Activity, Course Created, when searching for courses
                   15526: or communities
                   15527: 
                   15528: Inputs:
                   15529: 
                   15530: item - name of form element (sincefilter or createdfilter)
                   15531: 
                   15532: filter - anonymous hash of criteria and their values
                   15533: 
                   15534: Returns: HTML for a select box contained a blank, then six time selections,
                   15535:          with value set in incoming form variables currently selected. 
                   15536: 
                   15537: Side Effects: None
                   15538: 
                   15539: =cut
                   15540: 
                   15541: sub timebased_select_form {
                   15542:     my ($item,$filter) = @_;
                   15543:     if (ref($filter) eq 'HASH') {
                   15544:         $filter->{$item} =~ s/[^\d-]//g;
                   15545:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15546:         return &select_form(
                   15547:                             $filter->{$item},
                   15548:                             $item,
                   15549:                             {      '-1' => '',
                   15550:                                 '86400' => &mt('today'),
                   15551:                                '604800' => &mt('last week'),
                   15552:                               '2592000' => &mt('last month'),
                   15553:                               '7776000' => &mt('last three months'),
                   15554:                              '15552000' => &mt('last six months'),
                   15555:                              '31104000' => &mt('last year'),
                   15556:                     'select_form_order' =>
                   15557:                            ['-1','86400','604800','2592000','7776000',
                   15558:                             '15552000','31104000']});
                   15559:     }
                   15560: }
                   15561: 
                   15562: =pod
                   15563: 
                   15564: =item * &js_changer()
                   15565: 
                   15566: Create script tag containing Javascript used to submit course search form
1.1183    raeburn  15567: when course type or domain is changed, and also to hide 'Searching ...' on
                   15568: page load completion for page showing search result.
1.1181    raeburn  15569: 
                   15570: Inputs: None
                   15571: 
1.1183    raeburn  15572: Returns: markup containing updateFilters() and hideSearching() javascript functions. 
1.1181    raeburn  15573: 
                   15574: Side Effects: None
                   15575: 
                   15576: =cut
                   15577: 
                   15578: sub js_changer {
                   15579:     return <<ENDJS;
                   15580: <script type="text/javascript">
                   15581: // <![CDATA[
                   15582: function updateFilters(caller) {
                   15583:     if (typeof(caller) != "undefined") {
                   15584:         document.filterpicker.updater.value = caller.name;
                   15585:     }
                   15586:     document.filterpicker.submit();
                   15587: }
1.1183    raeburn  15588: 
                   15589: function hideSearching() {
                   15590:     if (document.getElementById('searching')) {
                   15591:         document.getElementById('searching').style.display = 'none';
                   15592:     }
                   15593:     return;
                   15594: }
                   15595: 
1.1181    raeburn  15596: // ]]>
                   15597: </script>
                   15598: 
                   15599: ENDJS
                   15600: }
                   15601: 
                   15602: =pod
                   15603: 
1.1182    raeburn  15604: =item * &search_courses()
                   15605: 
                   15606: Process selected filters form course search form and pass to lonnet::courseiddump
                   15607: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15608: 
                   15609: Inputs:
                   15610: 
                   15611: dom - domain being searched 
                   15612: 
                   15613: type - course type ('Course' or 'Community' or '.' if any).
                   15614: 
                   15615: filter - anonymous hash of criteria and their values
                   15616: 
                   15617: numtitles - for institutional codes - number of categories
                   15618: 
                   15619: cloneruname - optional username of new course owner
                   15620: 
                   15621: clonerudom - optional domain of new course owner
                   15622: 
                   15623: domcloner - Optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by, 
                   15624:             (used when DC is using course creation form)
                   15625: 
                   15626: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15627: 
                   15628: 
                   15629: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15630: 
                   15631: 
                   15632: Side Effects: None
                   15633: 
                   15634: =cut
                   15635: 
                   15636: 
                   15637: sub search_courses {
                   15638:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles) = @_;
                   15639:     my (%courses,%showcourses,$cloner);
                   15640:     if (($filter->{'ownerfilter'} ne '') ||
                   15641:         ($filter->{'ownerdomfilter'} ne '')) {
                   15642:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15643:                                        $filter->{'ownerdomfilter'};
                   15644:     }
                   15645:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15646:         if (!$filter->{$item}) {
                   15647:             $filter->{$item}='.';
                   15648:         }
                   15649:     }
                   15650:     my $now = time;
                   15651:     my $timefilter =
                   15652:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15653:     my ($createdbefore,$createdafter);
                   15654:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15655:         $createdbefore = $now;
                   15656:         $createdafter = $now-$filter->{'createdfilter'};
                   15657:     }
                   15658:     my ($instcodefilter,$regexpok);
                   15659:     if ($numtitles) {
                   15660:         if ($env{'form.official'} eq 'on') {
                   15661:             $instcodefilter =
                   15662:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15663:             $regexpok = 1;
                   15664:         } elsif ($env{'form.official'} eq 'off') {
                   15665:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15666:             unless ($instcodefilter eq '') {
                   15667:                 $regexpok = -1;
                   15668:             }
                   15669:         }
                   15670:     } else {
                   15671:         $instcodefilter = $filter->{'instcodefilter'};
                   15672:     }
                   15673:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15674:     if ($type eq '') { $type = '.'; }
                   15675: 
                   15676:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15677:         $cloner = $cloneruname.':'.$clonerudom;
                   15678:     }
                   15679:     %courses = &Apache::lonnet::courseiddump($dom,
                   15680:                                              $filter->{'descriptfilter'},
                   15681:                                              $timefilter,
                   15682:                                              $instcodefilter,
                   15683:                                              $filter->{'combownerfilter'},
                   15684:                                              $filter->{'coursefilter'},
                   15685:                                              undef,undef,$type,$regexpok,undef,undef,
                   15686:                                              undef,undef,$cloner,$env{'form.cc_clone'},
                   15687:                                              $filter->{'cloneableonly'},
                   15688:                                              $createdbefore,$createdafter,undef,
                   15689:                                              $domcloner);
                   15690:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15691:         my $ccrole;
                   15692:         if ($type eq 'Community') {
                   15693:             $ccrole = 'co';
                   15694:         } else {
                   15695:             $ccrole = 'cc';
                   15696:         }
                   15697:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15698:                                                      $filter->{'persondomfilter'},
                   15699:                                                      'userroles',undef,
                   15700:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15701:                                                      $dom);
                   15702:         foreach my $role (keys(%rolehash)) {
                   15703:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15704:             my $cid = $cdom.'_'.$cnum;
                   15705:             if (exists($courses{$cid})) {
                   15706:                 if (ref($courses{$cid}) eq 'HASH') {
                   15707:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15708:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15709:                             push (@{$courses{$cid}{roles}},$courserole);
                   15710:                         }
                   15711:                     } else {
                   15712:                         $courses{$cid}{roles} = [$courserole];
                   15713:                     }
                   15714:                     $showcourses{$cid} = $courses{$cid};
                   15715:                 }
                   15716:             }
                   15717:         }
                   15718:         %courses = %showcourses;
                   15719:     }
                   15720:     return %courses;
                   15721: }
                   15722: 
                   15723: =pod
                   15724: 
1.1181    raeburn  15725: =back
                   15726: 
1.1207    raeburn  15727: =head1 Routines for version requirements for current course.
                   15728: 
                   15729: =over 4
                   15730: 
                   15731: =item * &check_release_required()
                   15732: 
                   15733: Compares required LON-CAPA version with version on server, and
                   15734: if required version is newer looks for a server with the required version.
                   15735: 
                   15736: Looks first at servers in user's owen domain; if none suitable, looks at
                   15737: servers in course's domain are permitted to host sessions for user's domain.
                   15738: 
                   15739: Inputs:
                   15740: 
                   15741: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15742: 
                   15743: $courseid - Course ID of current course
                   15744: 
                   15745: $rolecode - User's current role in course (for switchserver query string).
                   15746: 
                   15747: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15748: 
                   15749: 
                   15750: Returns:
                   15751: 
                   15752: $switchserver - query string tp append to /adm/switchserver call (if 
                   15753:                 current server's LON-CAPA version is too old. 
                   15754: 
                   15755: $warning - Message is displayed if no suitable server could be found.
                   15756: 
                   15757: =cut
                   15758: 
                   15759: sub check_release_required {
                   15760:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15761:     my ($switchserver,$warning);
                   15762:     if ($required ne '') {
                   15763:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15764:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15765:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15766:             my $otherserver;
                   15767:             if (($major eq '' && $minor eq '') ||
                   15768:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15769:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15770:                 my $switchlcrev =
                   15771:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15772:                                                            $userdomserver);
                   15773:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15774:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15775:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15776:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15777:                     if ($cdom ne $env{'user.domain'}) {
                   15778:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15779:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15780:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15781:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15782:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15783:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15784:                         my $canhost =
                   15785:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15786:                                                               $coursedomserver,
                   15787:                                                               $remoterev,
                   15788:                                                               $udomdefaults{'remotesessions'},
                   15789:                                                               $defdomdefaults{'hostedsessions'});
                   15790: 
                   15791:                         if ($canhost) {
                   15792:                             $otherserver = $coursedomserver;
                   15793:                         } else {
                   15794:                             $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.");
                   15795:                         }
                   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 your own domain (which is also the course's domain).");
                   15798:                     }
                   15799:                 } else {
                   15800:                     $otherserver = $userdomserver;
                   15801:                 }
                   15802:             }
                   15803:             if ($otherserver ne '') {
                   15804:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   15805:             }
                   15806:         }
                   15807:     }
                   15808:     return ($switchserver,$warning);
                   15809: }
                   15810: 
                   15811: =pod
                   15812: 
                   15813: =item * &check_release_result()
                   15814: 
                   15815: Inputs:
                   15816: 
                   15817: $switchwarning - Warning message if no suitable server found to host session.
                   15818: 
                   15819: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15820:                 and current role.
                   15821: 
                   15822: Returns: HTML to display with information about requirement to switch server.
                   15823:          Either displaying warning with link to Roles/Courses screen or
                   15824:          display link to switchserver.
                   15825: 
1.1181    raeburn  15826: =cut
                   15827: 
1.1207    raeburn  15828: sub check_release_result {
                   15829:     my ($switchwarning,$switchserver) = @_;
                   15830:     my $output = &start_page('Selected course unavailable on this server').
                   15831:                  '<p class="LC_warning">';
                   15832:     if ($switchwarning) {
                   15833:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   15834:         if (&show_course()) {
                   15835:             $output .= &mt('Display courses');
                   15836:         } else {
                   15837:             $output .= &mt('Display roles');
                   15838:         }
                   15839:         $output .= '</a>';
                   15840:     } elsif ($switchserver) {
                   15841:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   15842:                    '<br />'.
                   15843:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   15844:                    &mt('Switch Server').
                   15845:                    '</a>';
                   15846:     }
                   15847:     $output .= '</p>'.&end_page();
                   15848:     return $output;
                   15849: }
                   15850: 
                   15851: =pod
                   15852: 
                   15853: =item * &needs_coursereinit()
                   15854: 
                   15855: Determine if course contents stored for user's session needs to be
                   15856: refreshed, because content has changed since "Big Hash" last tied.
                   15857: 
                   15858: Check for change is made if time last checked is more than 10 minutes ago
                   15859: (by default).
                   15860: 
                   15861: Inputs:
                   15862: 
                   15863: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15864: 
                   15865: $interval (optional) - Time which may elapse (in s) between last check for content
                   15866:                        change in current course. (default: 600 s).  
                   15867: 
                   15868: Returns: an array; first element is:
                   15869: 
                   15870: =over 4
                   15871: 
                   15872: 'switch' - if content updates mean user's session
                   15873:            needs to be switched to a server running a newer LON-CAPA version
                   15874:  
                   15875: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   15876:            on current server hosting user's session                
                   15877: 
                   15878: ''       - if no action required.
                   15879: 
                   15880: =back
                   15881: 
                   15882: If first item element is 'switch':
                   15883: 
                   15884: second item is $switchwarning - Warning message if no suitable server found to host session. 
                   15885: 
                   15886: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15887:                               and current role. 
                   15888: 
                   15889: otherwise: no other elements returned.
                   15890: 
                   15891: =back
                   15892: 
                   15893: =cut
                   15894: 
                   15895: sub needs_coursereinit {
                   15896:     my ($loncaparev,$interval) = @_;
                   15897:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   15898:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   15899:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   15900:     my $now = time;
                   15901:     if ($interval eq '') {
                   15902:         $interval = 600;
                   15903:     }
                   15904:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   15905:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15906:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   15907:         if ($lastchange > $env{'request.course.tied'}) {
                   15908:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15909:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   15910:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   15911:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   15912:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   15913:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   15914:                     my ($switchserver,$switchwarning) =
                   15915:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   15916:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   15917:                     if ($switchwarning ne '' || $switchserver ne '') {
                   15918:                         return ('switch',$switchwarning,$switchserver);
                   15919:                     }
                   15920:                 }
                   15921:             }
                   15922:             return ('update');
                   15923:         }
                   15924:     }
                   15925:     return ();
                   15926: }
1.1181    raeburn  15927: 
1.1083    raeburn  15928: sub update_content_constraints {
                   15929:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15930:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15931:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15932:     my %checkresponsetypes;
                   15933:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15934:         my ($item,$name,$value) = split(/:/,$key);
                   15935:         if ($item eq 'resourcetag') {
                   15936:             if ($name eq 'responsetype') {
                   15937:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15938:             }
                   15939:         }
                   15940:     }
                   15941:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15942:     if (defined($navmap)) {
                   15943:         my %allresponses;
                   15944:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15945:             my %responses = $res->responseTypes();
                   15946:             foreach my $key (keys(%responses)) {
                   15947:                 next unless(exists($checkresponsetypes{$key}));
                   15948:                 $allresponses{$key} += $responses{$key};
                   15949:             }
                   15950:         }
                   15951:         foreach my $key (keys(%allresponses)) {
                   15952:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15953:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15954:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15955:             }
                   15956:         }
                   15957:         undef($navmap);
                   15958:     }
                   15959:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15960:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15961:     }
                   15962:     return;
                   15963: }
                   15964: 
1.1110    raeburn  15965: sub allmaps_incourse {
                   15966:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15967:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15968:         $cid = $env{'request.course.id'};
                   15969:         $cdom = $env{'course.'.$cid.'.domain'};
                   15970:         $cnum = $env{'course.'.$cid.'.num'};
                   15971:         $chome = $env{'course.'.$cid.'.home'};
                   15972:     }
                   15973:     my %allmaps = ();
                   15974:     my $lastchange =
                   15975:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15976:     if ($lastchange > $env{'request.course.tied'}) {
                   15977:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15978:         unless ($ferr) {
                   15979:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15980:         }
                   15981:     }
                   15982:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15983:     if (defined($navmap)) {
                   15984:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15985:             $allmaps{$res->src()} = 1;
                   15986:         }
                   15987:     }
                   15988:     return \%allmaps;
                   15989: }
                   15990: 
1.1083    raeburn  15991: sub parse_supplemental_title {
                   15992:     my ($title) = @_;
                   15993: 
                   15994:     my ($foldertitle,$renametitle);
                   15995:     if ($title =~ /&amp;&amp;&amp;/) {
                   15996:         $title = &HTML::Entites::decode($title);
                   15997:     }
                   15998:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   15999:         $renametitle=$4;
                   16000:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16001:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16002:         my $name =  &plainname($uname,$udom);
                   16003:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16004:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16005:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16006:             $name.': <br />'.$foldertitle;
                   16007:     }
                   16008:     if (wantarray) {
                   16009:         return ($title,$foldertitle,$renametitle);
                   16010:     }
                   16011:     return $title;
                   16012: }
                   16013: 
1.1143    raeburn  16014: sub recurse_supplemental {
                   16015:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16016:     if ($suppmap) {
                   16017:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16018:         if ($fatal) {
                   16019:             $errors ++;
                   16020:         } else {
                   16021:             if ($#LONCAPA::map::resources > 0) {
                   16022:                 foreach my $res (@LONCAPA::map::resources) {
                   16023:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16024:                     if (($src ne '') && ($status eq 'res')) {
1.1146    raeburn  16025:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16026:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1143    raeburn  16027:                         } else {
                   16028:                             $numfiles ++;
                   16029:                         }
                   16030:                     }
                   16031:                 }
                   16032:             }
                   16033:         }
                   16034:     }
                   16035:     return ($numfiles,$errors);
                   16036: }
                   16037: 
1.1101    raeburn  16038: sub symb_to_docspath {
                   16039:     my ($symb) = @_;
                   16040:     return unless ($symb);
                   16041:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16042:     if ($resurl=~/\.(sequence|page)$/) {
                   16043:         $mapurl=$resurl;
                   16044:     } elsif ($resurl eq 'adm/navmaps') {
                   16045:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16046:     }
                   16047:     my $mapresobj;
                   16048:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16049:     if (ref($navmap)) {
                   16050:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   16051:     }
                   16052:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16053:     my $type=$2;
                   16054:     my $path;
                   16055:     if (ref($mapresobj)) {
                   16056:         my $pcslist = $mapresobj->map_hierarchy();
                   16057:         if ($pcslist ne '') {
                   16058:             foreach my $pc (split(/,/,$pcslist)) {
                   16059:                 next if ($pc <= 1);
                   16060:                 my $res = $navmap->getByMapPc($pc);
                   16061:                 if (ref($res)) {
                   16062:                     my $thisurl = $res->src();
                   16063:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16064:                     my $thistitle = $res->title();
                   16065:                     $path .= '&'.
                   16066:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1146    raeburn  16067:                              &escape($thistitle).
1.1101    raeburn  16068:                              ':'.$res->randompick().
                   16069:                              ':'.$res->randomout().
                   16070:                              ':'.$res->encrypted().
                   16071:                              ':'.$res->randomorder().
                   16072:                              ':'.$res->is_page();
                   16073:                 }
                   16074:             }
                   16075:         }
                   16076:         $path =~ s/^\&//;
                   16077:         my $maptitle = $mapresobj->title();
                   16078:         if ($mapurl eq 'default') {
1.1129    raeburn  16079:             $maptitle = 'Main Content';
1.1101    raeburn  16080:         }
                   16081:         $path .= (($path ne '')? '&' : '').
                   16082:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16083:                  &escape($maptitle).
1.1101    raeburn  16084:                  ':'.$mapresobj->randompick().
                   16085:                  ':'.$mapresobj->randomout().
                   16086:                  ':'.$mapresobj->encrypted().
                   16087:                  ':'.$mapresobj->randomorder().
                   16088:                  ':'.$mapresobj->is_page();
                   16089:     } else {
                   16090:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16091:         my $ispage = (($type eq 'page')? 1 : '');
                   16092:         if ($mapurl eq 'default') {
1.1129    raeburn  16093:             $maptitle = 'Main Content';
1.1101    raeburn  16094:         }
                   16095:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1146    raeburn  16096:                 &escape($maptitle).':::::'.$ispage;
1.1101    raeburn  16097:     }
                   16098:     unless ($mapurl eq 'default') {
                   16099:         $path = 'default&'.
1.1146    raeburn  16100:                 &escape('Main Content').
1.1101    raeburn  16101:                 ':::::&'.$path;
                   16102:     }
                   16103:     return $path;
                   16104: }
                   16105: 
1.1094    raeburn  16106: sub captcha_display {
                   16107:     my ($context,$lonhost) = @_;
                   16108:     my ($output,$error);
                   16109:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16110:     if ($captcha eq 'original') {
1.1094    raeburn  16111:         $output = &create_captcha();
                   16112:         unless ($output) {
1.1172    raeburn  16113:             $error = 'captcha';
1.1094    raeburn  16114:         }
                   16115:     } elsif ($captcha eq 'recaptcha') {
                   16116:         $output = &create_recaptcha($pubkey);
                   16117:         unless ($output) {
1.1172    raeburn  16118:             $error = 'recaptcha';
1.1094    raeburn  16119:         }
                   16120:     }
1.1176    raeburn  16121:     return ($output,$error,$captcha);
1.1094    raeburn  16122: }
                   16123: 
                   16124: sub captcha_response {
                   16125:     my ($context,$lonhost) = @_;
                   16126:     my ($captcha_chk,$captcha_error);
                   16127:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
1.1095    raeburn  16128:     if ($captcha eq 'original') {
1.1094    raeburn  16129:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16130:     } elsif ($captcha eq 'recaptcha') {
                   16131:         $captcha_chk = &check_recaptcha($privkey);
                   16132:     } else {
                   16133:         $captcha_chk = 1;
                   16134:     }
                   16135:     return ($captcha_chk,$captcha_error);
                   16136: }
                   16137: 
                   16138: sub get_captcha_config {
                   16139:     my ($context,$lonhost) = @_;
1.1095    raeburn  16140:     my ($captcha,$pubkey,$privkey,$hashtocheck);
1.1094    raeburn  16141:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16142:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16143:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
1.1095    raeburn  16144:     if ($context eq 'usercreation') {
                   16145:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16146:         if (ref($domconfig{$context}) eq 'HASH') {
                   16147:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16148:             if (ref($hashtocheck) eq 'HASH') {
                   16149:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16150:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16151:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16152:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16153:                     }
                   16154:                     if ($privkey && $pubkey) {
                   16155:                         $captcha = 'recaptcha';
                   16156:                     } else {
                   16157:                         $captcha = 'original';
                   16158:                     }
                   16159:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16160:                     $captcha = 'original';
                   16161:                 }
1.1094    raeburn  16162:             }
1.1095    raeburn  16163:         } else {
                   16164:             $captcha = 'captcha';
                   16165:         }
                   16166:     } elsif ($context eq 'login') {
                   16167:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16168:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16169:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16170:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
1.1094    raeburn  16171:             if ($privkey && $pubkey) {
                   16172:                 $captcha = 'recaptcha';
1.1095    raeburn  16173:             } else {
                   16174:                 $captcha = 'original';
1.1094    raeburn  16175:             }
1.1095    raeburn  16176:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16177:             $captcha = 'original';
1.1094    raeburn  16178:         }
                   16179:     }
                   16180:     return ($captcha,$pubkey,$privkey);
                   16181: }
                   16182: 
                   16183: sub create_captcha {
                   16184:     my %captcha_params = &captcha_settings();
                   16185:     my ($output,$maxtries,$tries) = ('',10,0);
                   16186:     while ($tries < $maxtries) {
                   16187:         $tries ++;
                   16188:         my $captcha = Authen::Captcha->new (
                   16189:                                            output_folder => $captcha_params{'output_dir'},
                   16190:                                            data_folder   => $captcha_params{'db_dir'},
                   16191:                                           );
                   16192:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16193: 
                   16194:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16195:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16196:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1176    raeburn  16197:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16198:                       '<br />'.
                   16199:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1094    raeburn  16200:             last;
                   16201:         }
                   16202:     }
                   16203:     return $output;
                   16204: }
                   16205: 
                   16206: sub captcha_settings {
                   16207:     my %captcha_params = (
                   16208:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16209:                            www_output_dir => "/captchaspool",
                   16210:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16211:                            numchars       => '5',
                   16212:                          );
                   16213:     return %captcha_params;
                   16214: }
                   16215: 
                   16216: sub check_captcha {
                   16217:     my ($captcha_chk,$captcha_error);
                   16218:     my $code = $env{'form.code'};
                   16219:     my $md5sum = $env{'form.crypt'};
                   16220:     my %captcha_params = &captcha_settings();
                   16221:     my $captcha = Authen::Captcha->new(
                   16222:                       output_folder => $captcha_params{'output_dir'},
                   16223:                       data_folder   => $captcha_params{'db_dir'},
                   16224:                   );
1.1109    raeburn  16225:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1094    raeburn  16226:     my %captcha_hash = (
                   16227:                         0       => 'Code not checked (file error)',
                   16228:                        -1      => 'Failed: code expired',
                   16229:                        -2      => 'Failed: invalid code (not in database)',
                   16230:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16231:     );
                   16232:     if ($captcha_chk != 1) {
                   16233:         $captcha_error = $captcha_hash{$captcha_chk}
                   16234:     }
                   16235:     return ($captcha_chk,$captcha_error);
                   16236: }
                   16237: 
                   16238: sub create_recaptcha {
                   16239:     my ($pubkey) = @_;
1.1153    raeburn  16240:     my $use_ssl;
                   16241:     if ($ENV{'SERVER_PORT'} == 443) {
                   16242:         $use_ssl = 1;
                   16243:     }
1.1094    raeburn  16244:     my $captcha = Captcha::reCAPTCHA->new;
                   16245:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1153    raeburn  16246:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1213    raeburn  16247:            &mt('If the text is hard to read, [_1] will replace them.',
1.1133    raeburn  16248:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1094    raeburn  16249:            '<br /><br />';
                   16250: }
                   16251: 
                   16252: sub check_recaptcha {
                   16253:     my ($privkey) = @_;
                   16254:     my $captcha_chk;
                   16255:     my $captcha = Captcha::reCAPTCHA->new;
                   16256:     my $captcha_result =
                   16257:         $captcha->check_answer(
                   16258:                                 $privkey,
                   16259:                                 $ENV{'REMOTE_ADDR'},
                   16260:                                 $env{'form.recaptcha_challenge_field'},
                   16261:                                 $env{'form.recaptcha_response_field'},
                   16262:                               );
                   16263:     if ($captcha_result->{is_valid}) {
                   16264:         $captcha_chk = 1;
                   16265:     }
                   16266:     return $captcha_chk;
                   16267: }
                   16268: 
1.1174    raeburn  16269: sub emailusername_info {
1.1177    raeburn  16270:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1174    raeburn  16271:     my %titles = &Apache::lonlocal::texthash (
                   16272:                      lastname      => 'Last Name',
                   16273:                      firstname     => 'First Name',
                   16274:                      institution   => 'School/college/university',
                   16275:                      location      => "School's city, state/province, country",
                   16276:                      web           => "School's web address",
                   16277:                      officialemail => 'E-mail address at institution (if different)',
                   16278:                  );
                   16279:     return (\@fields,\%titles);
                   16280: }
                   16281: 
1.1161    raeburn  16282: sub cleanup_html {
                   16283:     my ($incoming) = @_;
                   16284:     my $outgoing;
                   16285:     if ($incoming ne '') {
                   16286:         $outgoing = $incoming;
                   16287:         $outgoing =~ s/;/&#059;/g;
                   16288:         $outgoing =~ s/\#/&#035;/g;
                   16289:         $outgoing =~ s/\&/&#038;/g;
                   16290:         $outgoing =~ s/</&#060;/g;
                   16291:         $outgoing =~ s/>/&#062;/g;
                   16292:         $outgoing =~ s/\(/&#040/g;
                   16293:         $outgoing =~ s/\)/&#041;/g;
                   16294:         $outgoing =~ s/"/&#034;/g;
                   16295:         $outgoing =~ s/'/&#039;/g;
                   16296:         $outgoing =~ s/\$/&#036;/g;
                   16297:         $outgoing =~ s{/}{&#047;}g;
                   16298:         $outgoing =~ s/=/&#061;/g;
                   16299:         $outgoing =~ s/\\/&#092;/g
                   16300:     }
                   16301:     return $outgoing;
                   16302: }
                   16303: 
1.1190    musolffc 16304: # Checks for critical messages and returns a redirect url if one exists.
                   16305: # $interval indicates how often to check for messages.
                   16306: sub critical_redirect {
                   16307:     my ($interval) = @_;
                   16308:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16309:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'}, 
                   16310:                                         $env{'user.name'});
                   16311:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
1.1191    raeburn  16312:         my $redirecturl;
1.1190    musolffc 16313:         if ($what[0]) {
                   16314: 	    if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16315: 	        $redirecturl='/adm/email?critical=display';
1.1191    raeburn  16316: 	        my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16317:                 return (1, $url);
1.1190    musolffc 16318:             }
1.1191    raeburn  16319:         }
                   16320:     } 
                   16321:     return ();
1.1190    musolffc 16322: }
                   16323: 
1.1174    raeburn  16324: # Use:
                   16325: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16326: #
                   16327: ##################################################
                   16328: #          password associated functions         #
                   16329: ##################################################
                   16330: sub des_keys {
                   16331:     # Make a new key for DES encryption.
                   16332:     # Each key has two parts which are returned separately.
                   16333:     # Please note:  Each key must be passed through the &hex function
                   16334:     # before it is output to the web browser.  The hex versions cannot
                   16335:     # be used to decrypt.
                   16336:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16337:                 '8','9','a','b','c','d','e','f');
                   16338:     my $lkey='';
                   16339:     for (0..7) {
                   16340:         $lkey.=$hexstr[rand(15)];
                   16341:     }
                   16342:     my $ukey='';
                   16343:     for (0..7) {
                   16344:         $ukey.=$hexstr[rand(15)];
                   16345:     }
                   16346:     return ($lkey,$ukey);
                   16347: }
                   16348: 
                   16349: sub des_decrypt {
                   16350:     my ($key,$cyphertext) = @_;
                   16351:     my $keybin=pack("H16",$key);
                   16352:     my $cypher;
                   16353:     if ($Crypt::DES::VERSION>=2.03) {
                   16354:         $cypher=new Crypt::DES $keybin;
                   16355:     } else {
                   16356:         $cypher=new DES $keybin;
                   16357:     }
                   16358:     my $plaintext=
                   16359:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16360:     $plaintext.=
                   16361:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16362:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16363:     return $plaintext;
                   16364: }
                   16365: 
1.112     bowersj2 16366: 1;
                   16367: __END__;
1.41      ng       16368: 

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