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

1.10      albertel    1: # The LearningOnline Network with CAPA
1.1       albertel    2: # a pile of common routines
1.10      albertel    3: #
1.1075.2.100! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.99 2016/08/04 23:26:51 raeburn Exp $
1.10      albertel    5: #
                      6: # Copyright Michigan State University Board of Trustees
                      7: #
                      8: # This file is part of the LearningOnline Network with CAPA (LON-CAPA).
                      9: #
                     10: # LON-CAPA is free software; you can redistribute it and/or modify
                     11: # it under the terms of the GNU General Public License as published by
                     12: # the Free Software Foundation; either version 2 of the License, or
                     13: # (at your option) any later version.
                     14: #
                     15: # LON-CAPA is distributed in the hope that it will be useful,
                     16: # but WITHOUT ANY WARRANTY; without even the implied warranty of
                     17: # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
                     18: # GNU General Public License for more details.
                     19: #
                     20: # You should have received a copy of the GNU General Public License
                     21: # along with LON-CAPA; if not, write to the Free Software
                     22: # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
                     23: #
                     24: # /home/httpd/html/adm/gpl.txt
                     25: #
                     26: # http://www.lon-capa.org/
                     27: #
1.1       albertel   28: 
                     29: # Makes a table out of the previous attempts
1.2       albertel   30: # Inputs result_from_symbread, user, domain, course_id
1.16      harris41   31: # Reads in non-network-related .tab files
1.1       albertel   32: 
1.35      matthew    33: # POD header:
                     34: 
1.45      matthew    35: =pod
                     36: 
1.35      matthew    37: =head1 NAME
                     38: 
                     39: Apache::loncommon - pile of common routines
                     40: 
                     41: =head1 SYNOPSIS
                     42: 
1.112     bowersj2   43: Common routines for manipulating connections, student answers,
                     44:     domains, common Javascript fragments, etc.
1.35      matthew    45: 
1.112     bowersj2   46: =head1 OVERVIEW
1.35      matthew    47: 
1.112     bowersj2   48: A collection of commonly used subroutines that don't have a natural
                     49: home anywhere else. This collection helps remove
1.35      matthew    50: redundancy from other modules and increase efficiency of memory usage.
                     51: 
                     52: =cut 
                     53: 
                     54: # End of POD header
1.1       albertel   55: package Apache::loncommon;
                     56: 
                     57: use strict;
1.258     albertel   58: use Apache::lonnet;
1.46      matthew    59: use GDBM_File;
1.51      www        60: use POSIX qw(strftime mktime);
1.82      www        61: use Apache::lonmenu();
1.498     albertel   62: use Apache::lonenc();
1.117     www        63: use Apache::lonlocal;
1.685     tempelho   64: use Apache::lonnet();
1.139     matthew    65: use HTML::Entities;
1.334     albertel   66: use Apache::lonhtmlcommon();
                     67: use Apache::loncoursedata();
1.344     albertel   68: use Apache::lontexconvert();
1.444     albertel   69: use Apache::lonclonecourse();
1.1075.2.25  raeburn    70: use Apache::lonuserutils();
1.1075.2.27  raeburn    71: use Apache::lonuserstate();
1.1075.2.69  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.1075.2.94  raeburn    76: use Encode();
1.1075.2.14  raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1075.2.64  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.1048    foxr      165: my %latex_language;		# For choosing hyphenation in <transl..>
                    166: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  167: my %cprtag;
1.192     taceyjo1  168: my %scprtag;
1.351     www       169: my %fe; my %fd; my %fm;
1.41      ng        170: my %category_extensions;
1.12      harris41  171: 
1.46      matthew   172: # ---------------------------------------------- Thesaurus variables
1.144     matthew   173: #
                    174: # %Keywords:
                    175: #      A hash used by &keyword to determine if a word is considered a keyword.
                    176: # $thesaurus_db_file 
                    177: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   178: 
                    179: my %Keywords;
                    180: my $thesaurus_db_file;
                    181: 
1.144     matthew   182: #
                    183: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    184: # thesaurus.tab, and filecategories.tab.
                    185: #
1.18      www       186: BEGIN {
1.46      matthew   187:     # Variable initialization
                    188:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    189:     #
1.22      www       190:     unless ($readit) {
1.12      harris41  191: # ------------------------------------------------------------------- languages
                    192:     {
1.158     raeburn   193:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    194:                                    '/language.tab';
                    195:         if ( open(my $fh,"<$langtabfile") ) {
1.356     albertel  196:             while (my $line = <$fh>) {
                    197:                 next if ($line=~/^\#/);
                    198:                 chomp($line);
1.1048    foxr      199:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   200:                 $language{$key}=$val.' - '.$enc;
                    201:                 if ($sup) {
                    202:                     $supported_language{$key}=$sup;
                    203:                 }
1.1048    foxr      204: 		if ($latex) {
                    205: 		    $latex_language_bykey{$key} = $latex;
                    206: 		    $latex_language{$two} = $latex;
                    207: 		}
1.158     raeburn   208:             }
                    209:             close($fh);
                    210:         }
1.12      harris41  211:     }
                    212: # ------------------------------------------------------------------ copyrights
                    213:     {
1.158     raeburn   214:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    215:                                   '/copyright.tab';
                    216:         if ( open (my $fh,"<$copyrightfile") ) {
1.356     albertel  217:             while (my $line = <$fh>) {
                    218:                 next if ($line=~/^\#/);
                    219:                 chomp($line);
                    220:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   221:                 $cprtag{$key}=$val;
                    222:             }
                    223:             close($fh);
                    224:         }
1.12      harris41  225:     }
1.351     www       226: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  227:     {
                    228:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    229:                                   '/source_copyright.tab';
                    230:         if ( open (my $fh,"<$sourcecopyrightfile") ) {
1.356     albertel  231:             while (my $line = <$fh>) {
                    232:                 next if ($line =~ /^\#/);
                    233:                 chomp($line);
                    234:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  235:                 $scprtag{$key}=$val;
                    236:             }
                    237:             close($fh);
                    238:         }
                    239:     }
1.63      www       240: 
1.517     raeburn   241: # -------------------------------------------------------------- default domain designs
1.63      www       242:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   243:     my $designfile = $designdir.'/default.tab';
                    244:     if ( open (my $fh,"<$designfile") ) {
                    245:         while (my $line = <$fh>) {
                    246:             next if ($line =~ /^\#/);
                    247:             chomp($line);
                    248:             my ($key,$val)=(split(/\=/,$line));
                    249:             if ($val) { $defaultdesign{$key}=$val; }
                    250:         }
                    251:         close($fh);
1.63      www       252:     }
                    253: 
1.15      harris41  254: # ------------------------------------------------------------- file categories
                    255:     {
1.158     raeburn   256:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    257:                                   '/filecategories.tab';
                    258:         if ( open (my $fh,"<$categoryfile") ) {
1.356     albertel  259: 	    while (my $line = <$fh>) {
                    260: 		next if ($line =~ /^\#/);
                    261: 		chomp($line);
                    262:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.158     raeburn   263:                 push @{$category_extensions{lc($category)}},$extension;
                    264:             }
                    265:             close($fh);
                    266:         }
                    267: 
1.15      harris41  268:     }
1.12      harris41  269: # ------------------------------------------------------------------ file types
                    270:     {
1.158     raeburn   271:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    272:                '/filetypes.tab';
                    273:         if ( open (my $fh,"<$typesfile") ) {
1.356     albertel  274:             while (my $line = <$fh>) {
                    275: 		next if ($line =~ /^\#/);
                    276: 		chomp($line);
                    277:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   278:                 if ($descr ne '') {
                    279:                     $fe{$ending}=lc($emb);
                    280:                     $fd{$ending}=$descr;
1.351     www       281:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   282:                 }
                    283:             }
                    284:             close($fh);
                    285:         }
1.12      harris41  286:     }
1.22      www       287:     &Apache::lonnet::logthis(
1.705     tempelho  288:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       289:     $readit=1;
1.46      matthew   290:     }  # end of unless($readit) 
1.32      matthew   291:     
                    292: }
1.112     bowersj2  293: 
1.42      matthew   294: ###############################################################
                    295: ##           HTML and Javascript Helper Functions            ##
                    296: ###############################################################
                    297: 
                    298: =pod 
                    299: 
1.112     bowersj2  300: =head1 HTML and Javascript Functions
1.42      matthew   301: 
1.112     bowersj2  302: =over 4
                    303: 
1.648     raeburn   304: =item * &browser_and_searcher_javascript()
1.112     bowersj2  305: 
                    306: X<browsing, javascript>X<searching, javascript>Returns a string
                    307: containing javascript with two functions, C<openbrowser> and
                    308: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    309: tags.
1.42      matthew   310: 
1.648     raeburn   311: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   312: 
                    313: inputs: formname, elementname, only, omit
                    314: 
                    315: formname and elementname indicate the name of the html form and name of
                    316: the element that the results of the browsing selection are to be placed in. 
                    317: 
                    318: Specifying 'only' will restrict the browser to displaying only files
1.185     www       319: with the given extension.  Can be a comma separated list.
1.42      matthew   320: 
                    321: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       322: with the given extension.  Can be a comma separated list.
1.42      matthew   323: 
1.648     raeburn   324: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   325: 
                    326: Inputs: formname, elementname
                    327: 
                    328: formname and elementname specify the name of the html form and the name
                    329: of the element the selection from the search results will be placed in.
1.542     raeburn   330: 
1.42      matthew   331: =cut
                    332: 
                    333: sub browser_and_searcher_javascript {
1.199     albertel  334:     my ($mode)=@_;
                    335:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  336:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   337:     return <<END;
1.219     albertel  338: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   339:     var editbrowser = null;
1.135     albertel  340:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       341:         var url = '$resurl/?';
1.42      matthew   342:         if (editbrowser == null) {
                    343:             url += 'launch=1&';
                    344:         }
                    345:         url += 'catalogmode=interactive&';
1.199     albertel  346:         url += 'mode=$mode&';
1.611     albertel  347:         url += 'inhibitmenu=yes&';
1.42      matthew   348:         url += 'form=' + formname + '&';
                    349:         if (only != null) {
                    350:             url += 'only=' + only + '&';
1.217     albertel  351:         } else {
                    352:             url += 'only=&';
                    353: 	}
1.42      matthew   354:         if (omit != null) {
                    355:             url += 'omit=' + omit + '&';
1.217     albertel  356:         } else {
                    357:             url += 'omit=&';
                    358: 	}
1.135     albertel  359:         if (titleelement != null) {
                    360:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  361:         } else {
                    362: 	    url += 'titleelement=&';
                    363: 	}
1.42      matthew   364:         url += 'element=' + elementname + '';
                    365:         var title = 'Browser';
1.435     albertel  366:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   367:         options += ',width=700,height=600';
                    368:         editbrowser = open(url,title,options,'1');
                    369:         editbrowser.focus();
                    370:     }
                    371:     var editsearcher;
1.135     albertel  372:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   373:         var url = '/adm/searchcat?';
                    374:         if (editsearcher == null) {
                    375:             url += 'launch=1&';
                    376:         }
                    377:         url += 'catalogmode=interactive&';
1.199     albertel  378:         url += 'mode=$mode&';
1.42      matthew   379:         url += 'form=' + formname + '&';
1.135     albertel  380:         if (titleelement != null) {
                    381:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  382:         } else {
                    383: 	    url += 'titleelement=&';
                    384: 	}
1.42      matthew   385:         url += 'element=' + elementname + '';
                    386:         var title = 'Search';
1.435     albertel  387:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   388:         options += ',width=700,height=600';
                    389:         editsearcher = open(url,title,options,'1');
                    390:         editsearcher.focus();
                    391:     }
1.219     albertel  392: // END LON-CAPA Internal -->
1.42      matthew   393: END
1.170     www       394: }
                    395: 
                    396: sub lastresurl {
1.258     albertel  397:     if ($env{'environment.lastresurl'}) {
                    398: 	return $env{'environment.lastresurl'}
1.170     www       399:     } else {
                    400: 	return '/res';
                    401:     }
                    402: }
                    403: 
                    404: sub storeresurl {
                    405:     my $resurl=&Apache::lonnet::clutter(shift);
                    406:     unless ($resurl=~/^\/res/) { return 0; }
                    407:     $resurl=~s/\/$//;
                    408:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   409:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       410:     return 1;
1.42      matthew   411: }
                    412: 
1.74      www       413: sub studentbrowser_javascript {
1.111     www       414:    unless (
1.258     albertel  415:             (($env{'request.course.id'}) && 
1.302     albertel  416:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    417: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    418: 					  '/'.$env{'request.course.sec'})
                    419: 	      ))
1.258     albertel  420:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       421:           ) { return ''; }  
1.74      www       422:    return (<<'ENDSTDBRW');
1.776     bisitz    423: <script type="text/javascript" language="Javascript">
1.824     bisitz    424: // <![CDATA[
1.74      www       425:     var stdeditbrowser;
1.999     www       426:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       427:         var url = '/adm/pickstudent?';
                    428:         var filter;
1.558     albertel  429: 	if (!ignorefilter) {
                    430: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    431: 	}
1.74      www       432:         if (filter != null) {
                    433:            if (filter != '') {
                    434:                url += 'filter='+filter+'&';
                    435: 	   }
                    436:         }
                    437:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       438:                                     '&udomelement='+udom+
                    439:                                     '&clicker='+clicker;
1.111     www       440: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   441:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       442:         var title = 'Student_Browser';
1.74      www       443:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    444:         options += ',width=700,height=600';
                    445:         stdeditbrowser = open(url,title,options,'1');
                    446:         stdeditbrowser.focus();
                    447:     }
1.824     bisitz    448: // ]]>
1.74      www       449: </script>
                    450: ENDSTDBRW
                    451: }
1.42      matthew   452: 
1.1003    www       453: sub resourcebrowser_javascript {
                    454:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       455:    return (<<'ENDRESBRW');
1.1003    www       456: <script type="text/javascript" language="Javascript">
                    457: // <![CDATA[
                    458:     var reseditbrowser;
1.1004    www       459:     function openresbrowser(formname,reslink) {
1.1005    www       460:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       461:         var title = 'Resource_Browser';
                    462:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       463:         options += ',width=700,height=500';
1.1004    www       464:         reseditbrowser = open(url,title,options,'1');
                    465:         reseditbrowser.focus();
1.1003    www       466:     }
                    467: // ]]>
                    468: </script>
1.1004    www       469: ENDRESBRW
1.1003    www       470: }
                    471: 
1.74      www       472: sub selectstudent_link {
1.999     www       473:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    474:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    475:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    476:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  477:    if ($env{'request.course.id'}) {  
1.302     albertel  478:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    479: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    480: 					'/'.$env{'request.course.sec'})) {
1.111     www       481: 	   return '';
                    482:        }
1.999     www       483:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   484:        if ($courseadvonly)  {
                    485:            $callargs .= ",'',1,1";
                    486:        }
                    487:        return '<span class="LC_nobreak">'.
                    488:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    489:               &mt('Select User').'</a></span>';
1.74      www       490:    }
1.258     albertel  491:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       492:        $callargs .= ",'',1"; 
1.793     raeburn   493:        return '<span class="LC_nobreak">'.
                    494:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    495:               &mt('Select User').'</a></span>';
1.111     www       496:    }
                    497:    return '';
1.91      www       498: }
                    499: 
1.1004    www       500: sub selectresource_link {
                    501:    my ($form,$reslink,$arg)=@_;
                    502:    
                    503:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    504:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    505:    unless ($env{'request.course.id'}) { return $arg; }
                    506:    return '<span class="LC_nobreak">'.
                    507:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    508:               $arg.'</a></span>';
                    509: }
                    510: 
                    511: 
                    512: 
1.653     raeburn   513: sub authorbrowser_javascript {
                    514:     return <<"ENDAUTHORBRW";
1.776     bisitz    515: <script type="text/javascript" language="JavaScript">
1.824     bisitz    516: // <![CDATA[
1.653     raeburn   517: var stdeditbrowser;
                    518: 
                    519: function openauthorbrowser(formname,udom) {
                    520:     var url = '/adm/pickauthor?';
                    521:     url += 'form='+formname+'&roledom='+udom;
                    522:     var title = 'Author_Browser';
                    523:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    524:     options += ',width=700,height=600';
                    525:     stdeditbrowser = open(url,title,options,'1');
                    526:     stdeditbrowser.focus();
                    527: }
                    528: 
1.824     bisitz    529: // ]]>
1.653     raeburn   530: </script>
                    531: ENDAUTHORBRW
                    532: }
                    533: 
1.91      www       534: sub coursebrowser_javascript {
1.1075.2.31  raeburn   535:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   536:         $credits_element,$instcode) = @_;
1.932     raeburn   537:     my $wintitle = 'Course_Browser';
1.931     raeburn   538:     if ($crstype eq 'Community') {
1.932     raeburn   539:         $wintitle = 'Community_Browser';
1.909     raeburn   540:     }
1.876     raeburn   541:     my $id_functions = &javascript_index_functions();
                    542:     my $output = '
1.776     bisitz    543: <script type="text/javascript" language="JavaScript">
1.824     bisitz    544: // <![CDATA[
1.468     raeburn   545:     var stdeditbrowser;'."\n";
1.876     raeburn   546: 
                    547:     $output .= <<"ENDSTDBRW";
1.909     raeburn   548:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       549:         var url = '/adm/pickcourse?';
1.895     raeburn   550:         var formid = getFormIdByName(formname);
1.876     raeburn   551:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  552:         if (domainfilter != null) {
                    553:            if (domainfilter != '') {
                    554:                url += 'domainfilter='+domainfilter+'&';
                    555: 	   }
                    556:         }
1.91      www       557:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  558: 	                            '&cdomelement='+udom+
                    559:                                     '&cnameelement='+desc;
1.468     raeburn   560:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   561:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   562:                 url += '&roleelement='+extra_element;
                    563:                 if (domainfilter == null || domainfilter == '') {
                    564:                     url += '&domainfilter='+extra_element;
                    565:                 }
1.234     raeburn   566:             }
1.468     raeburn   567:             else {
                    568:                 if (formname == 'portform') {
                    569:                     url += '&setroles='+extra_element;
1.800     raeburn   570:                 } else {
                    571:                     if (formname == 'rules') {
                    572:                         url += '&fixeddom='+extra_element; 
                    573:                     }
1.468     raeburn   574:                 }
                    575:             }     
1.230     raeburn   576:         }
1.909     raeburn   577:         if (type != null && type != '') {
                    578:             url += '&type='+type;
                    579:         }
                    580:         if (type_elem != null && type_elem != '') {
                    581:             url += '&typeelement='+type_elem;
                    582:         }
1.872     raeburn   583:         if (formname == 'ccrs') {
                    584:             var ownername = document.forms[formid].ccuname.value;
                    585:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.95  raeburn   586:             url += '&cloner='+ownername+':'+ownerdom+'&crscode='+document.forms[formid].crscode.value;
                    587:         }
                    588:         if (formname == 'requestcrs') {
                    589:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   590:         }
1.293     raeburn   591:         if (multflag !=null && multflag != '') {
                    592:             url += '&multiple='+multflag;
                    593:         }
1.909     raeburn   594:         var title = '$wintitle';
1.91      www       595:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    596:         options += ',width=700,height=600';
                    597:         stdeditbrowser = open(url,title,options,'1');
                    598:         stdeditbrowser.focus();
                    599:     }
1.876     raeburn   600: $id_functions
                    601: ENDSTDBRW
1.1075.2.31  raeburn   602:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    603:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    604:                                       $credits_element);
1.876     raeburn   605:     }
                    606:     $output .= '
                    607: // ]]>
                    608: </script>';
                    609:     return $output;
                    610: }
                    611: 
                    612: sub javascript_index_functions {
                    613:     return <<"ENDJS";
                    614: 
                    615: function getFormIdByName(formname) {
                    616:     for (var i=0;i<document.forms.length;i++) {
                    617:         if (document.forms[i].name == formname) {
                    618:             return i;
                    619:         }
                    620:     }
                    621:     return -1;
                    622: }
                    623: 
                    624: function getIndexByName(formid,item) {
                    625:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    626:         if (document.forms[formid].elements[i].name == item) {
                    627:             return i;
                    628:         }
                    629:     }
                    630:     return -1;
                    631: }
1.468     raeburn   632: 
1.876     raeburn   633: function getDomainFromSelectbox(formname,udom) {
                    634:     var userdom;
                    635:     var formid = getFormIdByName(formname);
                    636:     if (formid > -1) {
                    637:         var domid = getIndexByName(formid,udom);
                    638:         if (domid > -1) {
                    639:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    640:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    641:             }
                    642:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    643:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   644:             }
                    645:         }
                    646:     }
1.876     raeburn   647:     return userdom;
                    648: }
                    649: 
                    650: ENDJS
1.468     raeburn   651: 
1.876     raeburn   652: }
                    653: 
1.1017    raeburn   654: sub javascript_array_indexof {
1.1018    raeburn   655:     return <<ENDJS;
1.1017    raeburn   656: <script type="text/javascript" language="JavaScript">
                    657: // <![CDATA[
                    658: 
                    659: if (!Array.prototype.indexOf) {
                    660:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    661:         "use strict";
                    662:         if (this === void 0 || this === null) {
                    663:             throw new TypeError();
                    664:         }
                    665:         var t = Object(this);
                    666:         var len = t.length >>> 0;
                    667:         if (len === 0) {
                    668:             return -1;
                    669:         }
                    670:         var n = 0;
                    671:         if (arguments.length > 0) {
                    672:             n = Number(arguments[1]);
                    673:             if (n !== n) { // shortcut for verifying if it's NaN
                    674:                 n = 0;
                    675:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    676:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    677:             }
                    678:         }
                    679:         if (n >= len) {
                    680:             return -1;
                    681:         }
                    682:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    683:         for (; k < len; k++) {
                    684:             if (k in t && t[k] === searchElement) {
                    685:                 return k;
                    686:             }
                    687:         }
                    688:         return -1;
                    689:     }
                    690: }
                    691: 
                    692: // ]]>
                    693: </script>
                    694: 
                    695: ENDJS
                    696: 
                    697: }
                    698: 
1.876     raeburn   699: sub userbrowser_javascript {
                    700:     my $id_functions = &javascript_index_functions();
                    701:     return <<"ENDUSERBRW";
                    702: 
1.888     raeburn   703: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   704:     var url = '/adm/pickuser?';
                    705:     var userdom = getDomainFromSelectbox(formname,udom);
                    706:     if (userdom != null) {
                    707:        if (userdom != '') {
                    708:            url += 'srchdom='+userdom+'&';
                    709:        }
                    710:     }
                    711:     url += 'form=' + formname + '&unameelement='+uname+
                    712:                                 '&udomelement='+udom+
                    713:                                 '&ulastelement='+ulast+
                    714:                                 '&ufirstelement='+ufirst+
                    715:                                 '&uemailelement='+uemail+
1.881     raeburn   716:                                 '&hideudomelement='+hideudom+
                    717:                                 '&coursedom='+crsdom;
1.888     raeburn   718:     if ((caller != null) && (caller != undefined)) {
                    719:         url += '&caller='+caller;
                    720:     }
1.876     raeburn   721:     var title = 'User_Browser';
                    722:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    723:     options += ',width=700,height=600';
                    724:     var stdeditbrowser = open(url,title,options,'1');
                    725:     stdeditbrowser.focus();
                    726: }
                    727: 
1.888     raeburn   728: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   729:     var formid = getFormIdByName(formname);
                    730:     if (formid > -1) {
1.888     raeburn   731:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   732:         var domid = getIndexByName(formid,udom);
                    733:         var hidedomid = getIndexByName(formid,origdom);
                    734:         if (hidedomid > -1) {
                    735:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   736:             var unameval = document.forms[formid].elements[unameid].value;
                    737:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    738:                 if (domid > -1) {
                    739:                     var slct = document.forms[formid].elements[domid];
                    740:                     if (slct.type == 'select-one') {
                    741:                         var i;
                    742:                         for (i=0;i<slct.length;i++) {
                    743:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    744:                         }
                    745:                     }
                    746:                     if (slct.type == 'hidden') {
                    747:                         slct.value = fixeddom;
1.876     raeburn   748:                     }
                    749:                 }
1.468     raeburn   750:             }
                    751:         }
                    752:     }
1.876     raeburn   753:     return;
                    754: }
                    755: 
                    756: $id_functions
                    757: ENDUSERBRW
1.468     raeburn   758: }
                    759: 
                    760: sub setsec_javascript {
1.1075.2.31  raeburn   761:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   762:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    763:         $communityrolestr);
                    764:     if ($role_element ne '') {
                    765:         my @allroles = ('st','ta','ep','in','ad');
                    766:         foreach my $crstype ('Course','Community') {
                    767:             if ($crstype eq 'Community') {
                    768:                 foreach my $role (@allroles) {
                    769:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    770:                 }
                    771:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    772:             } else {
                    773:                 foreach my $role (@allroles) {
                    774:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    775:                 }
                    776:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    777:             }
                    778:         }
                    779:         $rolestr = '"'.join('","',@allroles).'"';
                    780:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    781:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    782:     }
1.468     raeburn   783:     my $setsections = qq|
                    784: function setSect(sectionlist) {
1.629     raeburn   785:     var sectionsArray = new Array();
                    786:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    787:         sectionsArray = sectionlist.split(",");
                    788:     }
1.468     raeburn   789:     var numSections = sectionsArray.length;
                    790:     document.$formname.$sec_element.length = 0;
                    791:     if (numSections == 0) {
                    792:         document.$formname.$sec_element.multiple=false;
                    793:         document.$formname.$sec_element.size=1;
                    794:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    795:     } else {
                    796:         if (numSections == 1) {
                    797:             document.$formname.$sec_element.multiple=false;
                    798:             document.$formname.$sec_element.size=1;
                    799:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    800:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    801:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    802:         } else {
                    803:             for (var i=0; i<numSections; i++) {
                    804:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    805:             }
                    806:             document.$formname.$sec_element.multiple=true
                    807:             if (numSections < 3) {
                    808:                 document.$formname.$sec_element.size=numSections;
                    809:             } else {
                    810:                 document.$formname.$sec_element.size=3;
                    811:             }
                    812:             document.$formname.$sec_element.options[0].selected = false
                    813:         }
                    814:     }
1.91      www       815: }
1.905     raeburn   816: 
                    817: function setRole(crstype) {
1.468     raeburn   818: |;
1.905     raeburn   819:     if ($role_element eq '') {
                    820:         $setsections .= '    return;
                    821: }
                    822: ';
                    823:     } else {
                    824:         $setsections .= qq|
                    825:     var elementLength = document.$formname.$role_element.length;
                    826:     var allroles = Array($rolestr);
                    827:     var courserolenames = Array($courserolestr);
                    828:     var communityrolenames = Array($communityrolestr);
                    829:     if (elementLength != undefined) {
                    830:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    831:             if (crstype == 'Course') {
                    832:                 return;
                    833:             } else {
                    834:                 allroles[5] = 'co';
                    835:                 for (var i=0; i<6; i++) {
                    836:                     document.$formname.$role_element.options[i].value = allroles[i];
                    837:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    838:                 }
                    839:             }
                    840:         } else {
                    841:             if (crstype == 'Community') {
                    842:                 return;
                    843:             } else {
                    844:                 allroles[5] = 'cc';
                    845:                 for (var i=0; i<6; i++) {
                    846:                     document.$formname.$role_element.options[i].value = allroles[i];
                    847:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    848:                 }
                    849:             }
                    850:         }
                    851:     }
                    852:     return;
                    853: }
                    854: |;
                    855:     }
1.1075.2.31  raeburn   856:     if ($credits_element) {
                    857:         $setsections .= qq|
                    858: function setCredits(defaultcredits) {
                    859:     document.$formname.$credits_element.value = defaultcredits;
                    860:     return;
                    861: }
                    862: |;
                    863:     }
1.468     raeburn   864:     return $setsections;
                    865: }
                    866: 
1.91      www       867: sub selectcourse_link {
1.909     raeburn   868:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    869:        $typeelement) = @_;
                    870:    my $type = $selecttype;
1.871     raeburn   871:    my $linktext = &mt('Select Course');
                    872:    if ($selecttype eq 'Community') {
1.909     raeburn   873:        $linktext = &mt('Select Community');
1.906     raeburn   874:    } elsif ($selecttype eq 'Course/Community') {
                    875:        $linktext = &mt('Select Course/Community');
1.909     raeburn   876:        $type = '';
1.1019    raeburn   877:    } elsif ($selecttype eq 'Select') {
                    878:        $linktext = &mt('Select');
                    879:        $type = '';
1.871     raeburn   880:    }
1.787     bisitz    881:    return '<span class="LC_nobreak">'
                    882:          ."<a href='"
                    883:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    884:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   885:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   886:          ."'>".$linktext.'</a>'
1.787     bisitz    887:          .'</span>';
1.74      www       888: }
1.42      matthew   889: 
1.653     raeburn   890: sub selectauthor_link {
                    891:    my ($form,$udom)=@_;
                    892:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    893:           &mt('Select Author').'</a>';
                    894: }
                    895: 
1.876     raeburn   896: sub selectuser_link {
1.881     raeburn   897:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   898:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   899:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   900:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   901:            ');">'.$linktext.'</a>';
1.876     raeburn   902: }
                    903: 
1.273     raeburn   904: sub check_uncheck_jscript {
                    905:     my $jscript = <<"ENDSCRT";
                    906: function checkAll(field) {
                    907:     if (field.length > 0) {
                    908:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   909:             if (!field[i].disabled) {
                    910:                 field[i].checked = true;
                    911:             }
1.273     raeburn   912:         }
                    913:     } else {
1.1075.2.14  raeburn   914:         if (!field.disabled) {
                    915:             field.checked = true;
                    916:         }
1.273     raeburn   917:     }
                    918: }
                    919:  
                    920: function uncheckAll(field) {
                    921:     if (field.length > 0) {
                    922:         for (i = 0; i < field.length; i++) {
                    923:             field[i].checked = false ;
1.543     albertel  924:         }
                    925:     } else {
1.273     raeburn   926:         field.checked = false ;
                    927:     }
                    928: }
                    929: ENDSCRT
                    930:     return $jscript;
                    931: }
                    932: 
1.656     www       933: sub select_timezone {
1.659     raeburn   934:    my ($name,$selected,$onchange,$includeempty)=@_;
                    935:    my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    936:    if ($includeempty) {
                    937:        $output .= '<option value=""';
                    938:        if (($selected eq '') || ($selected eq 'local')) {
                    939:            $output .= ' selected="selected" ';
                    940:        }
                    941:        $output .= '> </option>';
                    942:    }
1.657     raeburn   943:    my @timezones = DateTime::TimeZone->all_names;
                    944:    foreach my $tzone (@timezones) {
                    945:        $output.= '<option value="'.$tzone.'"';
                    946:        if ($tzone eq $selected) {
                    947:            $output.=' selected="selected"';
                    948:        }
                    949:        $output.=">$tzone</option>\n";
1.656     www       950:    }
                    951:    $output.="</select>";
                    952:    return $output;
                    953: }
1.273     raeburn   954: 
1.687     raeburn   955: sub select_datelocale {
                    956:     my ($name,$selected,$onchange,$includeempty)=@_;
                    957:     my $output='<select name="'.$name.'" '.$onchange.'>'."\n";
                    958:     if ($includeempty) {
                    959:         $output .= '<option value=""';
                    960:         if ($selected eq '') {
                    961:             $output .= ' selected="selected" ';
                    962:         }
                    963:         $output .= '> </option>';
                    964:     }
                    965:     my (@possibles,%locale_names);
                    966:     my @locales = DateTime::Locale::Catalog::Locales;
                    967:     foreach my $locale (@locales) {
                    968:         if (ref($locale) eq 'HASH') {
                    969:             my $id = $locale->{'id'};
                    970:             if ($id ne '') {
                    971:                 my $en_terr = $locale->{'en_territory'};
                    972:                 my $native_terr = $locale->{'native_territory'};
1.695     raeburn   973:                 my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   974:                 if (grep(/^en$/,@languages) || !@languages) {
                    975:                     if ($en_terr ne '') {
                    976:                         $locale_names{$id} = '('.$en_terr.')';
                    977:                     } elsif ($native_terr ne '') {
                    978:                         $locale_names{$id} = $native_terr;
                    979:                     }
                    980:                 } else {
                    981:                     if ($native_terr ne '') {
                    982:                         $locale_names{$id} = $native_terr.' ';
                    983:                     } elsif ($en_terr ne '') {
                    984:                         $locale_names{$id} = '('.$en_terr.')';
                    985:                     }
                    986:                 }
1.1075.2.94  raeburn   987:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.687     raeburn   988:                 push (@possibles,$id);
                    989:             }
                    990:         }
                    991:     }
                    992:     foreach my $item (sort(@possibles)) {
                    993:         $output.= '<option value="'.$item.'"';
                    994:         if ($item eq $selected) {
                    995:             $output.=' selected="selected"';
                    996:         }
                    997:         $output.=">$item";
                    998:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn   999:             $output.='  '.$locale_names{$item};
1.687     raeburn  1000:         }
                   1001:         $output.="</option>\n";
                   1002:     }
                   1003:     $output.="</select>";
                   1004:     return $output;
                   1005: }
                   1006: 
1.792     raeburn  1007: sub select_language {
                   1008:     my ($name,$selected,$includeempty) = @_;
                   1009:     my %langchoices;
                   1010:     if ($includeempty) {
1.1075.2.32  raeburn  1011:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1012:     }
                   1013:     foreach my $id (&languageids()) {
                   1014:         my $code = &supportedlanguagecode($id);
                   1015:         if ($code) {
                   1016:             $langchoices{$code} = &plainlanguagedescription($id);
                   1017:         }
                   1018:     }
1.1075.2.32  raeburn  1019:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.970     raeburn  1020:     return &select_form($selected,$name,\%langchoices);
1.792     raeburn  1021: }
                   1022: 
1.42      matthew  1023: =pod
1.36      matthew  1024: 
1.648     raeburn  1025: =item * &linked_select_forms(...)
1.36      matthew  1026: 
                   1027: linked_select_forms returns a string containing a <script></script> block
                   1028: and html for two <select> menus.  The select menus will be linked in that
                   1029: changing the value of the first menu will result in new values being placed
                   1030: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1031: order unless a defined order is provided.
1.36      matthew  1032: 
                   1033: linked_select_forms takes the following ordered inputs:
                   1034: 
                   1035: =over 4
                   1036: 
1.112     bowersj2 1037: =item * $formname, the name of the <form> tag
1.36      matthew  1038: 
1.112     bowersj2 1039: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1040: 
1.112     bowersj2 1041: =item * $firstdefault, the default value for the first menu
1.36      matthew  1042: 
1.112     bowersj2 1043: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1044: 
1.112     bowersj2 1045: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1046: 
1.112     bowersj2 1047: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1048: 
1.609     raeburn  1049: =item * $menuorder, the order of values in the first menu
                   1050: 
1.1075.2.31  raeburn  1051: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1052:         event for the first <select> tag
                   1053: 
                   1054: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1055:         event for the second <select> tag
                   1056: 
1.41      ng       1057: =back 
                   1058: 
1.36      matthew  1059: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1060: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1061: values for the first select menu.  The text that coincides with the 
1.41      ng       1062: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1063: and text for the second menu are given in the hash pointed to by 
                   1064: $menu{$choice1}->{'select2'}.  
                   1065: 
1.112     bowersj2 1066:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1067:                        default => "B3",
                   1068:                        select2 => { 
                   1069:                            B1 => "Choice B1",
                   1070:                            B2 => "Choice B2",
                   1071:                            B3 => "Choice B3",
                   1072:                            B4 => "Choice B4"
1.609     raeburn  1073:                            },
                   1074:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1075:                    },
                   1076:                A2 => { text =>"Choice A2" ,
                   1077:                        default => "C2",
                   1078:                        select2 => { 
                   1079:                            C1 => "Choice C1",
                   1080:                            C2 => "Choice C2",
                   1081:                            C3 => "Choice C3"
1.609     raeburn  1082:                            },
                   1083:                        order => ['C2','C1','C3'],
1.112     bowersj2 1084:                    },
                   1085:                A3 => { text =>"Choice A3" ,
                   1086:                        default => "D6",
                   1087:                        select2 => { 
                   1088:                            D1 => "Choice D1",
                   1089:                            D2 => "Choice D2",
                   1090:                            D3 => "Choice D3",
                   1091:                            D4 => "Choice D4",
                   1092:                            D5 => "Choice D5",
                   1093:                            D6 => "Choice D6",
                   1094:                            D7 => "Choice D7"
1.609     raeburn  1095:                            },
                   1096:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1097:                    }
                   1098:                );
1.36      matthew  1099: 
                   1100: =cut
                   1101: 
                   1102: sub linked_select_forms {
                   1103:     my ($formname,
                   1104:         $middletext,
                   1105:         $firstdefault,
                   1106:         $firstselectname,
                   1107:         $secondselectname, 
1.609     raeburn  1108:         $hashref,
                   1109:         $menuorder,
1.1075.2.31  raeburn  1110:         $onchangefirst,
                   1111:         $onchangesecond
1.36      matthew  1112:         ) = @_;
                   1113:     my $second = "document.$formname.$secondselectname";
                   1114:     my $first = "document.$formname.$firstselectname";
                   1115:     # output the javascript to do the changing
                   1116:     my $result = '';
1.776     bisitz   1117:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1118:     $result.="// <![CDATA[\n";
1.36      matthew  1119:     $result.="var select2data = new Object();\n";
                   1120:     $" = '","';
                   1121:     my $debug = '';
                   1122:     foreach my $s1 (sort(keys(%$hashref))) {
                   1123:         $result.="select2data.d_$s1 = new Object();\n";        
                   1124:         $result.="select2data.d_$s1.def = new String('".
                   1125:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1126:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1127:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1128:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1129:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1130:         }
1.36      matthew  1131:         $result.="\"@s2values\");\n";
                   1132:         $result.="select2data.d_$s1.texts = new Array(";        
                   1133:         my @s2texts;
                   1134:         foreach my $value (@s2values) {
                   1135:             push @s2texts, $hashref->{$s1}->{'select2'}->{$value};
                   1136:         }
                   1137:         $result.="\"@s2texts\");\n";
                   1138:     }
                   1139:     $"=' ';
                   1140:     $result.= <<"END";
                   1141: 
                   1142: function select1_changed() {
                   1143:     // Determine new choice
                   1144:     var newvalue = "d_" + $first.value;
                   1145:     // update select2
                   1146:     var values     = select2data[newvalue].values;
                   1147:     var texts      = select2data[newvalue].texts;
                   1148:     var select2def = select2data[newvalue].def;
                   1149:     var i;
                   1150:     // out with the old
                   1151:     for (i = 0; i < $second.options.length; i++) {
                   1152:         $second.options[i] = null;
                   1153:     }
                   1154:     // in with the nuclear
                   1155:     for (i=0;i<values.length; i++) {
                   1156:         $second.options[i] = new Option(values[i]);
1.143     matthew  1157:         $second.options[i].value = values[i];
1.36      matthew  1158:         $second.options[i].text = texts[i];
                   1159:         if (values[i] == select2def) {
                   1160:             $second.options[i].selected = true;
                   1161:         }
                   1162:     }
                   1163: }
1.824     bisitz   1164: // ]]>
1.36      matthew  1165: </script>
                   1166: END
                   1167:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1168:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1169:     my @order = sort(keys(%{$hashref}));
                   1170:     if (ref($menuorder) eq 'ARRAY') {
                   1171:         @order = @{$menuorder};
                   1172:     }
                   1173:     foreach my $value (@order) {
1.36      matthew  1174:         $result.="    <option value=\"$value\" ";
1.253     albertel 1175:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1176:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1177:     }
                   1178:     $result .= "</select>\n";
                   1179:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1180:     $result .= $middletext;
1.1075.2.31  raeburn  1181:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1182:     if ($onchangesecond) {
                   1183:         $result .= ' onchange="'.$onchangesecond.'"';
                   1184:     }
                   1185:     $result .= ">\n";
1.36      matthew  1186:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1187:     
                   1188:     my @secondorder = sort(keys(%select2));
                   1189:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1190:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1191:     }
                   1192:     foreach my $value (@secondorder) {
1.36      matthew  1193:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1194:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1195:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1196:     }
                   1197:     $result .= "</select>\n";
                   1198:     #    return $debug;
                   1199:     return $result;
                   1200: }   #  end of sub linked_select_forms {
                   1201: 
1.45      matthew  1202: =pod
1.44      bowersj2 1203: 
1.973     raeburn  1204: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1205: 
1.112     bowersj2 1206: Returns a string corresponding to an HTML link to the given help
                   1207: $topic, where $topic corresponds to the name of a .tex file in
                   1208: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1209: spaces. 
                   1210: 
                   1211: $text will optionally be linked to the same topic, allowing you to
                   1212: link text in addition to the graphic. If you do not want to link
                   1213: text, but wish to specify one of the later parameters, pass an
                   1214: empty string. 
                   1215: 
                   1216: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1217: the link will not open a new window. If false, the link will open
                   1218: a new window using Javascript. (Default is false.) 
                   1219: 
                   1220: $width and $height are optional numerical parameters that will
                   1221: override the width and height of the popped up window, which may
1.973     raeburn  1222: be useful for certain help topics with big pictures included.
                   1223: 
                   1224: $imgid is the id of the img tag used for the help icon. This may be
                   1225: used in a javascript call to switch the image src.  See 
                   1226: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1227: 
                   1228: =cut
                   1229: 
                   1230: sub help_open_topic {
1.973     raeburn  1231:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1232:     $text = "" if (not defined $text);
1.44      bowersj2 1233:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1234:     $width = 500 if (not defined $width);
1.44      bowersj2 1235:     $height = 400 if (not defined $height);
                   1236:     my $filename = $topic;
                   1237:     $filename =~ s/ /_/g;
                   1238: 
1.48      bowersj2 1239:     my $template = "";
                   1240:     my $link;
1.572     banghart 1241:     
1.159     www      1242:     $topic=~s/\W/\_/g;
1.44      bowersj2 1243: 
1.572     banghart 1244:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1245:         if ($env{'browser.mobile'}) {
                   1246: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1247:         } else {
                   1248:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1249:         }
1.1037    www      1250:     } elsif ($stayOnPage eq 'popup') {
                   1251:         $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 1252:     } else {
1.48      bowersj2 1253: 	$link = "/adm/help/${filename}.hlp";
                   1254:     }
                   1255: 
                   1256:     # Add the text
1.755     neumanie 1257:     if ($text ne "") {	
1.763     bisitz   1258: 	$template.='<span class="LC_help_open_topic">'
                   1259:                   .'<a target="_top" href="'.$link.'">'
                   1260:                   .$text.'</a>';
1.48      bowersj2 1261:     }
                   1262: 
1.763     bisitz   1263:     # (Always) Add the graphic
1.179     matthew  1264:     my $title = &mt('Online Help');
1.667     raeburn  1265:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1266:     if ($imgid ne '') {
                   1267:         $imgid = ' id="'.$imgid.'"';
                   1268:     }
1.763     bisitz   1269:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1270:               .'<img src="'.$helpicon.'" border="0"'
                   1271:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1272:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1273:               .' /></a>';
                   1274:     if ($text ne "") {	
                   1275:         $template.='</span>';
                   1276:     }
1.44      bowersj2 1277:     return $template;
                   1278: 
1.106     bowersj2 1279: }
                   1280: 
                   1281: # This is a quicky function for Latex cheatsheet editing, since it 
                   1282: # appears in at least four places
                   1283: sub helpLatexCheatsheet {
1.1037    www      1284:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1285:     my $out;
1.106     bowersj2 1286:     my $addOther = '';
1.732     raeburn  1287:     if ($topic) {
1.1037    www      1288: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1289:     }
                   1290:     $out = '<span>' # Start cheatsheet
                   1291: 	  .$addOther
                   1292:           .'<span>'
1.1037    www      1293: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1294: 	  .'</span> <span>'
1.1037    www      1295: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1296: 	  .'</span>';
1.732     raeburn  1297:     unless ($not_author) {
1.763     bisitz   1298:         $out .= ' <span>'
1.1037    www      1299: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1300: 	       .'</span> <span>'
1.1075.2.78  raeburn  1301:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1302:                .'</span>';
1.732     raeburn  1303:     }
1.763     bisitz   1304:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1305:     return $out;
1.172     www      1306: }
                   1307: 
1.430     albertel 1308: sub general_help {
                   1309:     my $helptopic='Student_Intro';
                   1310:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1311: 	$helptopic='Authoring_Intro';
1.907     raeburn  1312:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1313: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1314:     } elsif ($env{'request.role'}=~/^dc/) {
                   1315:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1316:     }
                   1317:     return $helptopic;
                   1318: }
                   1319: 
                   1320: sub update_help_link {
                   1321:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1322:     my $origurl = $ENV{'REQUEST_URI'};
                   1323:     $origurl=~s|^/~|/priv/|;
                   1324:     my $timestamp = time;
                   1325:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1326:         $$datum = &escape($$datum);
                   1327:     }
                   1328: 
                   1329:     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";
                   1330:     my $output .= <<"ENDOUTPUT";
                   1331: <script type="text/javascript">
1.824     bisitz   1332: // <![CDATA[
1.430     albertel 1333: banner_link = '$banner_link';
1.824     bisitz   1334: // ]]>
1.430     albertel 1335: </script>
                   1336: ENDOUTPUT
                   1337:     return $output;
                   1338: }
                   1339: 
                   1340: # now just updates the help link and generates a blue icon
1.193     raeburn  1341: sub help_open_menu {
1.430     albertel 1342:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1343: 	= @_;    
1.949     droeschl 1344:     $stayOnPage = 1;
1.430     albertel 1345:     my $output;
                   1346:     if ($component_help) {
                   1347: 	if (!$text) {
                   1348: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1349: 				       $width,$height);
                   1350: 	} else {
                   1351: 	    my $help_text;
                   1352: 	    $help_text=&unescape($topic);
                   1353: 	    $output='<table><tr><td>'.
                   1354: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1355: 				 $width,$height).'</td></tr></table>';
                   1356: 	}
                   1357:     }
                   1358:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1359:     return $output.$banner_link;
                   1360: }
                   1361: 
                   1362: sub top_nav_help {
                   1363:     my ($text) = @_;
1.436     albertel 1364:     $text = &mt($text);
1.1075.2.60  raeburn  1365:     my $stay_on_page;
                   1366:     unless ($env{'environment.remote'} eq 'on') {
                   1367:         $stay_on_page = 1;
                   1368:     }
1.1075.2.61  raeburn  1369:     my ($link,$banner_link);
                   1370:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1371:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1372: 	                         : "javascript:helpMenu('open')";
                   1373:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1374:     }
1.201     raeburn  1375:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1376:     if ($link) {
                   1377:         return <<"END";
1.436     albertel 1378: $banner_link
1.1075.2.56  raeburn  1379: <a href="$link" title="$title">$text</a>
1.436     albertel 1380: END
1.1075.2.61  raeburn  1381:     } else {
                   1382:         return '&nbsp;'.$text.'&nbsp;';
                   1383:     }
1.436     albertel 1384: }
                   1385: 
                   1386: sub help_menu_js {
1.1075.2.52  raeburn  1387:     my ($httphost) = @_;
1.949     droeschl 1388:     my $stayOnPage = 1;
1.436     albertel 1389:     my $width = 620;
                   1390:     my $height = 600;
1.430     albertel 1391:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1392:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1393:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1394:     my $start_page =
                   1395:         &Apache::loncommon::start_page('Help Menu', undef,
                   1396: 				       {'frameset'    => 1,
                   1397: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1398:                                         'use_absolute' => $httphost, 
1.331     albertel 1399: 					'add_entries' => {
                   1400: 					    'border' => '0',
1.579     raeburn  1401: 					    'rows'   => "110,*",},});
1.331     albertel 1402:     my $end_page =
                   1403:         &Apache::loncommon::end_page({'frameset' => 1,
                   1404: 				      'js_ready' => 1,});
                   1405: 
1.436     albertel 1406:     my $template .= <<"ENDTEMPLATE";
                   1407: <script type="text/javascript">
1.877     bisitz   1408: // <![CDATA[
1.253     albertel 1409: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1410: var banner_link = '';
1.243     raeburn  1411: function helpMenu(target) {
                   1412:     var caller = this;
                   1413:     if (target == 'open') {
                   1414:         var newWindow = null;
                   1415:         try {
1.262     albertel 1416:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1417:         }
                   1418:         catch(error) {
                   1419:             writeHelp(caller);
                   1420:             return;
                   1421:         }
                   1422:         if (newWindow) {
                   1423:             caller = newWindow;
                   1424:         }
1.193     raeburn  1425:     }
1.243     raeburn  1426:     writeHelp(caller);
                   1427:     return;
                   1428: }
                   1429: function writeHelp(caller) {
1.1075.2.61  raeburn  1430:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1431:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1432:     caller.document.close();
                   1433:     caller.focus();
1.193     raeburn  1434: }
1.877     bisitz   1435: // END LON-CAPA Internal -->
1.253     albertel 1436: // ]]>
1.436     albertel 1437: </script>
1.193     raeburn  1438: ENDTEMPLATE
                   1439:     return $template;
                   1440: }
                   1441: 
1.172     www      1442: sub help_open_bug {
                   1443:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1444:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1445:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1446:     $text = "" if (not defined $text);
                   1447: 	$stayOnPage=1;
1.184     albertel 1448:     $width = 600 if (not defined $width);
                   1449:     $height = 600 if (not defined $height);
1.172     www      1450: 
                   1451:     $topic=~s/\W+/\+/g;
                   1452:     my $link='';
                   1453:     my $template='';
1.379     albertel 1454:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1455: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1456:     if (!$stayOnPage)
                   1457:     {
                   1458: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1459:     }
                   1460:     else
                   1461:     {
                   1462: 	$link = $url;
                   1463:     }
                   1464:     # Add the text
                   1465:     if ($text ne "")
                   1466:     {
                   1467: 	$template .= 
                   1468:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1469:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1470:     }
                   1471: 
                   1472:     # Add the graphic
1.179     matthew  1473:     my $title = &mt('Report a Bug');
1.215     albertel 1474:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1475:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1476:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1477: ENDTEMPLATE
                   1478:     if ($text ne '') { $template.='</td></tr></table>' };
                   1479:     return $template;
                   1480: 
                   1481: }
                   1482: 
                   1483: sub help_open_faq {
                   1484:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1485:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1486:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1487:     $text = "" if (not defined $text);
                   1488: 	$stayOnPage=1;
                   1489:     $width = 350 if (not defined $width);
                   1490:     $height = 400 if (not defined $height);
                   1491: 
                   1492:     $topic=~s/\W+/\+/g;
                   1493:     my $link='';
                   1494:     my $template='';
                   1495:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1496:     if (!$stayOnPage)
                   1497:     {
                   1498: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1499:     }
                   1500:     else
                   1501:     {
                   1502: 	$link = $url;
                   1503:     }
                   1504: 
                   1505:     # Add the text
                   1506:     if ($text ne "")
                   1507:     {
                   1508: 	$template .= 
1.173     www      1509:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1510:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1511:     }
                   1512: 
                   1513:     # Add the graphic
1.179     matthew  1514:     my $title = &mt('View the FAQ');
1.215     albertel 1515:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1516:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1517:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1518: ENDTEMPLATE
                   1519:     if ($text ne '') { $template.='</td></tr></table>' };
                   1520:     return $template;
                   1521: 
1.44      bowersj2 1522: }
1.37      matthew  1523: 
1.180     matthew  1524: ###############################################################
                   1525: ###############################################################
                   1526: 
1.45      matthew  1527: =pod
                   1528: 
1.648     raeburn  1529: =item * &change_content_javascript():
1.256     matthew  1530: 
                   1531: This and the next function allow you to create small sections of an
                   1532: otherwise static HTML page that you can update on the fly with
                   1533: Javascript, even in Netscape 4.
                   1534: 
                   1535: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1536: must be written to the HTML page once. It will prove the Javascript
                   1537: function "change(name, content)". Calling the change function with the
                   1538: name of the section 
                   1539: you want to update, matching the name passed to C<changable_area>, and
                   1540: the new content you want to put in there, will put the content into
                   1541: that area.
                   1542: 
                   1543: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1544: to contain room for the original contents. You need to "make space"
                   1545: for whatever changes you wish to make, and be B<sure> to check your
                   1546: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1547: it's adequate for updating a one-line status display, but little more.
                   1548: This script will set the space to 100% width, so you only need to
                   1549: worry about height in Netscape 4.
                   1550: 
                   1551: Modern browsers are much less limiting, and if you can commit to the
                   1552: user not using Netscape 4, this feature may be used freely with
                   1553: pretty much any HTML.
                   1554: 
                   1555: =cut
                   1556: 
                   1557: sub change_content_javascript {
                   1558:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1559:     if ($env{'browser.type'} eq 'netscape' &&
                   1560: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1561: 	return (<<NETSCAPE4);
                   1562: 	function change(name, content) {
                   1563: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1564: 	    doc.open();
                   1565: 	    doc.write(content);
                   1566: 	    doc.close();
                   1567: 	}
                   1568: NETSCAPE4
                   1569:     } else {
                   1570: 	# Otherwise, we need to use semi-standards-compliant code
                   1571: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1572: 	# is really scary, and every useful browser supports it
                   1573: 	return (<<DOMBASED);
                   1574: 	function change(name, content) {
                   1575: 	    element = document.getElementById(name);
                   1576: 	    element.innerHTML = content;
                   1577: 	}
                   1578: DOMBASED
                   1579:     }
                   1580: }
                   1581: 
                   1582: =pod
                   1583: 
1.648     raeburn  1584: =item * &changable_area($name,$origContent):
1.256     matthew  1585: 
                   1586: This provides a "changable area" that can be modified on the fly via
                   1587: the Javascript code provided in C<change_content_javascript>. $name is
                   1588: the name you will use to reference the area later; do not repeat the
                   1589: same name on a given HTML page more then once. $origContent is what
                   1590: the area will originally contain, which can be left blank.
                   1591: 
                   1592: =cut
                   1593: 
                   1594: sub changable_area {
                   1595:     my ($name, $origContent) = @_;
                   1596: 
1.258     albertel 1597:     if ($env{'browser.type'} eq 'netscape' &&
                   1598: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1599: 	# If this is netscape 4, we need to use the Layer tag
                   1600: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1601:     } else {
                   1602: 	return "<span id='$name'>$origContent</span>";
                   1603:     }
                   1604: }
                   1605: 
                   1606: =pod
                   1607: 
1.648     raeburn  1608: =item * &viewport_geometry_js 
1.590     raeburn  1609: 
                   1610: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1611: 
                   1612: =cut
                   1613: 
                   1614: 
                   1615: sub viewport_geometry_js { 
                   1616:     return <<"GEOMETRY";
                   1617: var Geometry = {};
                   1618: function init_geometry() {
                   1619:     if (Geometry.init) { return };
                   1620:     Geometry.init=1;
                   1621:     if (window.innerHeight) {
                   1622:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1623:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1624:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1625:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1626:     }
                   1627:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1628:         Geometry.getViewportHeight =
                   1629:             function() { return document.documentElement.clientHeight; };
                   1630:         Geometry.getViewportWidth =
                   1631:             function() { return document.documentElement.clientWidth; };
                   1632: 
                   1633:         Geometry.getHorizontalScroll =
                   1634:             function() { return document.documentElement.scrollLeft; };
                   1635:         Geometry.getVerticalScroll =
                   1636:             function() { return document.documentElement.scrollTop; };
                   1637:     }
                   1638:     else if (document.body.clientHeight) {
                   1639:         Geometry.getViewportHeight =
                   1640:             function() { return document.body.clientHeight; };
                   1641:         Geometry.getViewportWidth =
                   1642:             function() { return document.body.clientWidth; };
                   1643:         Geometry.getHorizontalScroll =
                   1644:             function() { return document.body.scrollLeft; };
                   1645:         Geometry.getVerticalScroll =
                   1646:             function() { return document.body.scrollTop; };
                   1647:     }
                   1648: }
                   1649: 
                   1650: GEOMETRY
                   1651: }
                   1652: 
                   1653: =pod
                   1654: 
1.648     raeburn  1655: =item * &viewport_size_js()
1.590     raeburn  1656: 
                   1657: 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. 
                   1658: 
                   1659: =cut
                   1660: 
                   1661: sub viewport_size_js {
                   1662:     my $geometry = &viewport_geometry_js();
                   1663:     return <<"DIMS";
                   1664: 
                   1665: $geometry
                   1666: 
                   1667: function getViewportDims(width,height) {
                   1668:     init_geometry();
                   1669:     width.value = Geometry.getViewportWidth();
                   1670:     height.value = Geometry.getViewportHeight();
                   1671:     return;
                   1672: }
                   1673: 
                   1674: DIMS
                   1675: }
                   1676: 
                   1677: =pod
                   1678: 
1.648     raeburn  1679: =item * &resize_textarea_js()
1.565     albertel 1680: 
                   1681: emits the needed javascript to resize a textarea to be as big as possible
                   1682: 
                   1683: creates a function resize_textrea that takes two IDs first should be
                   1684: the id of the element to resize, second should be the id of a div that
                   1685: surrounds everything that comes after the textarea, this routine needs
                   1686: to be attached to the <body> for the onload and onresize events.
                   1687: 
1.648     raeburn  1688: =back
1.565     albertel 1689: 
                   1690: =cut
                   1691: 
                   1692: sub resize_textarea_js {
1.590     raeburn  1693:     my $geometry = &viewport_geometry_js();
1.565     albertel 1694:     return <<"RESIZE";
                   1695:     <script type="text/javascript">
1.824     bisitz   1696: // <![CDATA[
1.590     raeburn  1697: $geometry
1.565     albertel 1698: 
1.588     albertel 1699: function getX(element) {
                   1700:     var x = 0;
                   1701:     while (element) {
                   1702: 	x += element.offsetLeft;
                   1703: 	element = element.offsetParent;
                   1704:     }
                   1705:     return x;
                   1706: }
                   1707: function getY(element) {
                   1708:     var y = 0;
                   1709:     while (element) {
                   1710: 	y += element.offsetTop;
                   1711: 	element = element.offsetParent;
                   1712:     }
                   1713:     return y;
                   1714: }
                   1715: 
                   1716: 
1.565     albertel 1717: function resize_textarea(textarea_id,bottom_id) {
                   1718:     init_geometry();
                   1719:     var textarea        = document.getElementById(textarea_id);
                   1720:     //alert(textarea);
                   1721: 
1.588     albertel 1722:     var textarea_top    = getY(textarea);
1.565     albertel 1723:     var textarea_height = textarea.offsetHeight;
                   1724:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1725:     var bottom_top      = getY(bottom);
1.565     albertel 1726:     var bottom_height   = bottom.offsetHeight;
                   1727:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1728:     var fudge           = 23;
1.565     albertel 1729:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1730:     if (new_height < 300) {
                   1731: 	new_height = 300;
                   1732:     }
                   1733:     textarea.style.height=new_height+'px';
                   1734: }
1.824     bisitz   1735: // ]]>
1.565     albertel 1736: </script>
                   1737: RESIZE
                   1738: 
                   1739: }
                   1740: 
                   1741: =pod
                   1742: 
1.256     matthew  1743: =head1 Excel and CSV file utility routines
                   1744: 
                   1745: =cut
                   1746: 
                   1747: ###############################################################
                   1748: ###############################################################
                   1749: 
                   1750: =pod
                   1751: 
1.1075.2.56  raeburn  1752: =over 4
                   1753: 
1.648     raeburn  1754: =item * &csv_translate($text) 
1.37      matthew  1755: 
1.185     www      1756: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  1757: format.
                   1758: 
                   1759: =cut
                   1760: 
1.180     matthew  1761: ###############################################################
                   1762: ###############################################################
1.37      matthew  1763: sub csv_translate {
                   1764:     my $text = shift;
                   1765:     $text =~ s/\"/\"\"/g;
1.209     albertel 1766:     $text =~ s/\n/ /g;
1.37      matthew  1767:     return $text;
                   1768: }
1.180     matthew  1769: 
                   1770: ###############################################################
                   1771: ###############################################################
                   1772: 
                   1773: =pod
                   1774: 
1.648     raeburn  1775: =item * &define_excel_formats()
1.180     matthew  1776: 
                   1777: Define some commonly used Excel cell formats.
                   1778: 
                   1779: Currently supported formats:
                   1780: 
                   1781: =over 4
                   1782: 
                   1783: =item header
                   1784: 
                   1785: =item bold
                   1786: 
                   1787: =item h1
                   1788: 
                   1789: =item h2
                   1790: 
                   1791: =item h3
                   1792: 
1.256     matthew  1793: =item h4
                   1794: 
                   1795: =item i
                   1796: 
1.180     matthew  1797: =item date
                   1798: 
                   1799: =back
                   1800: 
                   1801: Inputs: $workbook
                   1802: 
                   1803: Returns: $format, a hash reference.
                   1804: 
1.1057    foxr     1805: 
1.180     matthew  1806: =cut
                   1807: 
                   1808: ###############################################################
                   1809: ###############################################################
                   1810: sub define_excel_formats {
                   1811:     my ($workbook) = @_;
                   1812:     my $format;
                   1813:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   1814:                                                 bottom    => 1,
                   1815:                                                 align     => 'center');
                   1816:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   1817:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   1818:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   1819:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  1820:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  1821:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  1822:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  1823:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  1824:     return $format;
                   1825: }
                   1826: 
                   1827: ###############################################################
                   1828: ###############################################################
1.113     bowersj2 1829: 
                   1830: =pod
                   1831: 
1.648     raeburn  1832: =item * &create_workbook()
1.255     matthew  1833: 
                   1834: Create an Excel worksheet.  If it fails, output message on the
                   1835: request object and return undefs.
                   1836: 
                   1837: Inputs: Apache request object
                   1838: 
                   1839: Returns (undef) on failure, 
                   1840:     Excel worksheet object, scalar with filename, and formats 
                   1841:     from &Apache::loncommon::define_excel_formats on success
                   1842: 
                   1843: =cut
                   1844: 
                   1845: ###############################################################
                   1846: ###############################################################
                   1847: sub create_workbook {
                   1848:     my ($r) = @_;
                   1849:         #
                   1850:     # Create the excel spreadsheet
                   1851:     my $filename = '/prtspool/'.
1.258     albertel 1852:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  1853:         time.'_'.rand(1000000000).'.xls';
                   1854:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   1855:     if (! defined($workbook)) {
                   1856:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   1857:         $r->print(
                   1858:             '<p class="LC_error">'
                   1859:            .&mt('Problems occurred in creating the new Excel file.')
                   1860:            .' '.&mt('This error has been logged.')
                   1861:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1862:            .'</p>'
                   1863:         );
1.255     matthew  1864:         return (undef);
                   1865:     }
                   1866:     #
1.1014    foxr     1867:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  1868:     #
                   1869:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   1870:     return ($workbook,$filename,$format);
                   1871: }
                   1872: 
                   1873: ###############################################################
                   1874: ###############################################################
                   1875: 
                   1876: =pod
                   1877: 
1.648     raeburn  1878: =item * &create_text_file()
1.113     bowersj2 1879: 
1.542     raeburn  1880: Create a file to write to and eventually make available to the user.
1.256     matthew  1881: If file creation fails, outputs an error message on the request object and 
                   1882: return undefs.
1.113     bowersj2 1883: 
1.256     matthew  1884: Inputs: Apache request object, and file suffix
1.113     bowersj2 1885: 
1.256     matthew  1886: Returns (undef) on failure, 
                   1887:     Filehandle and filename on success.
1.113     bowersj2 1888: 
                   1889: =cut
                   1890: 
1.256     matthew  1891: ###############################################################
                   1892: ###############################################################
                   1893: sub create_text_file {
                   1894:     my ($r,$suffix) = @_;
                   1895:     if (! defined($suffix)) { $suffix = 'txt'; };
                   1896:     my $fh;
                   1897:     my $filename = '/prtspool/'.
1.258     albertel 1898:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  1899:         time.'_'.rand(1000000000).'.'.$suffix;
                   1900:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   1901:     if (! defined($fh)) {
                   1902:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   1903:         $r->print(
                   1904:             '<p class="LC_error">'
                   1905:            .&mt('Problems occurred in creating the output file.')
                   1906:            .' '.&mt('This error has been logged.')
                   1907:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   1908:            .'</p>'
                   1909:         );
1.113     bowersj2 1910:     }
1.256     matthew  1911:     return ($fh,$filename)
1.113     bowersj2 1912: }
                   1913: 
                   1914: 
1.256     matthew  1915: =pod 
1.113     bowersj2 1916: 
                   1917: =back
                   1918: 
                   1919: =cut
1.37      matthew  1920: 
                   1921: ###############################################################
1.33      matthew  1922: ##        Home server <option> list generating code          ##
                   1923: ###############################################################
1.35      matthew  1924: 
1.169     www      1925: # ------------------------------------------
                   1926: 
                   1927: sub domain_select {
                   1928:     my ($name,$value,$multiple)=@_;
                   1929:     my %domains=map { 
1.514     albertel 1930: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 1931:     } &Apache::lonnet::all_domains();
1.169     www      1932:     if ($multiple) {
                   1933: 	$domains{''}=&mt('Any domain');
1.550     albertel 1934: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 1935: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      1936:     } else {
1.550     albertel 1937: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  1938: 	return &select_form($name,$value,\%domains);
1.169     www      1939:     }
                   1940: }
                   1941: 
1.282     albertel 1942: #-------------------------------------------
                   1943: 
                   1944: =pod
                   1945: 
1.519     raeburn  1946: =head1 Routines for form select boxes
                   1947: 
                   1948: =over 4
                   1949: 
1.648     raeburn  1950: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 1951: 
                   1952: Returns a string containing a <select> element int multiple mode
                   1953: 
                   1954: 
                   1955: Args:
                   1956:   $name - name of the <select> element
1.506     raeburn  1957:   $value - scalar or array ref of values that should already be selected
1.282     albertel 1958:   $size - number of rows long the select element is
1.283     albertel 1959:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 1960:           (shown text should already have been &mt())
1.506     raeburn  1961:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 1962: 
1.282     albertel 1963: =cut
                   1964: 
                   1965: #-------------------------------------------
1.169     www      1966: sub multiple_select_form {
1.284     albertel 1967:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      1968:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   1969:     my $output='';
1.191     matthew  1970:     if (! defined($size)) {
                   1971:         $size = 4;
1.283     albertel 1972:         if (scalar(keys(%$hash))<4) {
                   1973:             $size = scalar(keys(%$hash));
1.191     matthew  1974:         }
                   1975:     }
1.734     bisitz   1976:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 1977:     my @order;
1.506     raeburn  1978:     if (ref($order) eq 'ARRAY')  {
                   1979:         @order = @{$order};
                   1980:     } else {
                   1981:         @order = sort(keys(%$hash));
1.501     banghart 1982:     }
                   1983:     if (exists($$hash{'select_form_order'})) {
                   1984:         @order = @{$$hash{'select_form_order'}};
                   1985:     }
                   1986:         
1.284     albertel 1987:     foreach my $key (@order) {
1.356     albertel 1988:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 1989:         $output.='selected="selected" ' if ($selected{$key});
                   1990:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      1991:     }
                   1992:     $output.="</select>\n";
                   1993:     return $output;
                   1994: }
                   1995: 
1.88      www      1996: #-------------------------------------------
                   1997: 
                   1998: =pod
                   1999: 
1.970     raeburn  2000: =item * &select_form($defdom,$name,$hashref,$onchange)
1.88      www      2001: 
                   2002: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2003: allow a user to select options from a ref to a hash containing:
                   2004: option_name => displayed text. An optional $onchange can include
                   2005: a javascript onchange item, e.g., onchange="this.form.submit();"  
                   2006: 
1.88      www      2007: See lonrights.pm for an example invocation and use.
                   2008: 
                   2009: =cut
                   2010: 
                   2011: #-------------------------------------------
                   2012: sub select_form {
1.970     raeburn  2013:     my ($def,$name,$hashref,$onchange) = @_;
                   2014:     return unless (ref($hashref) eq 'HASH');
                   2015:     if ($onchange) {
                   2016:         $onchange = ' onchange="'.$onchange.'"';
                   2017:     }
                   2018:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.128     albertel 2019:     my @keys;
1.970     raeburn  2020:     if (exists($hashref->{'select_form_order'})) {
                   2021: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2022:     } else {
1.970     raeburn  2023: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2024:     }
1.356     albertel 2025:     foreach my $key (@keys) {
                   2026:         $selectform.=
                   2027: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2028:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2029:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2030:     }
                   2031:     $selectform.="</select>";
                   2032:     return $selectform;
                   2033: }
                   2034: 
1.475     www      2035: # For display filters
                   2036: 
                   2037: sub display_filter {
1.1074    raeburn  2038:     my ($context) = @_;
1.475     www      2039:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2040:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2041:     my $phraseinput = 'hidden';
                   2042:     my $includeinput = 'hidden';
                   2043:     my ($checked,$includetypestext);
                   2044:     if ($env{'form.displayfilter'} eq 'containing') {
                   2045:         $phraseinput = 'text'; 
                   2046:         if ($context eq 'parmslog') {
                   2047:             $includeinput = 'checkbox';
                   2048:             if ($env{'form.includetypes'}) {
                   2049:                 $checked = ' checked="checked"';
                   2050:             }
                   2051:             $includetypestext = &mt('Include parameter types');
                   2052:         }
                   2053:     } else {
                   2054:         $includetypestext = '&nbsp;';
                   2055:     }
                   2056:     my ($additional,$secondid,$thirdid);
                   2057:     if ($context eq 'parmslog') {
                   2058:         $additional = 
                   2059:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2060:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2061:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2062:             '</label>';
                   2063:         $secondid = 'includetypes';
                   2064:         $thirdid = 'includetypestext';
                   2065:     }
                   2066:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2067:                                                     '$secondid','$thirdid')";
                   2068:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2069: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2070: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2071: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2072:            &mt('Filter: [_1]',
1.477     www      2073: 	   &select_form($env{'form.displayfilter'},
                   2074: 			'displayfilter',
1.970     raeburn  2075: 			{'currentfolder' => 'Current folder/page',
1.477     www      2076: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2077: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2078: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2079:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2080:                          '" />'.$additional;
                   2081: }
                   2082: 
                   2083: sub display_filter_js {
                   2084:     my $includetext = &mt('Include parameter types');
                   2085:     return <<"ENDJS";
                   2086:   
                   2087: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2088:     var firstType = 'hidden';
                   2089:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2090:         firstType = 'text';
                   2091:     }
                   2092:     firstObject = document.getElementById(firstid);
                   2093:     if (typeof(firstObject) == 'object') {
                   2094:         if (firstObject.type != firstType) {
                   2095:             changeInputType(firstObject,firstType);
                   2096:         }
                   2097:     }
                   2098:     if (context == 'parmslog') {
                   2099:         var secondType = 'hidden';
                   2100:         if (firstType == 'text') {
                   2101:             secondType = 'checkbox';
                   2102:         }
                   2103:         secondObject = document.getElementById(secondid);  
                   2104:         if (typeof(secondObject) == 'object') {
                   2105:             if (secondObject.type != secondType) {
                   2106:                 changeInputType(secondObject,secondType);
                   2107:             }
                   2108:         }
                   2109:         var textItem = document.getElementById(thirdid);
                   2110:         var currtext = textItem.innerHTML;
                   2111:         var newtext;
                   2112:         if (firstType == 'text') {
                   2113:             newtext = '$includetext';
                   2114:         } else {
                   2115:             newtext = '&nbsp;';
                   2116:         }
                   2117:         if (currtext != newtext) {
                   2118:             textItem.innerHTML = newtext;
                   2119:         }
                   2120:     }
                   2121:     return;
                   2122: }
                   2123: 
                   2124: function changeInputType(oldObject,newType) {
                   2125:     var newObject = document.createElement('input');
                   2126:     newObject.type = newType;
                   2127:     if (oldObject.size) {
                   2128:         newObject.size = oldObject.size;
                   2129:     }
                   2130:     if (oldObject.value) {
                   2131:         newObject.value = oldObject.value;
                   2132:     }
                   2133:     if (oldObject.name) {
                   2134:         newObject.name = oldObject.name;
                   2135:     }
                   2136:     if (oldObject.id) {
                   2137:         newObject.id = oldObject.id;
                   2138:     }
                   2139:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2140:     return;
                   2141: }
                   2142: 
                   2143: ENDJS
1.475     www      2144: }
                   2145: 
1.167     www      2146: sub gradeleveldescription {
                   2147:     my $gradelevel=shift;
                   2148:     my %gradelevels=(0 => 'Not specified',
                   2149: 		     1 => 'Grade 1',
                   2150: 		     2 => 'Grade 2',
                   2151: 		     3 => 'Grade 3',
                   2152: 		     4 => 'Grade 4',
                   2153: 		     5 => 'Grade 5',
                   2154: 		     6 => 'Grade 6',
                   2155: 		     7 => 'Grade 7',
                   2156: 		     8 => 'Grade 8',
                   2157: 		     9 => 'Grade 9',
                   2158: 		     10 => 'Grade 10',
                   2159: 		     11 => 'Grade 11',
                   2160: 		     12 => 'Grade 12',
                   2161: 		     13 => 'Grade 13',
                   2162: 		     14 => '100 Level',
                   2163: 		     15 => '200 Level',
                   2164: 		     16 => '300 Level',
                   2165: 		     17 => '400 Level',
                   2166: 		     18 => 'Graduate Level');
                   2167:     return &mt($gradelevels{$gradelevel});
                   2168: }
                   2169: 
1.163     www      2170: sub select_level_form {
                   2171:     my ($deflevel,$name)=@_;
                   2172:     unless ($deflevel) { $deflevel=0; }
1.167     www      2173:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2174:     for (my $i=0; $i<=18; $i++) {
                   2175:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2176:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2177:                 ">".&gradeleveldescription($i)."</option>\n";
                   2178:     }
                   2179:     $selectform.="</select>";
                   2180:     return $selectform;
1.163     www      2181: }
1.167     www      2182: 
1.35      matthew  2183: #-------------------------------------------
                   2184: 
1.45      matthew  2185: =pod
                   2186: 
1.1075.2.42  raeburn  2187: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms)
1.35      matthew  2188: 
                   2189: Returns a string containing a <select name='$name' size='1'> form to 
                   2190: allow a user to select the domain to preform an operation in.  
                   2191: See loncreateuser.pm for an example invocation and use.
                   2192: 
1.90      www      2193: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2194: selected");
                   2195: 
1.743     raeburn  2196: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2197: 
1.910     raeburn  2198: 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.
                   2199: 
1.1075.2.36  raeburn  2200: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2201: 
                   2202: The optional $excdoms is a reference to an array of domains which will be excluded from the available options. 
1.563     raeburn  2203: 
1.35      matthew  2204: =cut
                   2205: 
                   2206: #-------------------------------------------
1.34      matthew  2207: sub select_dom_form {
1.1075.2.36  raeburn  2208:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms) = @_;
1.872     raeburn  2209:     if ($onchange) {
1.874     raeburn  2210:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2211:     }
1.1075.2.36  raeburn  2212:     my (@domains,%exclude);
1.910     raeburn  2213:     if (ref($incdoms) eq 'ARRAY') {
                   2214:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2215:     } else {
                   2216:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2217:     }
1.90      www      2218:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2219:     if (ref($excdoms) eq 'ARRAY') {
                   2220:         map { $exclude{$_} = 1; } @{$excdoms};
                   2221:     }
1.743     raeburn  2222:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange>\n";
1.356     albertel 2223:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2224:         next if ($exclude{$dom});
1.356     albertel 2225:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2226:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2227:         if ($showdomdesc) {
                   2228:             if ($dom ne '') {
                   2229:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2230:                 if ($domdesc ne '') {
                   2231:                     $selectdomain .= ' ('.$domdesc.')';
                   2232:                 }
                   2233:             } 
                   2234:         }
                   2235:         $selectdomain .= "</option>\n";
1.34      matthew  2236:     }
                   2237:     $selectdomain.="</select>";
                   2238:     return $selectdomain;
                   2239: }
                   2240: 
1.35      matthew  2241: #-------------------------------------------
                   2242: 
1.45      matthew  2243: =pod
                   2244: 
1.648     raeburn  2245: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2246: 
1.586     raeburn  2247: input: 4 arguments (two required, two optional) - 
                   2248:     $domain - domain of new user
                   2249:     $name - name of form element
                   2250:     $default - Value of 'default' causes a default item to be first 
                   2251:                             option, and selected by default. 
                   2252:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2253:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2254: output: returns 2 items: 
1.586     raeburn  2255: (a) form element which contains either:
                   2256:    (i) <select name="$name">
                   2257:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2258:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2259:        </select>
                   2260:        form item if there are multiple library servers in $domain, or
                   2261:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2262:        if there is only one library server in $domain.
                   2263: 
                   2264: (b) number of library servers found.
                   2265: 
                   2266: See loncreateuser.pm for example of use.
1.35      matthew  2267: 
                   2268: =cut
                   2269: 
                   2270: #-------------------------------------------
1.586     raeburn  2271: sub home_server_form_item {
                   2272:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2273:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2274:     my $result;
                   2275:     my $numlib = keys(%servers);
                   2276:     if ($numlib > 1) {
                   2277:         $result .= '<select name="'.$name.'" />'."\n";
                   2278:         if ($default) {
1.804     bisitz   2279:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2280:                        '</option>'."\n";
                   2281:         }
                   2282:         foreach my $hostid (sort(keys(%servers))) {
                   2283:             $result.= '<option value="'.$hostid.'">'.
                   2284: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2285:         }
                   2286:         $result .= '</select>'."\n";
                   2287:     } elsif ($numlib == 1) {
                   2288:         my $hostid;
                   2289:         foreach my $item (keys(%servers)) {
                   2290:             $hostid = $item;
                   2291:         }
                   2292:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2293:                    $hostid.'" />';
                   2294:                    if (!$hide) {
                   2295:                        $result .= $hostid.' '.$servers{$hostid};
                   2296:                    }
                   2297:                    $result .= "\n";
                   2298:     } elsif ($default) {
                   2299:         $result .= '<input type="hidden" name="'.$name.
                   2300:                    '" value="default" />';
                   2301:                    if (!$hide) {
                   2302:                        $result .= &mt('default');
                   2303:                    }
                   2304:                    $result .= "\n";
1.33      matthew  2305:     }
1.586     raeburn  2306:     return ($result,$numlib);
1.33      matthew  2307: }
1.112     bowersj2 2308: 
                   2309: =pod
                   2310: 
1.534     albertel 2311: =back 
                   2312: 
1.112     bowersj2 2313: =cut
1.87      matthew  2314: 
                   2315: ###############################################################
1.112     bowersj2 2316: ##                  Decoding User Agent                      ##
1.87      matthew  2317: ###############################################################
                   2318: 
                   2319: =pod
                   2320: 
1.112     bowersj2 2321: =head1 Decoding the User Agent
                   2322: 
                   2323: =over 4
                   2324: 
                   2325: =item * &decode_user_agent()
1.87      matthew  2326: 
                   2327: Inputs: $r
                   2328: 
                   2329: Outputs:
                   2330: 
                   2331: =over 4
                   2332: 
1.112     bowersj2 2333: =item * $httpbrowser
1.87      matthew  2334: 
1.112     bowersj2 2335: =item * $clientbrowser
1.87      matthew  2336: 
1.112     bowersj2 2337: =item * $clientversion
1.87      matthew  2338: 
1.112     bowersj2 2339: =item * $clientmathml
1.87      matthew  2340: 
1.112     bowersj2 2341: =item * $clientunicode
1.87      matthew  2342: 
1.112     bowersj2 2343: =item * $clientos
1.87      matthew  2344: 
1.1075.2.42  raeburn  2345: =item * $clientmobile
                   2346: 
                   2347: =item * $clientinfo
                   2348: 
1.1075.2.77  raeburn  2349: =item * $clientosversion
                   2350: 
1.87      matthew  2351: =back
                   2352: 
1.157     matthew  2353: =back 
                   2354: 
1.87      matthew  2355: =cut
                   2356: 
                   2357: ###############################################################
                   2358: ###############################################################
                   2359: sub decode_user_agent {
1.247     albertel 2360:     my ($r)=@_;
1.87      matthew  2361:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2362:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2363:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2364:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2365:     my $clientbrowser='unknown';
                   2366:     my $clientversion='0';
                   2367:     my $clientmathml='';
                   2368:     my $clientunicode='0';
1.1075.2.42  raeburn  2369:     my $clientmobile=0;
1.1075.2.77  raeburn  2370:     my $clientosversion='';
1.87      matthew  2371:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2372:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2373: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2374: 	    $clientbrowser=$bname;
                   2375:             $httpbrowser=~/$vreg/i;
                   2376: 	    $clientversion=$1;
                   2377:             $clientmathml=($clientversion>=$minv);
                   2378:             $clientunicode=($clientversion>=$univ);
                   2379: 	}
                   2380:     }
                   2381:     my $clientos='unknown';
1.1075.2.42  raeburn  2382:     my $clientinfo;
1.87      matthew  2383:     if (($httpbrowser=~/linux/i) ||
                   2384:         ($httpbrowser=~/unix/i) ||
                   2385:         ($httpbrowser=~/ux/i) ||
                   2386:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2387:     if (($httpbrowser=~/vax/i) ||
                   2388:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2389:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2390:     if (($httpbrowser=~/mac/i) ||
                   2391:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2392:     if ($httpbrowser=~/win/i) {
                   2393:         $clientos='win';
                   2394:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2395:             $clientosversion = $1;
                   2396:         }
                   2397:     }
1.87      matthew  2398:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2399:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2400:         $clientmobile=lc($1);
                   2401:     }
                   2402:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2403:         $clientinfo = 'firefox-'.$1;
                   2404:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2405:         $clientinfo = 'chromeframe-'.$1;
                   2406:     }
1.87      matthew  2407:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2408:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2409:             $clientosversion);
1.87      matthew  2410: }
                   2411: 
1.32      matthew  2412: ###############################################################
                   2413: ##    Authentication changing form generation subroutines    ##
                   2414: ###############################################################
                   2415: ##
                   2416: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2417: ## hash, and have reasonable default values.
                   2418: ##
                   2419: ##    formname = the name given in the <form> tag.
1.35      matthew  2420: #-------------------------------------------
                   2421: 
1.45      matthew  2422: =pod
                   2423: 
1.112     bowersj2 2424: =head1 Authentication Routines
                   2425: 
                   2426: =over 4
                   2427: 
1.648     raeburn  2428: =item * &authform_xxxxxx()
1.35      matthew  2429: 
                   2430: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2431: handle some of the conveniences required for authentication forms.  
                   2432: This is not an optimal method, but it works.  
                   2433: 
                   2434: =over 4
                   2435: 
1.112     bowersj2 2436: =item * authform_header
1.35      matthew  2437: 
1.112     bowersj2 2438: =item * authform_authorwarning
1.35      matthew  2439: 
1.112     bowersj2 2440: =item * authform_nochange
1.35      matthew  2441: 
1.112     bowersj2 2442: =item * authform_kerberos
1.35      matthew  2443: 
1.112     bowersj2 2444: =item * authform_internal
1.35      matthew  2445: 
1.112     bowersj2 2446: =item * authform_filesystem
1.35      matthew  2447: 
                   2448: =back
                   2449: 
1.648     raeburn  2450: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2451: 
1.35      matthew  2452: =cut
                   2453: 
                   2454: #-------------------------------------------
1.32      matthew  2455: sub authform_header{  
                   2456:     my %in = (
                   2457:         formname => 'cu',
1.80      albertel 2458:         kerb_def_dom => '',
1.32      matthew  2459:         @_,
                   2460:     );
                   2461:     $in{'formname'} = 'document.' . $in{'formname'};
                   2462:     my $result='';
1.80      albertel 2463: 
                   2464: #---------------------------------------------- Code for upper case translation
                   2465:     my $Javascript_toUpperCase;
                   2466:     unless ($in{kerb_def_dom}) {
                   2467:         $Javascript_toUpperCase =<<"END";
                   2468:         switch (choice) {
                   2469:            case 'krb': currentform.elements[choicearg].value =
                   2470:                currentform.elements[choicearg].value.toUpperCase();
                   2471:                break;
                   2472:            default:
                   2473:         }
                   2474: END
                   2475:     } else {
                   2476:         $Javascript_toUpperCase = "";
                   2477:     }
                   2478: 
1.165     raeburn  2479:     my $radioval = "'nochange'";
1.591     raeburn  2480:     if (defined($in{'curr_authtype'})) {
                   2481:         if ($in{'curr_authtype'} ne '') {
                   2482:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2483:         }
1.174     matthew  2484:     }
1.165     raeburn  2485:     my $argfield = 'null';
1.591     raeburn  2486:     if (defined($in{'mode'})) {
1.165     raeburn  2487:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2488:             if (defined($in{'curr_autharg'})) {
                   2489:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2490:                     $argfield = "'$in{'curr_autharg'}'";
                   2491:                 }
                   2492:             }
                   2493:         }
                   2494:     }
                   2495: 
1.32      matthew  2496:     $result.=<<"END";
                   2497: var current = new Object();
1.165     raeburn  2498: current.radiovalue = $radioval;
                   2499: current.argfield = $argfield;
1.32      matthew  2500: 
                   2501: function changed_radio(choice,currentform) {
                   2502:     var choicearg = choice + 'arg';
                   2503:     // If a radio button in changed, we need to change the argfield
                   2504:     if (current.radiovalue != choice) {
                   2505:         current.radiovalue = choice;
                   2506:         if (current.argfield != null) {
                   2507:             currentform.elements[current.argfield].value = '';
                   2508:         }
                   2509:         if (choice == 'nochange') {
                   2510:             current.argfield = null;
                   2511:         } else {
                   2512:             current.argfield = choicearg;
                   2513:             switch(choice) {
                   2514:                 case 'krb': 
                   2515:                     currentform.elements[current.argfield].value = 
                   2516:                         "$in{'kerb_def_dom'}";
                   2517:                 break;
                   2518:               default:
                   2519:                 break;
                   2520:             }
                   2521:         }
                   2522:     }
                   2523:     return;
                   2524: }
1.22      www      2525: 
1.32      matthew  2526: function changed_text(choice,currentform) {
                   2527:     var choicearg = choice + 'arg';
                   2528:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2529:         $Javascript_toUpperCase
1.32      matthew  2530:         // clear old field
                   2531:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2532:             currentform.elements[current.argfield].value = '';
                   2533:         }
                   2534:         current.argfield = choicearg;
                   2535:     }
                   2536:     set_auth_radio_buttons(choice,currentform);
                   2537:     return;
1.20      www      2538: }
1.32      matthew  2539: 
                   2540: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2541:     var numauthchoices = currentform.login.length;
                   2542:     if (typeof numauthchoices  == "undefined") {
                   2543:         return;
                   2544:     } 
1.32      matthew  2545:     var i=0;
1.986     raeburn  2546:     while (i < numauthchoices) {
1.32      matthew  2547:         if (currentform.login[i].value == newvalue) { break; }
                   2548:         i++;
                   2549:     }
1.986     raeburn  2550:     if (i == numauthchoices) {
1.32      matthew  2551:         return;
                   2552:     }
                   2553:     current.radiovalue = newvalue;
                   2554:     currentform.login[i].checked = true;
                   2555:     return;
                   2556: }
                   2557: END
                   2558:     return $result;
                   2559: }
                   2560: 
1.1075.2.20  raeburn  2561: sub authform_authorwarning {
1.32      matthew  2562:     my $result='';
1.144     matthew  2563:     $result='<i>'.
                   2564:         &mt('As a general rule, only authors or co-authors should be '.
                   2565:             'filesystem authenticated '.
                   2566:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2567:     return $result;
                   2568: }
                   2569: 
1.1075.2.20  raeburn  2570: sub authform_nochange {
1.32      matthew  2571:     my %in = (
                   2572:               formname => 'document.cu',
                   2573:               kerb_def_dom => 'MSU.EDU',
                   2574:               @_,
                   2575:           );
1.1075.2.20  raeburn  2576:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2577:     my $result;
1.1075.2.20  raeburn  2578:     if (!$authnum) {
                   2579:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2580:     } else {
                   2581:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2582:                   '<input type="radio" name="login" value="nochange" '.
                   2583:                   'checked="checked" onclick="'.
1.281     albertel 2584:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2585: 	    '</label>';
1.586     raeburn  2586:     }
1.32      matthew  2587:     return $result;
                   2588: }
                   2589: 
1.591     raeburn  2590: sub authform_kerberos {
1.32      matthew  2591:     my %in = (
                   2592:               formname => 'document.cu',
                   2593:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2594:               kerb_def_auth => 'krb4',
1.32      matthew  2595:               @_,
                   2596:               );
1.586     raeburn  2597:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
                   2598:         $autharg,$jscall);
1.1075.2.20  raeburn  2599:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2600:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2601:        $check5 = ' checked="checked"';
1.80      albertel 2602:     } else {
1.772     bisitz   2603:        $check4 = ' checked="checked"';
1.80      albertel 2604:     }
1.165     raeburn  2605:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2606:     if (defined($in{'curr_authtype'})) {
                   2607:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2608:             $krbcheck = ' checked="checked"';
1.623     raeburn  2609:             if (defined($in{'mode'})) {
                   2610:                 if ($in{'mode'} eq 'modifyuser') {
                   2611:                     $krbcheck = '';
                   2612:                 }
                   2613:             }
1.591     raeburn  2614:             if (defined($in{'curr_kerb_ver'})) {
                   2615:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2616:                     $check5 = ' checked="checked"';
1.591     raeburn  2617:                     $check4 = '';
                   2618:                 } else {
1.772     bisitz   2619:                     $check4 = ' checked="checked"';
1.591     raeburn  2620:                     $check5 = '';
                   2621:                 }
1.586     raeburn  2622:             }
1.591     raeburn  2623:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2624:                 $krbarg = $in{'curr_autharg'};
                   2625:             }
1.586     raeburn  2626:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2627:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2628:                     $result = 
                   2629:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2630:         $in{'curr_autharg'},$krbver);
                   2631:                 } else {
                   2632:                     $result =
                   2633:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2634:                 }
                   2635:                 return $result; 
                   2636:             }
                   2637:         }
                   2638:     } else {
                   2639:         if ($authnum == 1) {
1.784     bisitz   2640:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2641:         }
                   2642:     }
1.586     raeburn  2643:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2644:         return;
1.587     raeburn  2645:     } elsif ($authtype eq '') {
1.591     raeburn  2646:         if (defined($in{'mode'})) {
1.587     raeburn  2647:             if ($in{'mode'} eq 'modifycourse') {
                   2648:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2649:                     $authtype = '<input type="radio" name="login" value="krb" />';
1.587     raeburn  2650:                 }
                   2651:             }
                   2652:         }
1.586     raeburn  2653:     }
                   2654:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2655:     if ($authtype eq '') {
                   2656:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2657:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
                   2658:                     $krbcheck.' />';
                   2659:     }
                   2660:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2661:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2662:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2663:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2664:          $in{'curr_authtype'} eq 'krb4')) {
                   2665:         $result .= &mt
1.144     matthew  2666:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2667:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2668:          '<label>'.$authtype,
1.281     albertel 2669:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2670:              'value="'.$krbarg.'" '.
1.144     matthew  2671:              'onchange="'.$jscall.'" />',
1.281     albertel 2672:          '<label><input type="radio" name="krbver" value="4" '.$check4.' />',
                   2673:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.' />',
                   2674: 	 '</label>');
1.586     raeburn  2675:     } elsif ($can_assign{'krb4'}) {
                   2676:         $result .= &mt
                   2677:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2678:          '[_3] Version 4 [_4]',
                   2679:          '<label>'.$authtype,
                   2680:          '</label><input type="text" size="10" name="krbarg" '.
                   2681:              'value="'.$krbarg.'" '.
                   2682:              'onchange="'.$jscall.'" />',
                   2683:          '<label><input type="hidden" name="krbver" value="4" />',
                   2684:          '</label>');
                   2685:     } elsif ($can_assign{'krb5'}) {
                   2686:         $result .= &mt
                   2687:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2688:          '[_3] Version 5 [_4]',
                   2689:          '<label>'.$authtype,
                   2690:          '</label><input type="text" size="10" name="krbarg" '.
                   2691:              'value="'.$krbarg.'" '.
                   2692:              'onchange="'.$jscall.'" />',
                   2693:          '<label><input type="hidden" name="krbver" value="5" />',
                   2694:          '</label>');
                   2695:     }
1.32      matthew  2696:     return $result;
                   2697: }
                   2698: 
1.1075.2.20  raeburn  2699: sub authform_internal {
1.586     raeburn  2700:     my %in = (
1.32      matthew  2701:                 formname => 'document.cu',
                   2702:                 kerb_def_dom => 'MSU.EDU',
                   2703:                 @_,
                   2704:                 );
1.586     raeburn  2705:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2706:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2707:     if (defined($in{'curr_authtype'})) {
                   2708:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2709:             if ($can_assign{'int'}) {
1.772     bisitz   2710:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2711:                 if (defined($in{'mode'})) {
                   2712:                     if ($in{'mode'} eq 'modifyuser') {
                   2713:                         $intcheck = '';
                   2714:                     }
                   2715:                 }
1.591     raeburn  2716:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2717:                     $intarg = $in{'curr_autharg'};
                   2718:                 }
                   2719:             } else {
                   2720:                 $result = &mt('Currently internally authenticated.');
                   2721:                 return $result;
1.165     raeburn  2722:             }
                   2723:         }
1.586     raeburn  2724:     } else {
                   2725:         if ($authnum == 1) {
1.784     bisitz   2726:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2727:         }
                   2728:     }
                   2729:     if (!$can_assign{'int'}) {
                   2730:         return;
1.587     raeburn  2731:     } elsif ($authtype eq '') {
1.591     raeburn  2732:         if (defined($in{'mode'})) {
1.587     raeburn  2733:             if ($in{'mode'} eq 'modifycourse') {
                   2734:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2735:                     $authtype = '<input type="radio" name="login" value="int" />';
1.587     raeburn  2736:                 }
                   2737:             }
                   2738:         }
1.165     raeburn  2739:     }
1.586     raeburn  2740:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   2741:     if ($authtype eq '') {
                   2742:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
                   2743:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'" />';
                   2744:     }
1.605     bisitz   2745:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.586     raeburn  2746:                $intarg.'" onchange="'.$jscall.'" />';
                   2747:     $result = &mt
1.144     matthew  2748:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  2749:          '<label>'.$authtype,'</label>'.$autharg);
1.824     bisitz   2750:     $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  2751:     return $result;
                   2752: }
                   2753: 
1.1075.2.20  raeburn  2754: sub authform_local {
1.32      matthew  2755:     my %in = (
                   2756:               formname => 'document.cu',
                   2757:               kerb_def_dom => 'MSU.EDU',
                   2758:               @_,
                   2759:               );
1.586     raeburn  2760:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2761:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2762:     if (defined($in{'curr_authtype'})) {
                   2763:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  2764:             if ($can_assign{'loc'}) {
1.772     bisitz   2765:                 $loccheck = 'checked="checked" ';
1.623     raeburn  2766:                 if (defined($in{'mode'})) {
                   2767:                     if ($in{'mode'} eq 'modifyuser') {
                   2768:                         $loccheck = '';
                   2769:                     }
                   2770:                 }
1.591     raeburn  2771:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2772:                     $locarg = $in{'curr_autharg'};
                   2773:                 }
                   2774:             } else {
                   2775:                 $result = &mt('Currently using local (institutional) authentication.');
                   2776:                 return $result;
1.165     raeburn  2777:             }
                   2778:         }
1.586     raeburn  2779:     } else {
                   2780:         if ($authnum == 1) {
1.784     bisitz   2781:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  2782:         }
                   2783:     }
                   2784:     if (!$can_assign{'loc'}) {
                   2785:         return;
1.587     raeburn  2786:     } elsif ($authtype eq '') {
1.591     raeburn  2787:         if (defined($in{'mode'})) {
1.587     raeburn  2788:             if ($in{'mode'} eq 'modifycourse') {
                   2789:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2790:                     $authtype = '<input type="radio" name="login" value="loc" />';
1.587     raeburn  2791:                 }
                   2792:             }
                   2793:         }
1.165     raeburn  2794:     }
1.586     raeburn  2795:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   2796:     if ($authtype eq '') {
                   2797:         $authtype = '<input type="radio" name="login" value="loc" '.
                   2798:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
                   2799:                     $jscall.'" />';
                   2800:     }
                   2801:     $autharg = '<input type="text" size="10" name="locarg" value="'.
                   2802:                $locarg.'" onchange="'.$jscall.'" />';
                   2803:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   2804:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  2805:     return $result;
                   2806: }
                   2807: 
1.1075.2.20  raeburn  2808: sub authform_filesystem {
1.32      matthew  2809:     my %in = (
                   2810:               formname => 'document.cu',
                   2811:               kerb_def_dom => 'MSU.EDU',
                   2812:               @_,
                   2813:               );
1.586     raeburn  2814:     my ($fsyscheck,$result,$authtype,$autharg,$jscall);
1.1075.2.20  raeburn  2815:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.591     raeburn  2816:     if (defined($in{'curr_authtype'})) {
                   2817:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  2818:             if ($can_assign{'fsys'}) {
1.772     bisitz   2819:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  2820:                 if (defined($in{'mode'})) {
                   2821:                     if ($in{'mode'} eq 'modifyuser') {
                   2822:                         $fsyscheck = '';
                   2823:                     }
                   2824:                 }
1.586     raeburn  2825:             } else {
                   2826:                 $result = &mt('Currently Filesystem Authenticated.');
                   2827:                 return $result;
                   2828:             }           
                   2829:         }
                   2830:     } else {
                   2831:         if ($authnum == 1) {
1.784     bisitz   2832:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  2833:         }
                   2834:     }
                   2835:     if (!$can_assign{'fsys'}) {
                   2836:         return;
1.587     raeburn  2837:     } elsif ($authtype eq '') {
1.591     raeburn  2838:         if (defined($in{'mode'})) {
1.587     raeburn  2839:             if ($in{'mode'} eq 'modifycourse') {
                   2840:                 if ($authnum == 1) {
1.1075.2.20  raeburn  2841:                     $authtype = '<input type="radio" name="login" value="fsys" />';
1.587     raeburn  2842:                 }
                   2843:             }
                   2844:         }
1.586     raeburn  2845:     }
                   2846:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   2847:     if ($authtype eq '') {
                   2848:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   2849:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
                   2850:                     $jscall.'" />';
                   2851:     }
                   2852:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
                   2853:                ' onchange="'.$jscall.'" />';
                   2854:     $result = &mt
1.144     matthew  2855:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 2856:          '<label><input type="radio" name="login" value="fsys" '.
1.586     raeburn  2857:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'" />',
1.605     bisitz   2858:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.144     matthew  2859:                   'onchange="'.$jscall.'" />');
1.32      matthew  2860:     return $result;
                   2861: }
                   2862: 
1.586     raeburn  2863: sub get_assignable_auth {
                   2864:     my ($dom) = @_;
                   2865:     if ($dom eq '') {
                   2866:         $dom = $env{'request.role.domain'};
                   2867:     }
                   2868:     my %can_assign = (
                   2869:                           krb4 => 1,
                   2870:                           krb5 => 1,
                   2871:                           int  => 1,
                   2872:                           loc  => 1,
                   2873:                      );
                   2874:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   2875:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   2876:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   2877:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   2878:             my $context;
                   2879:             if ($env{'request.role'} =~ /^au/) {
                   2880:                 $context = 'author';
                   2881:             } elsif ($env{'request.role'} =~ /^dc/) {
                   2882:                 $context = 'domain';
                   2883:             } elsif ($env{'request.course.id'}) {
                   2884:                 $context = 'course';
                   2885:             }
                   2886:             if ($context) {
                   2887:                 if (ref($authhash->{$context}) eq 'HASH') {
                   2888:                    %can_assign = %{$authhash->{$context}}; 
                   2889:                 }
                   2890:             }
                   2891:         }
                   2892:     }
                   2893:     my $authnum = 0;
                   2894:     foreach my $key (keys(%can_assign)) {
                   2895:         if ($can_assign{$key}) {
                   2896:             $authnum ++;
                   2897:         }
                   2898:     }
                   2899:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   2900:         $authnum --;
                   2901:     }
                   2902:     return ($authnum,%can_assign);
                   2903: }
                   2904: 
1.80      albertel 2905: ###############################################################
                   2906: ##    Get Kerberos Defaults for Domain                 ##
                   2907: ###############################################################
                   2908: ##
                   2909: ## Returns default kerberos version and an associated argument
                   2910: ## as listed in file domain.tab. If not listed, provides
                   2911: ## appropriate default domain and kerberos version.
                   2912: ##
                   2913: #-------------------------------------------
                   2914: 
                   2915: =pod
                   2916: 
1.648     raeburn  2917: =item * &get_kerberos_defaults()
1.80      albertel 2918: 
                   2919: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  2920: version and domain. If not found, it defaults to version 4 and the 
                   2921: domain of the server.
1.80      albertel 2922: 
1.648     raeburn  2923: =over 4
                   2924: 
1.80      albertel 2925: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   2926: 
1.648     raeburn  2927: =back
                   2928: 
                   2929: =back
                   2930: 
1.80      albertel 2931: =cut
                   2932: 
                   2933: #-------------------------------------------
                   2934: sub get_kerberos_defaults {
                   2935:     my $domain=shift;
1.641     raeburn  2936:     my ($krbdef,$krbdefdom);
                   2937:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   2938:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   2939:         $krbdef = $domdefaults{'auth_def'};
                   2940:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   2941:     } else {
1.80      albertel 2942:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   2943:         my $krbdefdom=$1;
                   2944:         $krbdefdom=~tr/a-z/A-Z/;
                   2945:         $krbdef = "krb4";
                   2946:     }
                   2947:     return ($krbdef,$krbdefdom);
                   2948: }
1.112     bowersj2 2949: 
1.32      matthew  2950: 
1.46      matthew  2951: ###############################################################
                   2952: ##                Thesaurus Functions                        ##
                   2953: ###############################################################
1.20      www      2954: 
1.46      matthew  2955: =pod
1.20      www      2956: 
1.112     bowersj2 2957: =head1 Thesaurus Functions
                   2958: 
                   2959: =over 4
                   2960: 
1.648     raeburn  2961: =item * &initialize_keywords()
1.46      matthew  2962: 
                   2963: Initializes the package variable %Keywords if it is empty.  Uses the
                   2964: package variable $thesaurus_db_file.
                   2965: 
                   2966: =cut
                   2967: 
                   2968: ###################################################
                   2969: 
                   2970: sub initialize_keywords {
                   2971:     return 1 if (scalar keys(%Keywords));
                   2972:     # If we are here, %Keywords is empty, so fill it up
                   2973:     #   Make sure the file we need exists...
                   2974:     if (! -e $thesaurus_db_file) {
                   2975:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   2976:                                  " failed because it does not exist");
                   2977:         return 0;
                   2978:     }
                   2979:     #   Set up the hash as a database
                   2980:     my %thesaurus_db;
                   2981:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 2982:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  2983:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   2984:                                  $thesaurus_db_file);
                   2985:         return 0;
                   2986:     } 
                   2987:     #  Get the average number of appearances of a word.
                   2988:     my $avecount = $thesaurus_db{'average.count'};
                   2989:     #  Put keywords (those that appear > average) into %Keywords
                   2990:     while (my ($word,$data)=each (%thesaurus_db)) {
                   2991:         my ($count,undef) = split /:/,$data;
                   2992:         $Keywords{$word}++ if ($count > $avecount);
                   2993:     }
                   2994:     untie %thesaurus_db;
                   2995:     # Remove special values from %Keywords.
1.356     albertel 2996:     foreach my $value ('total.count','average.count') {
                   2997:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  2998:   }
1.46      matthew  2999:     return 1;
                   3000: }
                   3001: 
                   3002: ###################################################
                   3003: 
                   3004: =pod
                   3005: 
1.648     raeburn  3006: =item * &keyword($word)
1.46      matthew  3007: 
                   3008: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3009: than the average number of times in the thesaurus database.  Calls 
                   3010: &initialize_keywords
                   3011: 
                   3012: =cut
                   3013: 
                   3014: ###################################################
1.20      www      3015: 
                   3016: sub keyword {
1.46      matthew  3017:     return if (!&initialize_keywords());
                   3018:     my $word=lc(shift());
                   3019:     $word=~s/\W//g;
                   3020:     return exists($Keywords{$word});
1.20      www      3021: }
1.46      matthew  3022: 
                   3023: ###############################################################
                   3024: 
                   3025: =pod 
1.20      www      3026: 
1.648     raeburn  3027: =item * &get_related_words()
1.46      matthew  3028: 
1.160     matthew  3029: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3030: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3031: will be returned.  The order of the words returned is determined by the
                   3032: database which holds them.
                   3033: 
                   3034: Uses global $thesaurus_db_file.
                   3035: 
1.1057    foxr     3036: 
1.46      matthew  3037: =cut
                   3038: 
                   3039: ###############################################################
                   3040: sub get_related_words {
                   3041:     my $keyword = shift;
                   3042:     my %thesaurus_db;
                   3043:     if (! -e $thesaurus_db_file) {
                   3044:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3045:                                  "failed because the file does not exist");
                   3046:         return ();
                   3047:     }
                   3048:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3049:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3050:         return ();
                   3051:     } 
                   3052:     my @Words=();
1.429     www      3053:     my $count=0;
1.46      matthew  3054:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3055: 	# The first element is the number of times
                   3056: 	# the word appears.  We do not need it now.
1.429     www      3057: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3058: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3059: 	my $threshold=$mostfrequentcount/10;
                   3060:         foreach my $possibleword (@RelatedWords) {
                   3061:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3062:             if ($wordcount>$threshold) {
                   3063: 		push(@Words,$word);
                   3064:                 $count++;
                   3065:                 if ($count>10) { last; }
                   3066: 	    }
1.20      www      3067:         }
                   3068:     }
1.46      matthew  3069:     untie %thesaurus_db;
                   3070:     return @Words;
1.14      harris41 3071: }
1.46      matthew  3072: 
1.112     bowersj2 3073: =pod
                   3074: 
                   3075: =back
                   3076: 
                   3077: =cut
1.61      www      3078: 
                   3079: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3080: =pod
                   3081: 
1.112     bowersj2 3082: =head1 User Name Functions
                   3083: 
                   3084: =over 4
                   3085: 
1.648     raeburn  3086: =item * &plainname($uname,$udom,$first)
1.81      albertel 3087: 
1.112     bowersj2 3088: Takes a users logon name and returns it as a string in
1.226     albertel 3089: "first middle last generation" form 
                   3090: if $first is set to 'lastname' then it returns it as
                   3091: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3092: 
                   3093: =cut
1.61      www      3094: 
1.295     www      3095: 
1.81      albertel 3096: ###############################################################
1.61      www      3097: sub plainname {
1.226     albertel 3098:     my ($uname,$udom,$first)=@_;
1.537     albertel 3099:     return if (!defined($uname) || !defined($udom));
1.295     www      3100:     my %names=&getnames($uname,$udom);
1.226     albertel 3101:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3102: 					  $names{'middlename'},
                   3103: 					  $names{'lastname'},
                   3104: 					  $names{'generation'},$first);
                   3105:     $name=~s/^\s+//;
1.62      www      3106:     $name=~s/\s+$//;
                   3107:     $name=~s/\s+/ /g;
1.353     albertel 3108:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3109:     return $name;
1.61      www      3110: }
1.66      www      3111: 
                   3112: # -------------------------------------------------------------------- Nickname
1.81      albertel 3113: =pod
                   3114: 
1.648     raeburn  3115: =item * &nickname($uname,$udom)
1.81      albertel 3116: 
                   3117: Gets a users name and returns it as a string as
                   3118: 
                   3119: "&quot;nickname&quot;"
1.66      www      3120: 
1.81      albertel 3121: if the user has a nickname or
                   3122: 
                   3123: "first middle last generation"
                   3124: 
                   3125: if the user does not
                   3126: 
                   3127: =cut
1.66      www      3128: 
                   3129: sub nickname {
                   3130:     my ($uname,$udom)=@_;
1.537     albertel 3131:     return if (!defined($uname) || !defined($udom));
1.295     www      3132:     my %names=&getnames($uname,$udom);
1.68      albertel 3133:     my $name=$names{'nickname'};
1.66      www      3134:     if ($name) {
                   3135:        $name='&quot;'.$name.'&quot;'; 
                   3136:     } else {
                   3137:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3138: 	     $names{'lastname'}.' '.$names{'generation'};
                   3139:        $name=~s/\s+$//;
                   3140:        $name=~s/\s+/ /g;
                   3141:     }
                   3142:     return $name;
                   3143: }
                   3144: 
1.295     www      3145: sub getnames {
                   3146:     my ($uname,$udom)=@_;
1.537     albertel 3147:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3148:     if ($udom eq 'public' && $uname eq 'public') {
                   3149: 	return ('lastname' => &mt('Public'));
                   3150:     }
1.295     www      3151:     my $id=$uname.':'.$udom;
                   3152:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3153:     if ($cached) {
                   3154: 	return %{$names};
                   3155:     } else {
                   3156: 	my %loadnames=&Apache::lonnet::get('environment',
                   3157:                     ['firstname','middlename','lastname','generation','nickname'],
                   3158: 					 $udom,$uname);
                   3159: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3160: 	return %loadnames;
                   3161:     }
                   3162: }
1.61      www      3163: 
1.542     raeburn  3164: # -------------------------------------------------------------------- getemails
1.648     raeburn  3165: 
1.542     raeburn  3166: =pod
                   3167: 
1.648     raeburn  3168: =item * &getemails($uname,$udom)
1.542     raeburn  3169: 
                   3170: Gets a user's email information and returns it as a hash with keys:
                   3171: notification, critnotification, permanentemail
                   3172: 
                   3173: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3174: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3175:  
1.648     raeburn  3176: 
1.542     raeburn  3177: =cut
                   3178: 
1.648     raeburn  3179: 
1.466     albertel 3180: sub getemails {
                   3181:     my ($uname,$udom)=@_;
                   3182:     if ($udom eq 'public' && $uname eq 'public') {
                   3183: 	return;
                   3184:     }
1.467     www      3185:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3186:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3187:     my $id=$uname.':'.$udom;
                   3188:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3189:     if ($cached) {
                   3190: 	return %{$names};
                   3191:     } else {
                   3192: 	my %loadnames=&Apache::lonnet::get('environment',
                   3193:                     			   ['notification','critnotification',
                   3194: 					    'permanentemail'],
                   3195: 					   $udom,$uname);
                   3196: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3197: 	return %loadnames;
                   3198:     }
                   3199: }
                   3200: 
1.551     albertel 3201: sub flush_email_cache {
                   3202:     my ($uname,$udom)=@_;
                   3203:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3204:     if (!$uname) { $uname=$env{'user.name'};   }
                   3205:     return if ($udom eq 'public' && $uname eq 'public');
                   3206:     my $id=$uname.':'.$udom;
                   3207:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3208: }
                   3209: 
1.728     raeburn  3210: # -------------------------------------------------------------------- getlangs
                   3211: 
                   3212: =pod
                   3213: 
                   3214: =item * &getlangs($uname,$udom)
                   3215: 
                   3216: Gets a user's language preference and returns it as a hash with key:
                   3217: language.
                   3218: 
                   3219: =cut
                   3220: 
                   3221: 
                   3222: sub getlangs {
                   3223:     my ($uname,$udom) = @_;
                   3224:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3225:     if (!$uname) { $uname=$env{'user.name'};   }
                   3226:     my $id=$uname.':'.$udom;
                   3227:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3228:     if ($cached) {
                   3229:         return %{$langs};
                   3230:     } else {
                   3231:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3232:                                            $udom,$uname);
                   3233:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3234:         return %loadlangs;
                   3235:     }
                   3236: }
                   3237: 
                   3238: sub flush_langs_cache {
                   3239:     my ($uname,$udom)=@_;
                   3240:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3241:     if (!$uname) { $uname=$env{'user.name'};   }
                   3242:     return if ($udom eq 'public' && $uname eq 'public');
                   3243:     my $id=$uname.':'.$udom;
                   3244:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3245: }
                   3246: 
1.61      www      3247: # ------------------------------------------------------------------ Screenname
1.81      albertel 3248: 
                   3249: =pod
                   3250: 
1.648     raeburn  3251: =item * &screenname($uname,$udom)
1.81      albertel 3252: 
                   3253: Gets a users screenname and returns it as a string
                   3254: 
                   3255: =cut
1.61      www      3256: 
                   3257: sub screenname {
                   3258:     my ($uname,$udom)=@_;
1.258     albertel 3259:     if ($uname eq $env{'user.name'} &&
                   3260: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3261:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3262:     return $names{'screenname'};
1.62      www      3263: }
                   3264: 
1.212     albertel 3265: 
1.802     bisitz   3266: # ------------------------------------------------------------- Confirm Wrapper
                   3267: =pod
                   3268: 
1.1075.2.42  raeburn  3269: =item * &confirmwrapper($message)
1.802     bisitz   3270: 
                   3271: Wrap messages about completion of operation in box
                   3272: 
                   3273: =cut
                   3274: 
                   3275: sub confirmwrapper {
                   3276:     my ($message)=@_;
                   3277:     if ($message) {
                   3278:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3279:                .$message."\n"
                   3280:                .'</div>'."\n";
                   3281:     } else {
                   3282:         return $message;
                   3283:     }
                   3284: }
                   3285: 
1.62      www      3286: # ------------------------------------------------------------- Message Wrapper
                   3287: 
                   3288: sub messagewrapper {
1.369     www      3289:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3290:     return 
1.441     albertel 3291:         '<a href="/adm/email?compose=individual&amp;'.
                   3292:         'recname='.$username.'&amp;recdom='.$domain.
                   3293: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3294:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3295: }
1.802     bisitz   3296: 
1.74      www      3297: # --------------------------------------------------------------- Notes Wrapper
                   3298: 
                   3299: sub noteswrapper {
                   3300:     my ($link,$un,$do)=@_;
                   3301:     return 
1.896     amueller 3302: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3303: }
1.802     bisitz   3304: 
1.62      www      3305: # ------------------------------------------------------------- Aboutme Wrapper
                   3306: 
                   3307: sub aboutmewrapper {
1.1070    raeburn  3308:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3309:     if (!defined($username)  && !defined($domain)) {
                   3310:         return;
                   3311:     }
1.1075.2.15  raeburn  3312:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3313: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3314: }
                   3315: 
                   3316: # ------------------------------------------------------------ Syllabus Wrapper
                   3317: 
                   3318: sub syllabuswrapper {
1.707     bisitz   3319:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3320:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3321: }
1.14      harris41 3322: 
1.802     bisitz   3323: # -----------------------------------------------------------------------------
                   3324: 
1.208     matthew  3325: sub track_student_link {
1.887     raeburn  3326:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3327:     my $link ="/adm/trackstudent?";
1.208     matthew  3328:     my $title = 'View recent activity';
                   3329:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3330:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3331:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3332:         $title .= ' of this student';
1.268     albertel 3333:     } 
1.208     matthew  3334:     if (defined($target) && $target !~ /^\s*$/) {
                   3335:         $target = qq{target="$target"};
                   3336:     } else {
                   3337:         $target = '';
                   3338:     }
1.268     albertel 3339:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3340:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3341:     $title = &mt($title);
                   3342:     $linktext = &mt($linktext);
1.448     albertel 3343:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3344: 	&help_open_topic('View_recent_activity');
1.208     matthew  3345: }
                   3346: 
1.781     raeburn  3347: sub slot_reservations_link {
                   3348:     my ($linktext,$sname,$sdom,$target) = @_;
                   3349:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3350:     my $title = 'View slot reservation history';
                   3351:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3352:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3353:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3354:         $title .= ' of this student';
                   3355:     }
                   3356:     if (defined($target) && $target !~ /^\s*$/) {
                   3357:         $target = qq{target="$target"};
                   3358:     } else {
                   3359:         $target = '';
                   3360:     }
                   3361:     $title = &mt($title);
                   3362:     $linktext = &mt($linktext);
                   3363:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3364: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3365: 
                   3366: }
                   3367: 
1.508     www      3368: # ===================================================== Display a student photo
                   3369: 
                   3370: 
1.509     albertel 3371: sub student_image_tag {
1.508     www      3372:     my ($domain,$user)=@_;
                   3373:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3374:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3375: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3376:     } else {
                   3377: 	return '';
                   3378:     }
                   3379: }
                   3380: 
1.112     bowersj2 3381: =pod
                   3382: 
                   3383: =back
                   3384: 
                   3385: =head1 Access .tab File Data
                   3386: 
                   3387: =over 4
                   3388: 
1.648     raeburn  3389: =item * &languageids() 
1.112     bowersj2 3390: 
                   3391: returns list of all language ids
                   3392: 
                   3393: =cut
                   3394: 
1.14      harris41 3395: sub languageids {
1.16      harris41 3396:     return sort(keys(%language));
1.14      harris41 3397: }
                   3398: 
1.112     bowersj2 3399: =pod
                   3400: 
1.648     raeburn  3401: =item * &languagedescription() 
1.112     bowersj2 3402: 
                   3403: returns description of a specified language id
                   3404: 
                   3405: =cut
                   3406: 
1.14      harris41 3407: sub languagedescription {
1.125     www      3408:     my $code=shift;
                   3409:     return  ($supported_language{$code}?'* ':'').
                   3410:             $language{$code}.
1.126     www      3411: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3412: }
                   3413: 
1.1048    foxr     3414: =pod
                   3415: 
                   3416: =item * &plainlanguagedescription
                   3417: 
                   3418: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3419: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3420: 
                   3421: =cut
                   3422: 
1.145     www      3423: sub plainlanguagedescription {
                   3424:     my $code=shift;
                   3425:     return $language{$code};
                   3426: }
                   3427: 
1.1048    foxr     3428: =pod
                   3429: 
                   3430: =item * &supportedlanguagecode
                   3431: 
                   3432: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3433: code.
                   3434: 
                   3435: =cut
                   3436: 
1.145     www      3437: sub supportedlanguagecode {
                   3438:     my $code=shift;
                   3439:     return $supported_language{$code};
1.97      www      3440: }
                   3441: 
1.112     bowersj2 3442: =pod
                   3443: 
1.1048    foxr     3444: =item * &latexlanguage()
                   3445: 
                   3446: Given a language key code returns the correspondnig language to use
                   3447: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3448: is no supported hyphenation for the language code.
                   3449: 
                   3450: =cut
                   3451: 
                   3452: sub latexlanguage {
                   3453:     my $code = shift;
                   3454:     return $latex_language{$code};
                   3455: }
                   3456: 
                   3457: =pod
                   3458: 
                   3459: =item * &latexhyphenation()
                   3460: 
                   3461: Same as above but what's supplied is the language as it might be stored
                   3462: in the metadata.
                   3463: 
                   3464: =cut
                   3465: 
                   3466: sub latexhyphenation {
                   3467:     my $key = shift;
                   3468:     return $latex_language_bykey{$key};
                   3469: }
                   3470: 
                   3471: =pod
                   3472: 
1.648     raeburn  3473: =item * &copyrightids() 
1.112     bowersj2 3474: 
                   3475: returns list of all copyrights
                   3476: 
                   3477: =cut
                   3478: 
                   3479: sub copyrightids {
                   3480:     return sort(keys(%cprtag));
                   3481: }
                   3482: 
                   3483: =pod
                   3484: 
1.648     raeburn  3485: =item * &copyrightdescription() 
1.112     bowersj2 3486: 
                   3487: returns description of a specified copyright id
                   3488: 
                   3489: =cut
                   3490: 
                   3491: sub copyrightdescription {
1.166     www      3492:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3493: }
1.197     matthew  3494: 
                   3495: =pod
                   3496: 
1.648     raeburn  3497: =item * &source_copyrightids() 
1.192     taceyjo1 3498: 
                   3499: returns list of all source copyrights
                   3500: 
                   3501: =cut
                   3502: 
                   3503: sub source_copyrightids {
                   3504:     return sort(keys(%scprtag));
                   3505: }
                   3506: 
                   3507: =pod
                   3508: 
1.648     raeburn  3509: =item * &source_copyrightdescription() 
1.192     taceyjo1 3510: 
                   3511: returns description of a specified source copyright id
                   3512: 
                   3513: =cut
                   3514: 
                   3515: sub source_copyrightdescription {
                   3516:     return &mt($scprtag{shift(@_)});
                   3517: }
1.112     bowersj2 3518: 
                   3519: =pod
                   3520: 
1.648     raeburn  3521: =item * &filecategories() 
1.112     bowersj2 3522: 
                   3523: returns list of all file categories
                   3524: 
                   3525: =cut
                   3526: 
                   3527: sub filecategories {
                   3528:     return sort(keys(%category_extensions));
                   3529: }
                   3530: 
                   3531: =pod
                   3532: 
1.648     raeburn  3533: =item * &filecategorytypes() 
1.112     bowersj2 3534: 
                   3535: returns list of file types belonging to a given file
                   3536: category
                   3537: 
                   3538: =cut
                   3539: 
                   3540: sub filecategorytypes {
1.356     albertel 3541:     my ($cat) = @_;
                   3542:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3543: }
                   3544: 
                   3545: =pod
                   3546: 
1.648     raeburn  3547: =item * &fileembstyle() 
1.112     bowersj2 3548: 
                   3549: returns embedding style for a specified file type
                   3550: 
                   3551: =cut
                   3552: 
                   3553: sub fileembstyle {
                   3554:     return $fe{lc(shift(@_))};
1.169     www      3555: }
                   3556: 
1.351     www      3557: sub filemimetype {
                   3558:     return $fm{lc(shift(@_))};
                   3559: }
                   3560: 
1.169     www      3561: 
                   3562: sub filecategoryselect {
                   3563:     my ($name,$value)=@_;
1.189     matthew  3564:     return &select_form($value,$name,
1.970     raeburn  3565:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3566: }
                   3567: 
                   3568: =pod
                   3569: 
1.648     raeburn  3570: =item * &filedescription() 
1.112     bowersj2 3571: 
                   3572: returns description for a specified file type
                   3573: 
                   3574: =cut
                   3575: 
                   3576: sub filedescription {
1.188     matthew  3577:     my $file_description = $fd{lc(shift())};
                   3578:     $file_description =~ s:([\[\]]):~$1:g;
                   3579:     return &mt($file_description);
1.112     bowersj2 3580: }
                   3581: 
                   3582: =pod
                   3583: 
1.648     raeburn  3584: =item * &filedescriptionex() 
1.112     bowersj2 3585: 
                   3586: returns description for a specified file type with
                   3587: extra formatting
                   3588: 
                   3589: =cut
                   3590: 
                   3591: sub filedescriptionex {
                   3592:     my $ex=shift;
1.188     matthew  3593:     my $file_description = $fd{lc($ex)};
                   3594:     $file_description =~ s:([\[\]]):~$1:g;
                   3595:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3596: }
                   3597: 
                   3598: # End of .tab access
                   3599: =pod
                   3600: 
                   3601: =back
                   3602: 
                   3603: =cut
                   3604: 
                   3605: # ------------------------------------------------------------------ File Types
                   3606: sub fileextensions {
                   3607:     return sort(keys(%fe));
                   3608: }
                   3609: 
1.97      www      3610: # ----------------------------------------------------------- Display Languages
                   3611: # returns a hash with all desired display languages
                   3612: #
                   3613: 
                   3614: sub display_languages {
                   3615:     my %languages=();
1.695     raeburn  3616:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3617: 	$languages{$lang}=1;
1.97      www      3618:     }
                   3619:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3620:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3621: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3622: 	    $languages{$lang}=1;
1.97      www      3623:         }
                   3624:     }
                   3625:     return %languages;
1.14      harris41 3626: }
                   3627: 
1.582     albertel 3628: sub languages {
                   3629:     my ($possible_langs) = @_;
1.695     raeburn  3630:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3631:     if (!ref($possible_langs)) {
                   3632: 	if( wantarray ) {
                   3633: 	    return @preferred_langs;
                   3634: 	} else {
                   3635: 	    return $preferred_langs[0];
                   3636: 	}
                   3637:     }
                   3638:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3639:     my @preferred_possibilities;
                   3640:     foreach my $preferred_lang (@preferred_langs) {
                   3641: 	if (exists($possibilities{$preferred_lang})) {
                   3642: 	    push(@preferred_possibilities, $preferred_lang);
                   3643: 	}
                   3644:     }
                   3645:     if( wantarray ) {
                   3646: 	return @preferred_possibilities;
                   3647:     }
                   3648:     return $preferred_possibilities[0];
                   3649: }
                   3650: 
1.742     raeburn  3651: sub user_lang {
                   3652:     my ($touname,$toudom,$fromcid) = @_;
                   3653:     my @userlangs;
                   3654:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3655:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3656:                     $env{'course.'.$fromcid.'.languages'}));
                   3657:     } else {
                   3658:         my %langhash = &getlangs($touname,$toudom);
                   3659:         if ($langhash{'languages'} ne '') {
                   3660:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3661:         } else {
                   3662:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3663:             if ($domdefs{'lang_def'} ne '') {
                   3664:                 @userlangs = ($domdefs{'lang_def'});
                   3665:             }
                   3666:         }
                   3667:     }
                   3668:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3669:     my $user_lh = Apache::localize->get_handle(@languages);
                   3670:     return $user_lh;
                   3671: }
                   3672: 
                   3673: 
1.112     bowersj2 3674: ###############################################################
                   3675: ##               Student Answer Attempts                     ##
                   3676: ###############################################################
                   3677: 
                   3678: =pod
                   3679: 
                   3680: =head1 Alternate Problem Views
                   3681: 
                   3682: =over 4
                   3683: 
1.648     raeburn  3684: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3685:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3686: 
                   3687: Return string with previous attempt on problem. Arguments:
                   3688: 
                   3689: =over 4
                   3690: 
                   3691: =item * $symb: Problem, including path
                   3692: 
                   3693: =item * $username: username of the desired student
                   3694: 
                   3695: =item * $domain: domain of the desired student
1.14      harris41 3696: 
1.112     bowersj2 3697: =item * $course: Course ID
1.14      harris41 3698: 
1.112     bowersj2 3699: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3700:     something
1.14      harris41 3701: 
1.112     bowersj2 3702: =item * $regexp: if string matches this regexp, the string will be
                   3703:     sent to $gradesub
1.14      harris41 3704: 
1.112     bowersj2 3705: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3706: 
1.1075.2.86  raeburn  3707: =item * $usec: section of the desired student
                   3708: 
                   3709: =item * $identifier: counter for student (multiple students one problem) or
                   3710:     problem (one student; whole sequence).
                   3711: 
1.112     bowersj2 3712: =back
1.14      harris41 3713: 
1.112     bowersj2 3714: The output string is a table containing all desired attempts, if any.
1.16      harris41 3715: 
1.112     bowersj2 3716: =cut
1.1       albertel 3717: 
                   3718: sub get_previous_attempt {
1.1075.2.86  raeburn  3719:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3720:   my $prevattempts='';
1.43      ng       3721:   no strict 'refs';
1.1       albertel 3722:   if ($symb) {
1.3       albertel 3723:     my (%returnhash)=
                   3724:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3725:     if ($returnhash{'version'}) {
                   3726:       my %lasthash=();
                   3727:       my $version;
                   3728:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3729:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3730:             if ($key =~ /\.rawrndseed$/) {
                   3731:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   3732:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   3733:             } else {
                   3734:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   3735:             }
1.19      harris41 3736:         }
1.1       albertel 3737:       }
1.596     albertel 3738:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   3739:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  3740:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  3741:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 3742:       foreach my $key (sort(keys(%lasthash))) {
                   3743: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       3744: 	if ($#parts > 0) {
1.31      albertel 3745: 	  my $data=$parts[-1];
1.989     raeburn  3746:           next if ($data eq 'foilorder');
1.31      albertel 3747: 	  pop(@parts);
1.1010    www      3748:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  3749:           if ($data eq 'type') {
                   3750:               unless ($showsurv) {
                   3751:                   my $id = join(',',@parts);
                   3752:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  3753:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   3754:                       $lasthidden{$ign.'.'.$id} = 1;
                   3755:                   }
1.945     raeburn  3756:               }
1.1075.2.86  raeburn  3757:               if ($identifier ne '') {
                   3758:                   my $id = join(',',@parts);
                   3759:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   3760:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   3761:                       $hidestatus{$ign.'.'.$id} = 1;
                   3762:                   }
                   3763:               }
                   3764:           } elsif ($data eq 'regrader') {
                   3765:               if (($identifier ne '') && (@parts)) {
                   3766:                   my $id = join(',',@parts);
                   3767:                   $regraded{$ign.'.'.$id} = 1;
                   3768:               }
1.1010    www      3769:           } 
1.31      albertel 3770: 	} else {
1.41      ng       3771: 	  if ($#parts == 0) {
                   3772: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   3773: 	  } else {
                   3774: 	    $prevattempts.='<th>'.$ign.'</th>';
                   3775: 	  }
1.31      albertel 3776: 	}
1.16      harris41 3777:       }
1.596     albertel 3778:       $prevattempts.=&end_data_table_header_row();
1.40      ng       3779:       if ($getattempt eq '') {
1.1075.2.86  raeburn  3780:         my (%solved,%resets,%probstatus);
                   3781:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   3782:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   3783:                 foreach my $id (keys(%regraded)) {
                   3784:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   3785:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   3786:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   3787:                         push(@{$resets{$id}},$version);
                   3788:                     }
                   3789:                 }
                   3790:             }
                   3791:         }
1.40      ng       3792: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  3793:             my (@hidden,@unsolved);
1.945     raeburn  3794:             if (%typeparts) {
                   3795:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  3796:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   3797:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  3798:                         push(@hidden,$id);
1.1075.2.86  raeburn  3799:                     } elsif ($identifier ne '') {
                   3800:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   3801:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   3802:                                 ($hidestatus{$id})) {
                   3803:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   3804:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   3805:                                 push(@{$solved{$id}},$version);
                   3806:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   3807:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   3808:                                 my $skip;
                   3809:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   3810:                                     foreach my $reset (@{$resets{$id}}) {
                   3811:                                         if ($reset > $solved{$id}[-1]) {
                   3812:                                             $skip=1;
                   3813:                                             last;
                   3814:                                         }
                   3815:                                     }
                   3816:                                 }
                   3817:                                 unless ($skip) {
                   3818:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   3819:                                     push(@unsolved,$partslist);
                   3820:                                 }
                   3821:                             }
                   3822:                         }
1.945     raeburn  3823:                     }
                   3824:                 }
                   3825:             }
                   3826:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  3827:                            '<td>'.&mt('Transaction [_1]',$version);
                   3828:             if (@unsolved) {
                   3829:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   3830:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   3831:                                  &mt('Hide').'</label></span>';
                   3832:             }
                   3833:             $prevattempts .= '</td>';
1.945     raeburn  3834:             if (@hidden) {
                   3835:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3836:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  3837:                     my $hide;
                   3838:                     foreach my $id (@hidden) {
                   3839:                         if ($key =~ /^\Q$id\E/) {
                   3840:                             $hide = 1;
                   3841:                             last;
                   3842:                         }
                   3843:                     }
                   3844:                     if ($hide) {
                   3845:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3846:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3847:                             my $value = &format_previous_attempt_value($key,
                   3848:                                              $returnhash{$version.':'.$key});
                   3849:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3850:                         } else {
                   3851:                             $prevattempts.='<td>&nbsp;</td>';
                   3852:                         }
                   3853:                     } else {
                   3854:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  3855:                             my $value = $returnhash{$version.':'.$key};
                   3856:                             if ($key =~ /\.rndseed$/) {
                   3857:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   3858:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   3859:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   3860:                                 }
                   3861:                             }
                   3862:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   3863:                                            '&nbsp;</td>';
1.945     raeburn  3864:                         } else {
                   3865:                             $prevattempts.='<td>&nbsp;</td>';
                   3866:                         }
                   3867:                     }
                   3868:                 }
                   3869:             } else {
                   3870: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3871:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  3872:                     my $value = $returnhash{$version.':'.$key};
                   3873:                     if ($key =~ /\.rndseed$/) {
                   3874:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   3875:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   3876:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   3877:                         }
                   3878:                     }
                   3879:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   3880:                                    '&nbsp;</td>';
1.945     raeburn  3881: 	        }
                   3882:             }
                   3883: 	    $prevattempts.=&end_data_table_row();
1.40      ng       3884: 	 }
1.1       albertel 3885:       }
1.945     raeburn  3886:       my @currhidden = keys(%lasthidden);
1.596     albertel 3887:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 3888:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  3889:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  3890:           if (%typeparts) {
                   3891:               my $hidden;
                   3892:               foreach my $id (@currhidden) {
                   3893:                   if ($key =~ /^\Q$id\E/) {
                   3894:                       $hidden = 1;
                   3895:                       last;
                   3896:                   }
                   3897:               }
                   3898:               if ($hidden) {
                   3899:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   3900:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   3901:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3902:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3903:                           $value = &$gradesub($value);
                   3904:                       }
                   3905:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3906:                   } else {
                   3907:                       $prevattempts.='<td>&nbsp;</td>';
                   3908:                   }
                   3909:               } else {
                   3910:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3911:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3912:                       $value = &$gradesub($value);
                   3913:                   }
                   3914:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3915:               }
                   3916:           } else {
                   3917: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   3918: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   3919:                   $value = &$gradesub($value);
                   3920:               }
                   3921: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   3922:           }
1.16      harris41 3923:       }
1.596     albertel 3924:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 3925:     } else {
1.596     albertel 3926:       $prevattempts=
                   3927: 	  &start_data_table().&start_data_table_row().
                   3928: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   3929: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3930:     }
                   3931:   } else {
1.596     albertel 3932:     $prevattempts=
                   3933: 	  &start_data_table().&start_data_table_row().
                   3934: 	  '<td>'.&mt('No data.').'</td>'.
                   3935: 	  &end_data_table_row().&end_data_table();
1.1       albertel 3936:   }
1.10      albertel 3937: }
                   3938: 
1.581     albertel 3939: sub format_previous_attempt_value {
                   3940:     my ($key,$value) = @_;
1.1011    www      3941:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 3942: 	$value = &Apache::lonlocal::locallocaltime($value);
                   3943:     } elsif (ref($value) eq 'ARRAY') {
                   3944: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  3945:     } elsif ($key =~ /answerstring$/) {
                   3946:         my %answers = &Apache::lonnet::str2hash($value);
                   3947:         my @anskeys = sort(keys(%answers));
                   3948:         if (@anskeys == 1) {
                   3949:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  3950:             if ($answer =~ m{\0}) {
                   3951:                 $answer =~ s{\0}{,}g;
1.988     raeburn  3952:             }
                   3953:             my $tag_internal_answer_name = 'INTERNAL';
                   3954:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   3955:                 $value = $answer; 
                   3956:             } else {
                   3957:                 $value = $anskeys[0].'='.$answer;
                   3958:             }
                   3959:         } else {
                   3960:             foreach my $ans (@anskeys) {
                   3961:                 my $answer = $answers{$ans};
1.1001    raeburn  3962:                 if ($answer =~ m{\0}) {
                   3963:                     $answer =~ s{\0}{,}g;
1.988     raeburn  3964:                 }
                   3965:                 $value .=  $ans.'='.$answer.'<br />';;
                   3966:             } 
                   3967:         }
1.581     albertel 3968:     } else {
                   3969: 	$value = &unescape($value);
                   3970:     }
                   3971:     return $value;
                   3972: }
                   3973: 
                   3974: 
1.107     albertel 3975: sub relative_to_absolute {
                   3976:     my ($url,$output)=@_;
                   3977:     my $parser=HTML::TokeParser->new(\$output);
                   3978:     my $token;
                   3979:     my $thisdir=$url;
                   3980:     my @rlinks=();
                   3981:     while ($token=$parser->get_token) {
                   3982: 	if ($token->[0] eq 'S') {
                   3983: 	    if ($token->[1] eq 'a') {
                   3984: 		if ($token->[2]->{'href'}) {
                   3985: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   3986: 		}
                   3987: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   3988: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   3989: 	    } elsif ($token->[1] eq 'base') {
                   3990: 		$thisdir=$token->[2]->{'href'};
                   3991: 	    }
                   3992: 	}
                   3993:     }
                   3994:     $thisdir=~s-/[^/]*$--;
1.356     albertel 3995:     foreach my $link (@rlinks) {
1.726     raeburn  3996: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 3997: 		($link=~/^\//) ||
                   3998: 		($link=~/^javascript:/i) ||
                   3999: 		($link=~/^mailto:/i) ||
                   4000: 		($link=~/^\#/)) {
                   4001: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4002: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4003: 	}
                   4004:     }
                   4005: # -------------------------------------------------- Deal with Applet codebases
                   4006:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4007:     return $output;
                   4008: }
                   4009: 
1.112     bowersj2 4010: =pod
                   4011: 
1.648     raeburn  4012: =item * &get_student_view()
1.112     bowersj2 4013: 
                   4014: show a snapshot of what student was looking at
                   4015: 
                   4016: =cut
                   4017: 
1.10      albertel 4018: sub get_student_view {
1.186     albertel 4019:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4020:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4021:   my (%form);
1.10      albertel 4022:   my @elements=('symb','courseid','domain','username');
                   4023:   foreach my $element (@elements) {
1.186     albertel 4024:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4025:   }
1.186     albertel 4026:   if (defined($moreenv)) {
                   4027:       %form=(%form,%{$moreenv});
                   4028:   }
1.236     albertel 4029:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4030:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4031:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4032:   $userview=~s/\<body[^\>]*\>//gi;
                   4033:   $userview=~s/\<\/body\>//gi;
                   4034:   $userview=~s/\<html\>//gi;
                   4035:   $userview=~s/\<\/html\>//gi;
                   4036:   $userview=~s/\<head\>//gi;
                   4037:   $userview=~s/\<\/head\>//gi;
                   4038:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4039:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4040:   if (wantarray) {
                   4041:      return ($userview,$response);
                   4042:   } else {
                   4043:      return $userview;
                   4044:   }
                   4045: }
                   4046: 
                   4047: sub get_student_view_with_retries {
                   4048:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4049: 
                   4050:     my $ok = 0;                 # True if we got a good response.
                   4051:     my $content;
                   4052:     my $response;
                   4053: 
                   4054:     # Try to get the student_view done. within the retries count:
                   4055:     
                   4056:     do {
                   4057:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4058:          $ok      = $response->is_success;
                   4059:          if (!$ok) {
                   4060:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4061:          }
                   4062:          $retries--;
                   4063:     } while (!$ok && ($retries > 0));
                   4064:     
                   4065:     if (!$ok) {
                   4066:        $content = '';          # On error return an empty content.
                   4067:     }
1.651     www      4068:     if (wantarray) {
                   4069:        return ($content, $response);
                   4070:     } else {
                   4071:        return $content;
                   4072:     }
1.11      albertel 4073: }
                   4074: 
1.112     bowersj2 4075: =pod
                   4076: 
1.648     raeburn  4077: =item * &get_student_answers() 
1.112     bowersj2 4078: 
                   4079: show a snapshot of how student was answering problem
                   4080: 
                   4081: =cut
                   4082: 
1.11      albertel 4083: sub get_student_answers {
1.100     sakharuk 4084:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4085:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4086:   my (%moreenv);
1.11      albertel 4087:   my @elements=('symb','courseid','domain','username');
                   4088:   foreach my $element (@elements) {
1.186     albertel 4089:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4090:   }
1.186     albertel 4091:   $moreenv{'grade_target'}='answer';
                   4092:   %moreenv=(%form,%moreenv);
1.497     raeburn  4093:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4094:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4095:   return $userview;
1.1       albertel 4096: }
1.116     albertel 4097: 
                   4098: =pod
                   4099: 
                   4100: =item * &submlink()
                   4101: 
1.242     albertel 4102: Inputs: $text $uname $udom $symb $target
1.116     albertel 4103: 
                   4104: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4105: 
                   4106: =cut
                   4107: 
                   4108: ###############################################
                   4109: sub submlink {
1.242     albertel 4110:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4111:     if (!($uname && $udom)) {
                   4112: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4113: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4114: 	if (!$symb) { $symb=$cursymb; }
                   4115:     }
1.254     matthew  4116:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4117:     $symb=&escape($symb);
1.960     bisitz   4118:     if ($target) { $target=" target=\"$target\""; }
                   4119:     return
                   4120:         '<a href="/adm/grades?command=submission'.
                   4121:         '&amp;symb='.$symb.
                   4122:         '&amp;student='.$uname.
                   4123:         '&amp;userdom='.$udom.'"'.
                   4124:         $target.'>'.$text.'</a>';
1.242     albertel 4125: }
                   4126: ##############################################
                   4127: 
                   4128: =pod
                   4129: 
                   4130: =item * &pgrdlink()
                   4131: 
                   4132: Inputs: $text $uname $udom $symb $target
                   4133: 
                   4134: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4135: 
                   4136: =cut
                   4137: 
                   4138: ###############################################
                   4139: sub pgrdlink {
                   4140:     my $link=&submlink(@_);
                   4141:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4142:     return $link;
                   4143: }
                   4144: ##############################################
                   4145: 
                   4146: =pod
                   4147: 
                   4148: =item * &pprmlink()
                   4149: 
                   4150: Inputs: $text $uname $udom $symb $target
                   4151: 
                   4152: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4153: student and a specific resource
1.242     albertel 4154: 
                   4155: =cut
                   4156: 
                   4157: ###############################################
                   4158: sub pprmlink {
                   4159:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4160:     if (!($uname && $udom)) {
                   4161: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4162: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4163: 	if (!$symb) { $symb=$cursymb; }
                   4164:     }
1.254     matthew  4165:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4166:     $symb=&escape($symb);
1.242     albertel 4167:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4168:     return '<a href="/adm/parmset?command=set&amp;'.
                   4169: 	'symb='.$symb.'&amp;uname='.$uname.
                   4170: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4171: }
                   4172: ##############################################
1.37      matthew  4173: 
1.112     bowersj2 4174: =pod
                   4175: 
                   4176: =back
                   4177: 
                   4178: =cut
                   4179: 
1.37      matthew  4180: ###############################################
1.51      www      4181: 
                   4182: 
                   4183: sub timehash {
1.687     raeburn  4184:     my ($thistime) = @_;
                   4185:     my $timezone = &Apache::lonlocal::gettimezone();
                   4186:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4187:                      ->set_time_zone($timezone);
                   4188:     my $wday = $dt->day_of_week();
                   4189:     if ($wday == 7) { $wday = 0; }
                   4190:     return ( 'second' => $dt->second(),
                   4191:              'minute' => $dt->minute(),
                   4192:              'hour'   => $dt->hour(),
                   4193:              'day'     => $dt->day_of_month(),
                   4194:              'month'   => $dt->month(),
                   4195:              'year'    => $dt->year(),
                   4196:              'weekday' => $wday,
                   4197:              'dayyear' => $dt->day_of_year(),
                   4198:              'dlsav'   => $dt->is_dst() );
1.51      www      4199: }
                   4200: 
1.370     www      4201: sub utc_string {
                   4202:     my ($date)=@_;
1.371     www      4203:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4204: }
                   4205: 
1.51      www      4206: sub maketime {
                   4207:     my %th=@_;
1.687     raeburn  4208:     my ($epoch_time,$timezone,$dt);
                   4209:     $timezone = &Apache::lonlocal::gettimezone();
                   4210:     eval {
                   4211:         $dt = DateTime->new( year   => $th{'year'},
                   4212:                              month  => $th{'month'},
                   4213:                              day    => $th{'day'},
                   4214:                              hour   => $th{'hour'},
                   4215:                              minute => $th{'minute'},
                   4216:                              second => $th{'second'},
                   4217:                              time_zone => $timezone,
                   4218:                          );
                   4219:     };
                   4220:     if (!$@) {
                   4221:         $epoch_time = $dt->epoch;
                   4222:         if ($epoch_time) {
                   4223:             return $epoch_time;
                   4224:         }
                   4225:     }
1.51      www      4226:     return POSIX::mktime(
                   4227:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4228:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4229: }
                   4230: 
                   4231: #########################################
1.51      www      4232: 
                   4233: sub findallcourses {
1.482     raeburn  4234:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4235:     my %roles;
                   4236:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4237:     my %courses;
1.51      www      4238:     my $now=time;
1.482     raeburn  4239:     if (!defined($uname)) {
                   4240:         $uname = $env{'user.name'};
                   4241:     }
                   4242:     if (!defined($udom)) {
                   4243:         $udom = $env{'user.domain'};
                   4244:     }
                   4245:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4246:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4247:         if (!%roles) {
                   4248:             %roles = (
                   4249:                        cc => 1,
1.907     raeburn  4250:                        co => 1,
1.482     raeburn  4251:                        in => 1,
                   4252:                        ep => 1,
                   4253:                        ta => 1,
                   4254:                        cr => 1,
                   4255:                        st => 1,
                   4256:              );
                   4257:         }
                   4258:         foreach my $entry (keys(%roleshash)) {
                   4259:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4260:             if ($trole =~ /^cr/) { 
                   4261:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4262:             } else {
                   4263:                 next if (!exists($roles{$trole}));
                   4264:             }
                   4265:             if ($tend) {
                   4266:                 next if ($tend < $now);
                   4267:             }
                   4268:             if ($tstart) {
                   4269:                 next if ($tstart > $now);
                   4270:             }
1.1058    raeburn  4271:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4272:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4273:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4274:             if ($secpart eq '') {
                   4275:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4276:                 $sec = 'none';
1.1058    raeburn  4277:                 $value .= $cnum.'/';
1.482     raeburn  4278:             } else {
                   4279:                 $cnum = $cnumpart;
                   4280:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4281:                 $value .= $cnum.'/'.$sec;
                   4282:             }
                   4283:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4284:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4285:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4286:                 }
                   4287:             } else {
                   4288:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4289:             }
1.482     raeburn  4290:         }
                   4291:     } else {
                   4292:         foreach my $key (keys(%env)) {
1.483     albertel 4293: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4294:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4295: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4296: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4297: 	        next if (%roles && !exists($roles{$role}));
                   4298: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4299:                 my $active=1;
                   4300:                 if ($starttime) {
                   4301: 		    if ($now<$starttime) { $active=0; }
                   4302:                 }
                   4303:                 if ($endtime) {
                   4304:                     if ($now>$endtime) { $active=0; }
                   4305:                 }
                   4306:                 if ($active) {
1.1058    raeburn  4307:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4308:                     if ($sec eq '') {
                   4309:                         $sec = 'none';
1.1058    raeburn  4310:                     } else {
                   4311:                         $value .= $sec;
                   4312:                     }
                   4313:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4314:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4315:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4316:                         }
                   4317:                     } else {
                   4318:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4319:                     }
1.474     raeburn  4320:                 }
                   4321:             }
1.51      www      4322:         }
                   4323:     }
1.474     raeburn  4324:     return %courses;
1.51      www      4325: }
1.37      matthew  4326: 
1.54      www      4327: ###############################################
1.474     raeburn  4328: 
                   4329: sub blockcheck {
1.1075.2.73  raeburn  4330:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4331: 
1.1075.2.73  raeburn  4332:     if (defined($udom) && defined($uname)) {
                   4333:         # If uname and udom are for a course, check for blocks in the course.
                   4334:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4335:             my ($startblock,$endblock,$triggerblock) =
                   4336:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4337:             return ($startblock,$endblock,$triggerblock);
                   4338:         }
                   4339:     } else {
1.490     raeburn  4340:         $udom = $env{'user.domain'};
                   4341:         $uname = $env{'user.name'};
                   4342:     }
                   4343: 
1.502     raeburn  4344:     my $startblock = 0;
                   4345:     my $endblock = 0;
1.1062    raeburn  4346:     my $triggerblock = '';
1.482     raeburn  4347:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4348: 
1.490     raeburn  4349:     # If uname is for a user, and activity is course-specific, i.e.,
                   4350:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4351: 
1.490     raeburn  4352:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4353:          $activity eq 'groups' || $activity eq 'printout') &&
                   4354:         ($env{'request.course.id'})) {
1.490     raeburn  4355:         foreach my $key (keys(%live_courses)) {
                   4356:             if ($key ne $env{'request.course.id'}) {
                   4357:                 delete($live_courses{$key});
                   4358:             }
                   4359:         }
                   4360:     }
                   4361: 
                   4362:     my $otheruser = 0;
                   4363:     my %own_courses;
                   4364:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4365:         # Resource belongs to user other than current user.
                   4366:         $otheruser = 1;
                   4367:         # Gather courses for current user
                   4368:         %own_courses = 
                   4369:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4370:     }
                   4371: 
                   4372:     # Gather active course roles - course coordinator, instructor, 
                   4373:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4374: 
                   4375:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4376:         my ($cdom,$cnum);
                   4377:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4378:             $cdom = $env{'course.'.$course.'.domain'};
                   4379:             $cnum = $env{'course.'.$course.'.num'};
                   4380:         } else {
1.490     raeburn  4381:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4382:         }
                   4383:         my $no_ownblock = 0;
                   4384:         my $no_userblock = 0;
1.533     raeburn  4385:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4386:             # Check if current user has 'evb' priv for this
                   4387:             if (defined($own_courses{$course})) {
                   4388:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4389:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4390:                     if ($sec ne 'none') {
                   4391:                         $checkrole .= '/'.$sec;
                   4392:                     }
                   4393:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4394:                         $no_ownblock = 1;
                   4395:                         last;
                   4396:                     }
                   4397:                 }
                   4398:             }
                   4399:             # if they have 'evb' priv and are currently not playing student
                   4400:             next if (($no_ownblock) &&
                   4401:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4402:         }
1.474     raeburn  4403:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4404:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4405:             if ($sec ne 'none') {
1.482     raeburn  4406:                 $checkrole .= '/'.$sec;
1.474     raeburn  4407:             }
1.490     raeburn  4408:             if ($otheruser) {
                   4409:                 # Resource belongs to user other than current user.
                   4410:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4411:                 my (%allroles,%userroles);
                   4412:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4413:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4414:                         my ($trole,$tdom,$tnum,$tsec);
                   4415:                         if ($entry =~ /^cr/) {
                   4416:                             ($trole,$tdom,$tnum,$tsec) = 
                   4417:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4418:                         } else {
                   4419:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4420:                         }
                   4421:                         my ($spec,$area,$trest);
                   4422:                         $area = '/'.$tdom.'/'.$tnum;
                   4423:                         $trest = $tnum;
                   4424:                         if ($tsec ne '') {
                   4425:                             $area .= '/'.$tsec;
                   4426:                             $trest .= '/'.$tsec;
                   4427:                         }
                   4428:                         $spec = $trole.'.'.$area;
                   4429:                         if ($trole =~ /^cr/) {
                   4430:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4431:                                                               $tdom,$spec,$trest,$area);
                   4432:                         } else {
                   4433:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4434:                                                                 $tdom,$spec,$trest,$area);
                   4435:                         }
                   4436:                     }
                   4437:                     my ($author,$adv) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
                   4438:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4439:                         if ($1) {
                   4440:                             $no_userblock = 1;
                   4441:                             last;
                   4442:                         }
1.486     raeburn  4443:                     }
                   4444:                 }
1.490     raeburn  4445:             } else {
                   4446:                 # Resource belongs to current user
                   4447:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4448:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4449:                     $no_ownblock = 1;
                   4450:                     last;
                   4451:                 }
1.474     raeburn  4452:             }
                   4453:         }
                   4454:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4455:         next if (($no_ownblock) &&
1.491     albertel 4456:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4457:         next if ($no_userblock);
1.474     raeburn  4458: 
1.866     kalberla 4459:         # Retrieve blocking times and identity of locker for course
1.490     raeburn  4460:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4461:         
1.1062    raeburn  4462:         my ($start,$end,$trigger) = 
                   4463:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4464:         if (($start != 0) && 
                   4465:             (($startblock == 0) || ($startblock > $start))) {
                   4466:             $startblock = $start;
1.1062    raeburn  4467:             if ($trigger ne '') {
                   4468:                 $triggerblock = $trigger;
                   4469:             }
1.502     raeburn  4470:         }
                   4471:         if (($end != 0)  &&
                   4472:             (($endblock == 0) || ($endblock < $end))) {
                   4473:             $endblock = $end;
1.1062    raeburn  4474:             if ($trigger ne '') {
                   4475:                 $triggerblock = $trigger;
                   4476:             }
1.502     raeburn  4477:         }
1.490     raeburn  4478:     }
1.1062    raeburn  4479:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4480: }
                   4481: 
                   4482: sub get_blocks {
1.1062    raeburn  4483:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4484:     my $startblock = 0;
                   4485:     my $endblock = 0;
1.1062    raeburn  4486:     my $triggerblock = '';
1.490     raeburn  4487:     my $course = $cdom.'_'.$cnum;
                   4488:     $setters->{$course} = {};
                   4489:     $setters->{$course}{'staff'} = [];
                   4490:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4491:     $setters->{$course}{'triggers'} = [];
                   4492:     my (@blockers,%triggered);
                   4493:     my $now = time;
                   4494:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4495:     if ($activity eq 'docs') {
                   4496:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4497:         foreach my $block (@blockers) {
                   4498:             if ($block =~ /^firstaccess____(.+)$/) {
                   4499:                 my $item = $1;
                   4500:                 my $type = 'map';
                   4501:                 my $timersymb = $item;
                   4502:                 if ($item eq 'course') {
                   4503:                     $type = 'course';
                   4504:                 } elsif ($item =~ /___\d+___/) {
                   4505:                     $type = 'resource';
                   4506:                 } else {
                   4507:                     $timersymb = &Apache::lonnet::symbread($item);
                   4508:                 }
                   4509:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4510:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4511:                 $triggered{$block} = {
                   4512:                                        start => $start,
                   4513:                                        end   => $end,
                   4514:                                        type  => $type,
                   4515:                                      };
                   4516:             }
                   4517:         }
                   4518:     } else {
                   4519:         foreach my $block (keys(%commblocks)) {
                   4520:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4521:                 my ($start,$end) = ($1,$2);
                   4522:                 if ($start <= time && $end >= time) {
                   4523:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4524:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4525:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4526:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4527:                                     push(@blockers,$block);
                   4528:                                 }
                   4529:                             }
                   4530:                         }
                   4531:                     }
                   4532:                 }
                   4533:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4534:                 my $item = $1;
                   4535:                 my $timersymb = $item; 
                   4536:                 my $type = 'map';
                   4537:                 if ($item eq 'course') {
                   4538:                     $type = 'course';
                   4539:                 } elsif ($item =~ /___\d+___/) {
                   4540:                     $type = 'resource';
                   4541:                 } else {
                   4542:                     $timersymb = &Apache::lonnet::symbread($item);
                   4543:                 }
                   4544:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4545:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4546:                 if ($start && $end) {
                   4547:                     if (($start <= time) && ($end >= time)) {
                   4548:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4549:                             push(@blockers,$block);
                   4550:                             $triggered{$block} = {
                   4551:                                                    start => $start,
                   4552:                                                    end   => $end,
                   4553:                                                    type  => $type,
                   4554:                                                  };
                   4555:                         }
                   4556:                     }
1.490     raeburn  4557:                 }
1.1062    raeburn  4558:             }
                   4559:         }
                   4560:     }
                   4561:     foreach my $blocker (@blockers) {
                   4562:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4563:             &parse_block_record($commblocks{$blocker});
                   4564:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4565:         my ($start,$end,$triggertype);
                   4566:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4567:             ($start,$end) = ($1,$2);
                   4568:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4569:             $start = $triggered{$blocker}{'start'};
                   4570:             $end = $triggered{$blocker}{'end'};
                   4571:             $triggertype = $triggered{$blocker}{'type'};
                   4572:         }
                   4573:         if ($start) {
                   4574:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4575:             if ($triggertype) {
                   4576:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4577:             } else {
                   4578:                 push(@{$$setters{$course}{'triggers'}},0);
                   4579:             }
                   4580:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4581:                 $startblock = $start;
                   4582:                 if ($triggertype) {
                   4583:                     $triggerblock = $blocker;
1.474     raeburn  4584:                 }
                   4585:             }
1.1062    raeburn  4586:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4587:                $endblock = $end;
                   4588:                if ($triggertype) {
                   4589:                    $triggerblock = $blocker;
                   4590:                }
                   4591:             }
1.474     raeburn  4592:         }
                   4593:     }
1.1062    raeburn  4594:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4595: }
                   4596: 
                   4597: sub parse_block_record {
                   4598:     my ($record) = @_;
                   4599:     my ($setuname,$setudom,$title,$blocks);
                   4600:     if (ref($record) eq 'HASH') {
                   4601:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4602:         $title = &unescape($record->{'event'});
                   4603:         $blocks = $record->{'blocks'};
                   4604:     } else {
                   4605:         my @data = split(/:/,$record,3);
                   4606:         if (scalar(@data) eq 2) {
                   4607:             $title = $data[1];
                   4608:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4609:         } else {
                   4610:             ($setuname,$setudom,$title) = @data;
                   4611:         }
                   4612:         $blocks = { 'com' => 'on' };
                   4613:     }
                   4614:     return ($setuname,$setudom,$title,$blocks);
                   4615: }
                   4616: 
1.854     kalberla 4617: sub blocking_status {
1.1075.2.73  raeburn  4618:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4619:     my %setters;
1.890     droeschl 4620: 
1.1061    raeburn  4621: # check for active blocking
1.1062    raeburn  4622:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4623:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4624:     my $blocked = 0;
                   4625:     if ($startblock && $endblock) {
                   4626:         $blocked = 1;
                   4627:     }
1.890     droeschl 4628: 
1.1061    raeburn  4629: # caller just wants to know whether a block is active
                   4630:     if (!wantarray) { return $blocked; }
                   4631: 
                   4632: # build a link to a popup window containing the details
                   4633:     my $querystring  = "?activity=$activity";
                   4634: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4635:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4636:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4637:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4638:     } elsif ($activity eq 'docs') {
                   4639:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4640:     }
1.1061    raeburn  4641: 
                   4642:     my $output .= <<'END_MYBLOCK';
                   4643: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4644:     var options = "width=" + w + ",height=" + h + ",";
                   4645:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4646:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4647:     var newWin = window.open(url, wdwName, options);
                   4648:     newWin.focus();
                   4649: }
1.890     droeschl 4650: END_MYBLOCK
1.854     kalberla 4651: 
1.1061    raeburn  4652:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4653:   
1.1061    raeburn  4654:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4655:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  4656:     my $class = 'LC_comblock';
1.1062    raeburn  4657:     if ($activity eq 'docs') {
                   4658:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  4659:         $class = '';
1.1063    raeburn  4660:     } elsif ($activity eq 'printout') {
                   4661:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  4662:     } elsif ($activity eq 'passwd') {
                   4663:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  4664:     }
1.1061    raeburn  4665:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  4666: <div class='$class'>
1.869     kalberla 4667:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4668:   title='$text'>
                   4669:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4670:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4671:   title='$text'>$text</a>
1.867     kalberla 4672: </div>
                   4673: 
                   4674: END_BLOCK
1.474     raeburn  4675: 
1.1061    raeburn  4676:     return ($blocked, $output);
1.854     kalberla 4677: }
1.490     raeburn  4678: 
1.60      matthew  4679: ###############################################
                   4680: 
1.682     raeburn  4681: sub check_ip_acc {
                   4682:     my ($acc)=@_;
                   4683:     &Apache::lonxml::debug("acc is $acc");
                   4684:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4685:         return 1;
                   4686:     }
                   4687:     my $allowed=0;
                   4688:     my $ip=$env{'request.host'} || $ENV{'REMOTE_ADDR'};
                   4689: 
                   4690:     my $name;
                   4691:     foreach my $pattern (split(',',$acc)) {
                   4692:         $pattern =~ s/^\s*//;
                   4693:         $pattern =~ s/\s*$//;
                   4694:         if ($pattern =~ /\*$/) {
                   4695:             #35.8.*
                   4696:             $pattern=~s/\*//;
                   4697:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4698:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4699:             #35.8.3.[34-56]
                   4700:             my $low=$2;
                   4701:             my $high=$3;
                   4702:             $pattern=$1;
                   4703:             if ($ip =~ /^\Q$pattern\E/) {
                   4704:                 my $last=(split(/\./,$ip))[3];
                   4705:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4706:             }
                   4707:         } elsif ($pattern =~ /^\*/) {
                   4708:             #*.msu.edu
                   4709:             $pattern=~s/\*//;
                   4710:             if (!defined($name)) {
                   4711:                 use Socket;
                   4712:                 my $netaddr=inet_aton($ip);
                   4713:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4714:             }
                   4715:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4716:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4717:             #127.0.0.1
                   4718:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4719:         } else {
                   4720:             #some.name.com
                   4721:             if (!defined($name)) {
                   4722:                 use Socket;
                   4723:                 my $netaddr=inet_aton($ip);
                   4724:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4725:             }
                   4726:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4727:         }
                   4728:         if ($allowed) { last; }
                   4729:     }
                   4730:     return $allowed;
                   4731: }
                   4732: 
                   4733: ###############################################
                   4734: 
1.60      matthew  4735: =pod
                   4736: 
1.112     bowersj2 4737: =head1 Domain Template Functions
                   4738: 
                   4739: =over 4
                   4740: 
                   4741: =item * &determinedomain()
1.60      matthew  4742: 
                   4743: Inputs: $domain (usually will be undef)
                   4744: 
1.63      www      4745: Returns: Determines which domain should be used for designs
1.60      matthew  4746: 
                   4747: =cut
1.54      www      4748: 
1.60      matthew  4749: ###############################################
1.63      www      4750: sub determinedomain {
                   4751:     my $domain=shift;
1.531     albertel 4752:     if (! $domain) {
1.60      matthew  4753:         # Determine domain if we have not been given one
1.893     raeburn  4754:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 4755:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   4756:         if ($env{'request.role.domain'}) { 
                   4757:             $domain=$env{'request.role.domain'}; 
1.60      matthew  4758:         }
                   4759:     }
1.63      www      4760:     return $domain;
                   4761: }
                   4762: ###############################################
1.517     raeburn  4763: 
1.518     albertel 4764: sub devalidate_domconfig_cache {
                   4765:     my ($udom)=@_;
                   4766:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   4767: }
                   4768: 
                   4769: # ---------------------- Get domain configuration for a domain
                   4770: sub get_domainconf {
                   4771:     my ($udom) = @_;
                   4772:     my $cachetime=1800;
                   4773:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   4774:     if (defined($cached)) { return %{$result}; }
                   4775: 
                   4776:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  4777: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  4778:     my (%designhash,%legacy);
1.518     albertel 4779:     if (keys(%domconfig) > 0) {
                   4780:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  4781:             if (keys(%{$domconfig{'login'}})) {
                   4782:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  4783:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  4784:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   4785:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   4786:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   4787:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   4788:                                         if ($key eq 'loginvia') {
                   4789:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   4790:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   4791:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   4792:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   4793:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   4794:                                                 } else {
                   4795:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   4796:                                                 }
1.948     raeburn  4797:                                             }
1.1075.2.87  raeburn  4798:                                         } elsif ($key eq 'headtag') {
                   4799:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   4800:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  4801:                                             }
1.946     raeburn  4802:                                         }
1.1075.2.87  raeburn  4803:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   4804:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   4805:                                         }
1.946     raeburn  4806:                                     }
                   4807:                                 }
                   4808:                             }
                   4809:                         } else {
                   4810:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   4811:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   4812:                                     $domconfig{'login'}{$key}{$img};
                   4813:                             }
1.699     raeburn  4814:                         }
                   4815:                     } else {
                   4816:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   4817:                     }
1.632     raeburn  4818:                 }
                   4819:             } else {
                   4820:                 $legacy{'login'} = 1;
1.518     albertel 4821:             }
1.632     raeburn  4822:         } else {
                   4823:             $legacy{'login'} = 1;
1.518     albertel 4824:         }
                   4825:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  4826:             if (keys(%{$domconfig{'rolecolors'}})) {
                   4827:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   4828:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   4829:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   4830:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   4831:                         }
1.518     albertel 4832:                     }
                   4833:                 }
1.632     raeburn  4834:             } else {
                   4835:                 $legacy{'rolecolors'} = 1;
1.518     albertel 4836:             }
1.632     raeburn  4837:         } else {
                   4838:             $legacy{'rolecolors'} = 1;
1.518     albertel 4839:         }
1.948     raeburn  4840:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   4841:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   4842:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   4843:             }
                   4844:         }
1.632     raeburn  4845:         if (keys(%legacy) > 0) {
                   4846:             my %legacyhash = &get_legacy_domconf($udom);
                   4847:             foreach my $item (keys(%legacyhash)) {
                   4848:                 if ($item =~ /^\Q$udom\E\.login/) {
                   4849:                     if ($legacy{'login'}) { 
                   4850:                         $designhash{$item} = $legacyhash{$item};
                   4851:                     }
                   4852:                 } else {
                   4853:                     if ($legacy{'rolecolors'}) {
                   4854:                         $designhash{$item} = $legacyhash{$item};
                   4855:                     }
1.518     albertel 4856:                 }
                   4857:             }
                   4858:         }
1.632     raeburn  4859:     } else {
                   4860:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 4861:     }
                   4862:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   4863: 				  $cachetime);
                   4864:     return %designhash;
                   4865: }
                   4866: 
1.632     raeburn  4867: sub get_legacy_domconf {
                   4868:     my ($udom) = @_;
                   4869:     my %legacyhash;
                   4870:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   4871:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   4872:     if (-e $designfile) {
                   4873:         if ( open (my $fh,"<$designfile") ) {
                   4874:             while (my $line = <$fh>) {
                   4875:                 next if ($line =~ /^\#/);
                   4876:                 chomp($line);
                   4877:                 my ($key,$val)=(split(/\=/,$line));
                   4878:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   4879:             }
                   4880:             close($fh);
                   4881:         }
                   4882:     }
1.1026    raeburn  4883:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  4884:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   4885:     }
                   4886:     return %legacyhash;
                   4887: }
                   4888: 
1.63      www      4889: =pod
                   4890: 
1.112     bowersj2 4891: =item * &domainlogo()
1.63      www      4892: 
                   4893: Inputs: $domain (usually will be undef)
                   4894: 
                   4895: Returns: A link to a domain logo, if the domain logo exists.
                   4896: If the domain logo does not exist, a description of the domain.
                   4897: 
                   4898: =cut
1.112     bowersj2 4899: 
1.63      www      4900: ###############################################
                   4901: sub domainlogo {
1.517     raeburn  4902:     my $domain = &determinedomain(shift);
1.518     albertel 4903:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  4904:     # See if there is a logo
                   4905:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  4906:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 4907:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   4908: 	    if ($imgsrc =~ m{^/res/}) {
                   4909: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   4910: 		&Apache::lonnet::repcopy($local_name);
                   4911: 	    }
                   4912: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  4913:         } 
                   4914:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 4915:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   4916:         return &Apache::lonnet::domain($domain,'description');
1.59      www      4917:     } else {
1.60      matthew  4918:         return '';
1.59      www      4919:     }
                   4920: }
1.63      www      4921: ##############################################
                   4922: 
                   4923: =pod
                   4924: 
1.112     bowersj2 4925: =item * &designparm()
1.63      www      4926: 
                   4927: Inputs: $which parameter; $domain (usually will be undef)
                   4928: 
                   4929: Returns: value of designparamter $which
                   4930: 
                   4931: =cut
1.112     bowersj2 4932: 
1.397     albertel 4933: 
1.400     albertel 4934: ##############################################
1.397     albertel 4935: sub designparm {
                   4936:     my ($which,$domain)=@_;
                   4937:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   4938:         return $env{'environment.color.'.$which};
1.96      www      4939:     }
1.63      www      4940:     $domain=&determinedomain($domain);
1.1016    raeburn  4941:     my %domdesign;
                   4942:     unless ($domain eq 'public') {
                   4943:         %domdesign = &get_domainconf($domain);
                   4944:     }
1.520     raeburn  4945:     my $output;
1.517     raeburn  4946:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   4947:         $output = $domdesign{$domain.'.'.$which};
1.63      www      4948:     } else {
1.520     raeburn  4949:         $output = $defaultdesign{$which};
                   4950:     }
                   4951:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  4952:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 4953:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   4954:             if ($output =~ m{^/res/}) {
                   4955:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   4956:                 &Apache::lonnet::repcopy($local_name);
                   4957:             }
1.520     raeburn  4958:             $output = &lonhttpdurl($output);
                   4959:         }
1.63      www      4960:     }
1.520     raeburn  4961:     return $output;
1.63      www      4962: }
1.59      www      4963: 
1.822     bisitz   4964: ##############################################
                   4965: =pod
                   4966: 
1.832     bisitz   4967: =item * &authorspace()
                   4968: 
1.1028    raeburn  4969: Inputs: $url (usually will be undef).
1.832     bisitz   4970: 
1.1075.2.40  raeburn  4971: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  4972:          directory being viewed (or for which action is being taken). 
                   4973:          If $url is provided, and begins /priv/<domain>/<uname>
                   4974:          the path will be that portion of the $context argument.
                   4975:          Otherwise the path will be for the author space of the current
                   4976:          user when the current role is author, or for that of the 
                   4977:          co-author/assistant co-author space when the current role 
                   4978:          is co-author or assistant co-author.
1.832     bisitz   4979: 
                   4980: =cut
                   4981: 
                   4982: sub authorspace {
1.1028    raeburn  4983:     my ($url) = @_;
                   4984:     if ($url ne '') {
                   4985:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   4986:            return $1;
                   4987:         }
                   4988:     }
1.832     bisitz   4989:     my $caname = '';
1.1024    www      4990:     my $cadom = '';
1.1028    raeburn  4991:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      4992:         ($cadom,$caname) =
1.832     bisitz   4993:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  4994:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   4995:         $caname = $env{'user.name'};
1.1024    www      4996:         $cadom = $env{'user.domain'};
1.832     bisitz   4997:     }
1.1028    raeburn  4998:     if (($caname ne '') && ($cadom ne '')) {
                   4999:         return "/priv/$cadom/$caname/";
                   5000:     }
                   5001:     return;
1.832     bisitz   5002: }
                   5003: 
                   5004: ##############################################
                   5005: =pod
                   5006: 
1.822     bisitz   5007: =item * &head_subbox()
                   5008: 
                   5009: Inputs: $content (contains HTML code with page functions, etc.)
                   5010: 
                   5011: Returns: HTML div with $content
                   5012:          To be included in page header
                   5013: 
                   5014: =cut
                   5015: 
                   5016: sub head_subbox {
                   5017:     my ($content)=@_;
                   5018:     my $output =
1.993     raeburn  5019:         '<div class="LC_head_subbox">'
1.822     bisitz   5020:        .$content
                   5021:        .'</div>'
                   5022: }
                   5023: 
                   5024: ##############################################
                   5025: =pod
                   5026: 
                   5027: =item * &CSTR_pageheader()
                   5028: 
1.1026    raeburn  5029: Input: (optional) filename from which breadcrumb trail is built.
                   5030:        In most cases no input as needed, as $env{'request.filename'}
                   5031:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5032: 
                   5033: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5034:          To be included on Authoring Space pages
1.822     bisitz   5035: 
                   5036: =cut
                   5037: 
                   5038: sub CSTR_pageheader {
1.1026    raeburn  5039:     my ($trailfile) = @_;
                   5040:     if ($trailfile eq '') {
                   5041:         $trailfile = $env{'request.filename'};
                   5042:     }
                   5043: 
                   5044: # this is for resources; directories have customtitle, and crumbs
                   5045: # and select recent are created in lonpubdir.pm
                   5046: 
                   5047:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5048:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5049:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5050:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5051:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5052: 
                   5053:     my $parentpath = '';
                   5054:     my $lastitem = '';
                   5055:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5056:         $parentpath = $1;
                   5057:         $lastitem = $2;
                   5058:     } else {
                   5059:         $lastitem = $thisdisfn;
                   5060:     }
1.921     bisitz   5061: 
                   5062:     my $output =
1.822     bisitz   5063:          '<div>'
                   5064:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5065:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5066:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5067:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5068:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5069: 
                   5070:     if ($lastitem) {
                   5071:         $output .=
                   5072:              '<span class="LC_filename">'
                   5073:             .$lastitem
                   5074:             .'</span>';
                   5075:     }
                   5076:     $output .=
                   5077:          '<br />'
1.822     bisitz   5078:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5079:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5080:         .'</form>'
                   5081:         .&Apache::lonmenu::constspaceform()
                   5082:         .'</div>';
1.921     bisitz   5083: 
                   5084:     return $output;
1.822     bisitz   5085: }
                   5086: 
1.60      matthew  5087: ###############################################
                   5088: ###############################################
                   5089: 
                   5090: =pod
                   5091: 
1.112     bowersj2 5092: =back
                   5093: 
1.549     albertel 5094: =head1 HTML Helpers
1.112     bowersj2 5095: 
                   5096: =over 4
                   5097: 
                   5098: =item * &bodytag()
1.60      matthew  5099: 
                   5100: Returns a uniform header for LON-CAPA web pages.
                   5101: 
                   5102: Inputs: 
                   5103: 
1.112     bowersj2 5104: =over 4
                   5105: 
                   5106: =item * $title, A title to be displayed on the page.
                   5107: 
                   5108: =item * $function, the current role (can be undef).
                   5109: 
                   5110: =item * $addentries, extra parameters for the <body> tag.
                   5111: 
                   5112: =item * $bodyonly, if defined, only return the <body> tag.
                   5113: 
                   5114: =item * $domain, if defined, force a given domain.
                   5115: 
                   5116: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5117:             text interface only)
1.60      matthew  5118: 
1.814     bisitz   5119: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5120:                      navigational links
1.317     albertel 5121: 
1.338     albertel 5122: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5123: 
1.1075.2.12  raeburn  5124: =item * $no_inline_link, if true and in remote mode, don't show the
                   5125:          'Switch To Inline Menu' link
                   5126: 
1.460     albertel 5127: =item * $args, optional argument valid values are
                   5128:             no_auto_mt_title -> prevents &mt()ing the title arg
                   5129: 
1.1075.2.15  raeburn  5130: =item * $advtoolsref, optional argument, ref to an array containing
                   5131:             inlineremote items to be added in "Functions" menu below
                   5132:             breadcrumbs.
                   5133: 
1.112     bowersj2 5134: =back
                   5135: 
1.60      matthew  5136: Returns: A uniform header for LON-CAPA web pages.  
                   5137: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5138: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5139: other decorations will be returned.
                   5140: 
                   5141: =cut
                   5142: 
1.54      www      5143: sub bodytag {
1.831     bisitz   5144:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5145:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5146: 
1.954     raeburn  5147:     my $public;
                   5148:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5149:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5150:         $public = 1;
                   5151:     }
1.460     albertel 5152:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5153:     my $httphost = $args->{'use_absolute'};
1.339     albertel 5154: 
1.183     matthew  5155:     $function = &get_users_function() if (!$function);
1.339     albertel 5156:     my $img =    &designparm($function.'.img',$domain);
                   5157:     my $font =   &designparm($function.'.font',$domain);
                   5158:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5159: 
1.803     bisitz   5160:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5161: 		   'bgcolor' => $pgbg,
1.339     albertel 5162: 		   'text'    => $font,
                   5163:                    'alink'   => &designparm($function.'.alink',$domain),
                   5164: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5165: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5166:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5167: 
1.63      www      5168:  # role and realm
1.1075.2.68  raeburn  5169:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5170:     if ($realm) {
                   5171:         $realm = '/'.$realm;
                   5172:     }
1.378     raeburn  5173:     if ($role  eq 'ca') {
1.479     albertel 5174:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5175:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5176:     } 
1.55      www      5177: # realm
1.258     albertel 5178:     if ($env{'request.course.id'}) {
1.378     raeburn  5179:         if ($env{'request.role'} !~ /^cr/) {
                   5180:             $role = &Apache::lonnet::plaintext($role,&course_type());
                   5181:         }
1.898     raeburn  5182:         if ($env{'request.course.sec'}) {
                   5183:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5184:         }   
1.359     albertel 5185: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5186:     } else {
                   5187:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5188:     }
1.433     albertel 5189: 
1.359     albertel 5190:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5191: 
1.438     albertel 5192:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5193: 
1.101     www      5194: # construct main body tag
1.359     albertel 5195:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100! raeburn  5196: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5197: 
1.1075.2.38  raeburn  5198:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5199: 
                   5200:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5201:         return $bodytag;
1.1075.2.38  raeburn  5202:     }
1.359     albertel 5203: 
1.954     raeburn  5204:     if ($public) {
1.433     albertel 5205: 	undef($role);
                   5206:     }
1.359     albertel 5207:     
1.762     bisitz   5208:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5209:     #
                   5210:     # Extra info if you are the DC
                   5211:     my $dc_info = '';
                   5212:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5213:                         $env{'course.'.$env{'request.course.id'}.
                   5214:                                  '.domain'}.'/'})) {
                   5215:         my $cid = $env{'request.course.id'};
1.917     raeburn  5216:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5217:         $dc_info =~ s/\s+$//;
1.359     albertel 5218:     }
                   5219: 
1.898     raeburn  5220:     $role = '<span class="LC_nobreak">('.$role.')</span>' if $role;
1.903     droeschl 5221: 
1.1075.2.13  raeburn  5222:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5223: 
1.1075.2.38  raeburn  5224: 
                   5225: 
1.1075.2.21  raeburn  5226:     my $funclist;
                   5227:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5228:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5229:                     Apache::lonmenu::serverform();
                   5230:         my $forbodytag;
                   5231:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5232:                                             $forcereg,$args->{'group'},
                   5233:                                             $args->{'bread_crumbs'},
                   5234:                                             $advtoolsref,'',\$forbodytag);
                   5235:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5236:             $funclist = $forbodytag;
                   5237:         }
                   5238:     } else {
1.903     droeschl 5239: 
                   5240:         #    if ($env{'request.state'} eq 'construct') {
                   5241:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5242:         #    }
                   5243: 
1.1075.2.38  raeburn  5244:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5245:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5246: 
1.1075.2.38  raeburn  5247:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5248: 
1.916     droeschl 5249:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5250:             if ($dc_info) {
                   5251:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5252:             }
1.1075.2.38  raeburn  5253:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5254:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5255:             return $bodytag;
                   5256:         }
1.894     droeschl 5257: 
1.927     raeburn  5258:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5259:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5260:         }
1.916     droeschl 5261: 
1.1075.2.38  raeburn  5262:         $bodytag .= $right;
1.852     droeschl 5263: 
1.917     raeburn  5264:         if ($dc_info) {
                   5265:             $dc_info = &dc_courseid_toggle($dc_info);
                   5266:         }
                   5267:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5268: 
1.1075.2.61  raeburn  5269:         #if directed to not display the secondary menu, don't.
                   5270:         if ($args->{'no_secondary_menu'}) {
                   5271:             return $bodytag;
                   5272:         }
1.903     droeschl 5273:         #don't show menus for public users
1.954     raeburn  5274:         if (!$public){
1.1075.2.52  raeburn  5275:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5276:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5277:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5278:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5279:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.920     raeburn  5280:                                 $args->{'bread_crumbs'});
                   5281:             } elsif ($forcereg) { 
1.1075.2.22  raeburn  5282:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
                   5283:                                                             $args->{'group'});
1.1075.2.15  raeburn  5284:             } else {
1.1075.2.21  raeburn  5285:                 my $forbodytag;
                   5286:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5287:                                                     $forcereg,$args->{'group'},
                   5288:                                                     $args->{'bread_crumbs'},
                   5289:                                                     $advtoolsref,'',\$forbodytag);
                   5290:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5291:                     $bodytag .= $forbodytag;
                   5292:                 }
1.920     raeburn  5293:             }
1.903     droeschl 5294:         }else{
                   5295:             # this is to seperate menu from content when there's no secondary
                   5296:             # menu. Especially needed for public accessible ressources.
                   5297:             $bodytag .= '<hr style="clear:both" />';
                   5298:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5299:         }
1.903     droeschl 5300: 
1.235     raeburn  5301:         return $bodytag;
1.1075.2.12  raeburn  5302:     }
                   5303: 
                   5304: #
                   5305: # Top frame rendering, Remote is up
                   5306: #
                   5307: 
                   5308:     my $imgsrc = $img;
                   5309:     if ($img =~ /^\/adm/) {
                   5310:         $imgsrc = &lonhttpdurl($img);
                   5311:     }
                   5312:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5313: 
1.1075.2.60  raeburn  5314:     my $help=($no_inline_link?''
                   5315:               :&Apache::loncommon::top_nav_help('Help'));
                   5316: 
1.1075.2.12  raeburn  5317:     # Explicit link to get inline menu
                   5318:     my $menu= ($no_inline_link?''
                   5319:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5320: 
                   5321:     if ($dc_info) {
                   5322:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5323:     }
                   5324: 
1.1075.2.38  raeburn  5325:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5326:     unless ($public) {
                   5327:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5328:                                 undef,'LC_menubuttons_link');
                   5329:     }
                   5330: 
1.1075.2.12  raeburn  5331:     unless ($env{'form.inhibitmenu'}) {
                   5332:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5333:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5334:                        <li>$help</li>
1.1075.2.12  raeburn  5335:                        <li>$menu</li>
                   5336:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5337:     }
1.1075.2.13  raeburn  5338:     if ($env{'request.state'} eq 'construct') {
                   5339:         if (!$public){
                   5340:             if ($env{'request.state'} eq 'construct') {
                   5341:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5342:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5343:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5344:                             &Apache::lonmenu::innerregister($forcereg,
                   5345:                                                             $args->{'bread_crumbs'});
                   5346:             }
                   5347:         }
                   5348:     }
1.1075.2.21  raeburn  5349:     return $bodytag."\n".$funclist;
1.182     matthew  5350: }
                   5351: 
1.917     raeburn  5352: sub dc_courseid_toggle {
                   5353:     my ($dc_info) = @_;
1.980     raeburn  5354:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5355:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5356:            &mt('(More ...)').'</a></span>'.
                   5357:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5358: }
                   5359: 
1.330     albertel 5360: sub make_attr_string {
                   5361:     my ($register,$attr_ref) = @_;
                   5362: 
                   5363:     if ($attr_ref && !ref($attr_ref)) {
                   5364: 	die("addentries Must be a hash ref ".
                   5365: 	    join(':',caller(1))." ".
                   5366: 	    join(':',caller(0))." ");
                   5367:     }
                   5368: 
                   5369:     if ($register) {
1.339     albertel 5370: 	my ($on_load,$on_unload);
                   5371: 	foreach my $key (keys(%{$attr_ref})) {
                   5372: 	    if      (lc($key) eq 'onload') {
                   5373: 		$on_load.=$attr_ref->{$key}.';';
                   5374: 		delete($attr_ref->{$key});
                   5375: 
                   5376: 	    } elsif (lc($key) eq 'onunload') {
                   5377: 		$on_unload.=$attr_ref->{$key}.';';
                   5378: 		delete($attr_ref->{$key});
                   5379: 	    }
                   5380: 	}
1.1075.2.12  raeburn  5381:         if ($env{'environment.remote'} eq 'on') {
                   5382:             $attr_ref->{'onload'}  =
                   5383:                 &Apache::lonmenu::loadevents().  $on_load;
                   5384:             $attr_ref->{'onunload'}=
                   5385:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5386:         } else {  
                   5387: 	    $attr_ref->{'onload'}  = $on_load;
                   5388: 	    $attr_ref->{'onunload'}= $on_unload;
                   5389:         }
1.330     albertel 5390:     }
1.339     albertel 5391: 
1.330     albertel 5392:     my $attr_string;
1.1075.2.56  raeburn  5393:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5394: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5395:     }
                   5396:     return $attr_string;
                   5397: }
                   5398: 
                   5399: 
1.182     matthew  5400: ###############################################
1.251     albertel 5401: ###############################################
                   5402: 
                   5403: =pod
                   5404: 
                   5405: =item * &endbodytag()
                   5406: 
                   5407: Returns a uniform footer for LON-CAPA web pages.
                   5408: 
1.635     raeburn  5409: Inputs: 1 - optional reference to an args hash
                   5410: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5411: a 'Continue' link is not displayed if the page contains an
                   5412: internal redirect in the <head></head> section,
                   5413: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5414: 
                   5415: =cut
                   5416: 
                   5417: sub endbodytag {
1.635     raeburn  5418:     my ($args) = @_;
1.1075.2.6  raeburn  5419:     my $endbodytag;
                   5420:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5421:         $endbodytag='</body>';
                   5422:     }
1.315     albertel 5423:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5424:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5425: 	    $endbodytag=
                   5426: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5427: 	        &mt('Continue').'</a>'.
                   5428: 	        $endbodytag;
                   5429:         }
1.315     albertel 5430:     }
1.251     albertel 5431:     return $endbodytag;
                   5432: }
                   5433: 
1.352     albertel 5434: =pod
                   5435: 
                   5436: =item * &standard_css()
                   5437: 
                   5438: Returns a style sheet
                   5439: 
                   5440: Inputs: (all optional)
                   5441:             domain         -> force to color decorate a page for a specific
                   5442:                                domain
                   5443:             function       -> force usage of a specific rolish color scheme
                   5444:             bgcolor        -> override the default page bgcolor
                   5445: 
                   5446: =cut
                   5447: 
1.343     albertel 5448: sub standard_css {
1.345     albertel 5449:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5450:     $function  = &get_users_function() if (!$function);
                   5451:     my $img    = &designparm($function.'.img',   $domain);
                   5452:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5453:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5454:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5455: #second colour for later usage
1.345     albertel 5456:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5457:     my $pgbg_or_bgcolor =
                   5458: 	         $bgcolor ||
1.352     albertel 5459: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5460:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5461:     my $alink  = &designparm($function.'.alink', $domain);
                   5462:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5463:     my $link   = &designparm($function.'.link',  $domain);
                   5464: 
1.602     albertel 5465:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5466:     my $mono                 = 'monospace';
1.850     bisitz   5467:     my $data_table_head      = $sidebg;
                   5468:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5469:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5470:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5471:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5472:     my $mail_new             = '#FFBB77';
                   5473:     my $mail_new_hover       = '#DD9955';
                   5474:     my $mail_read            = '#BBBB77';
                   5475:     my $mail_read_hover      = '#999944';
                   5476:     my $mail_replied         = '#AAAA88';
                   5477:     my $mail_replied_hover   = '#888855';
                   5478:     my $mail_other           = '#99BBBB';
                   5479:     my $mail_other_hover     = '#669999';
1.391     albertel 5480:     my $table_header         = '#DDDDDD';
1.489     raeburn  5481:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5482:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5483:     my $button_hover         = '#BF2317';
1.392     albertel 5484: 
1.608     albertel 5485:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5486:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5487:                                              : '0 3px 0 4px';
1.448     albertel 5488: 
1.523     albertel 5489: 
1.343     albertel 5490:     return <<END;
1.947     droeschl 5491: 
                   5492: /* needed for iframe to allow 100% height in FF */
                   5493: body, html { 
                   5494:     margin: 0;
                   5495:     padding: 0 0.5%;
                   5496:     height: 99%; /* to avoid scrollbars */
                   5497: }
                   5498: 
1.795     www      5499: body {
1.911     bisitz   5500:   font-family: $sans;
                   5501:   line-height:130%;
                   5502:   font-size:0.83em;
                   5503:   color:$font;
1.795     www      5504: }
                   5505: 
1.959     onken    5506: a:focus,
                   5507: a:focus img {
1.795     www      5508:   color: red;
                   5509: }
1.698     harmsja  5510: 
1.911     bisitz   5511: form, .inline {
                   5512:   display: inline;
1.795     www      5513: }
1.721     harmsja  5514: 
1.795     www      5515: .LC_right {
1.911     bisitz   5516:   text-align:right;
1.795     www      5517: }
                   5518: 
                   5519: .LC_middle {
1.911     bisitz   5520:   vertical-align:middle;
1.795     www      5521: }
1.721     harmsja  5522: 
1.1075.2.38  raeburn  5523: .LC_floatleft {
                   5524:   float: left;
                   5525: }
                   5526: 
                   5527: .LC_floatright {
                   5528:   float: right;
                   5529: }
                   5530: 
1.911     bisitz   5531: .LC_400Box {
                   5532:   width:400px;
                   5533: }
1.721     harmsja  5534: 
1.947     droeschl 5535: .LC_iframecontainer {
                   5536:     width: 98%;
                   5537:     margin: 0;
                   5538:     position: fixed;
                   5539:     top: 8.5em;
                   5540:     bottom: 0;
                   5541: }
                   5542: 
                   5543: .LC_iframecontainer iframe{
                   5544:     border: none;
                   5545:     width: 100%;
                   5546:     height: 100%;
                   5547: }
                   5548: 
1.778     bisitz   5549: .LC_filename {
                   5550:   font-family: $mono;
                   5551:   white-space:pre;
1.921     bisitz   5552:   font-size: 120%;
1.778     bisitz   5553: }
                   5554: 
                   5555: .LC_fileicon {
                   5556:   border: none;
                   5557:   height: 1.3em;
                   5558:   vertical-align: text-bottom;
                   5559:   margin-right: 0.3em;
                   5560:   text-decoration:none;
                   5561: }
                   5562: 
1.1008    www      5563: .LC_setting {
                   5564:   text-decoration:underline;
                   5565: }
                   5566: 
1.350     albertel 5567: .LC_error {
                   5568:   color: red;
                   5569: }
1.795     www      5570: 
1.1075.2.15  raeburn  5571: .LC_warning {
                   5572:   color: darkorange;
                   5573: }
                   5574: 
1.457     albertel 5575: .LC_diff_removed {
1.733     bisitz   5576:   color: red;
1.394     albertel 5577: }
1.532     albertel 5578: 
                   5579: .LC_info,
1.457     albertel 5580: .LC_success,
                   5581: .LC_diff_added {
1.350     albertel 5582:   color: green;
                   5583: }
1.795     www      5584: 
1.802     bisitz   5585: div.LC_confirm_box {
                   5586:   background-color: #FAFAFA;
                   5587:   border: 1px solid $lg_border_color;
                   5588:   margin-right: 0;
                   5589:   padding: 5px;
                   5590: }
                   5591: 
                   5592: div.LC_confirm_box .LC_error img,
                   5593: div.LC_confirm_box .LC_success img {
                   5594:   vertical-align: middle;
                   5595: }
                   5596: 
1.440     albertel 5597: .LC_icon {
1.771     droeschl 5598:   border: none;
1.790     droeschl 5599:   vertical-align: middle;
1.771     droeschl 5600: }
                   5601: 
1.543     albertel 5602: .LC_docs_spacer {
                   5603:   width: 25px;
                   5604:   height: 1px;
1.771     droeschl 5605:   border: none;
1.543     albertel 5606: }
1.346     albertel 5607: 
1.532     albertel 5608: .LC_internal_info {
1.735     bisitz   5609:   color: #999999;
1.532     albertel 5610: }
                   5611: 
1.794     www      5612: .LC_discussion {
1.1050    www      5613:   background: $data_table_dark;
1.911     bisitz   5614:   border: 1px solid black;
                   5615:   margin: 2px;
1.794     www      5616: }
                   5617: 
                   5618: .LC_disc_action_left {
1.1050    www      5619:   background: $sidebg;
1.911     bisitz   5620:   text-align: left;
1.1050    www      5621:   padding: 4px;
                   5622:   margin: 2px;
1.794     www      5623: }
                   5624: 
                   5625: .LC_disc_action_right {
1.1050    www      5626:   background: $sidebg;
1.911     bisitz   5627:   text-align: right;
1.1050    www      5628:   padding: 4px;
                   5629:   margin: 2px;
1.794     www      5630: }
                   5631: 
                   5632: .LC_disc_new_item {
1.911     bisitz   5633:   background: white;
                   5634:   border: 2px solid red;
1.1050    www      5635:   margin: 4px;
                   5636:   padding: 4px;
1.794     www      5637: }
                   5638: 
                   5639: .LC_disc_old_item {
1.911     bisitz   5640:   background: white;
1.1050    www      5641:   margin: 4px;
                   5642:   padding: 4px;
1.794     www      5643: }
                   5644: 
1.458     albertel 5645: table.LC_pastsubmission {
                   5646:   border: 1px solid black;
                   5647:   margin: 2px;
                   5648: }
                   5649: 
1.924     bisitz   5650: table#LC_menubuttons {
1.345     albertel 5651:   width: 100%;
                   5652:   background: $pgbg;
1.392     albertel 5653:   border: 2px;
1.402     albertel 5654:   border-collapse: separate;
1.803     bisitz   5655:   padding: 0;
1.345     albertel 5656: }
1.392     albertel 5657: 
1.801     tempelho 5658: table#LC_title_bar a {
                   5659:   color: $fontmenu;
                   5660: }
1.836     bisitz   5661: 
1.807     droeschl 5662: table#LC_title_bar {
1.819     tempelho 5663:   clear: both;
1.836     bisitz   5664:   display: none;
1.807     droeschl 5665: }
                   5666: 
1.795     www      5667: table#LC_title_bar,
1.933     droeschl 5668: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5669: table#LC_title_bar.LC_with_remote {
1.359     albertel 5670:   width: 100%;
1.392     albertel 5671:   border-color: $pgbg;
                   5672:   border-style: solid;
                   5673:   border-width: $border;
1.379     albertel 5674:   background: $pgbg;
1.801     tempelho 5675:   color: $fontmenu;
1.392     albertel 5676:   border-collapse: collapse;
1.803     bisitz   5677:   padding: 0;
1.819     tempelho 5678:   margin: 0;
1.359     albertel 5679: }
1.795     www      5680: 
1.933     droeschl 5681: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5682:     margin: 0;
                   5683:     padding: 0;
1.933     droeschl 5684:     position: relative;
                   5685:     list-style: none;
1.913     droeschl 5686: }
1.933     droeschl 5687: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5688:     display: inline;
                   5689: }
1.933     droeschl 5690: 
                   5691: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5692:     padding: 0;
1.933     droeschl 5693:     margin: 0;
                   5694:     float: left;
1.913     droeschl 5695: }
1.933     droeschl 5696: .LC_breadcrumb_tools_tools {
                   5697:     padding: 0;
                   5698:     margin: 0;
1.913     droeschl 5699:     float: right;
                   5700: }
                   5701: 
1.359     albertel 5702: table#LC_title_bar td {
                   5703:   background: $tabbg;
                   5704: }
1.795     www      5705: 
1.911     bisitz   5706: table#LC_menubuttons img {
1.803     bisitz   5707:   border: none;
1.346     albertel 5708: }
1.795     www      5709: 
1.842     droeschl 5710: .LC_breadcrumbs_component {
1.911     bisitz   5711:   float: right;
                   5712:   margin: 0 1em;
1.357     albertel 5713: }
1.842     droeschl 5714: .LC_breadcrumbs_component img {
1.911     bisitz   5715:   vertical-align: middle;
1.777     tempelho 5716: }
1.795     www      5717: 
1.383     albertel 5718: td.LC_table_cell_checkbox {
                   5719:   text-align: center;
                   5720: }
1.795     www      5721: 
                   5722: .LC_fontsize_small {
1.911     bisitz   5723:   font-size: 70%;
1.705     tempelho 5724: }
                   5725: 
1.844     bisitz   5726: #LC_breadcrumbs {
1.911     bisitz   5727:   clear:both;
                   5728:   background: $sidebg;
                   5729:   border-bottom: 1px solid $lg_border_color;
                   5730:   line-height: 2.5em;
1.933     droeschl 5731:   overflow: hidden;
1.911     bisitz   5732:   margin: 0;
                   5733:   padding: 0;
1.995     raeburn  5734:   text-align: left;
1.819     tempelho 5735: }
1.862     bisitz   5736: 
1.1075.2.16  raeburn  5737: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   5738:   clear:both;
                   5739:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 5740:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  5741:   margin: 0 0 10px 0;
1.966     bisitz   5742:   padding: 3px;
1.995     raeburn  5743:   text-align: left;
1.822     bisitz   5744: }
                   5745: 
1.795     www      5746: .LC_fontsize_medium {
1.911     bisitz   5747:   font-size: 85%;
1.705     tempelho 5748: }
                   5749: 
1.795     www      5750: .LC_fontsize_large {
1.911     bisitz   5751:   font-size: 120%;
1.705     tempelho 5752: }
                   5753: 
1.346     albertel 5754: .LC_menubuttons_inline_text {
                   5755:   color: $font;
1.698     harmsja  5756:   font-size: 90%;
1.701     harmsja  5757:   padding-left:3px;
1.346     albertel 5758: }
                   5759: 
1.934     droeschl 5760: .LC_menubuttons_inline_text img{
                   5761:   vertical-align: middle;
                   5762: }
                   5763: 
1.1051    www      5764: li.LC_menubuttons_inline_text img {
1.951     onken    5765:   cursor:pointer;
1.1002    droeschl 5766:   text-decoration: none;
1.951     onken    5767: }
                   5768: 
1.526     www      5769: .LC_menubuttons_link {
                   5770:   text-decoration: none;
                   5771: }
1.795     www      5772: 
1.522     albertel 5773: .LC_menubuttons_category {
1.521     www      5774:   color: $font;
1.526     www      5775:   background: $pgbg;
1.521     www      5776:   font-size: larger;
                   5777:   font-weight: bold;
                   5778: }
                   5779: 
1.346     albertel 5780: td.LC_menubuttons_text {
1.911     bisitz   5781:   color: $font;
1.346     albertel 5782: }
1.706     harmsja  5783: 
1.346     albertel 5784: .LC_current_location {
                   5785:   background: $tabbg;
                   5786: }
1.795     www      5787: 
1.938     bisitz   5788: table.LC_data_table {
1.347     albertel 5789:   border: 1px solid #000000;
1.402     albertel 5790:   border-collapse: separate;
1.426     albertel 5791:   border-spacing: 1px;
1.610     albertel 5792:   background: $pgbg;
1.347     albertel 5793: }
1.795     www      5794: 
1.422     albertel 5795: .LC_data_table_dense {
                   5796:   font-size: small;
                   5797: }
1.795     www      5798: 
1.507     raeburn  5799: table.LC_nested_outer {
                   5800:   border: 1px solid #000000;
1.589     raeburn  5801:   border-collapse: collapse;
1.803     bisitz   5802:   border-spacing: 0;
1.507     raeburn  5803:   width: 100%;
                   5804: }
1.795     www      5805: 
1.879     raeburn  5806: table.LC_innerpickbox,
1.507     raeburn  5807: table.LC_nested {
1.803     bisitz   5808:   border: none;
1.589     raeburn  5809:   border-collapse: collapse;
1.803     bisitz   5810:   border-spacing: 0;
1.507     raeburn  5811:   width: 100%;
                   5812: }
1.795     www      5813: 
1.911     bisitz   5814: table.LC_data_table tr th,
                   5815: table.LC_calendar tr th,
1.879     raeburn  5816: table.LC_prior_tries tr th,
                   5817: table.LC_innerpickbox tr th {
1.349     albertel 5818:   font-weight: bold;
                   5819:   background-color: $data_table_head;
1.801     tempelho 5820:   color:$fontmenu;
1.701     harmsja  5821:   font-size:90%;
1.347     albertel 5822: }
1.795     www      5823: 
1.879     raeburn  5824: table.LC_innerpickbox tr th,
                   5825: table.LC_innerpickbox tr td {
                   5826:   vertical-align: top;
                   5827: }
                   5828: 
1.711     raeburn  5829: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   5830:   background-color: #CCCCCC;
1.711     raeburn  5831:   font-weight: bold;
                   5832:   text-align: left;
                   5833: }
1.795     www      5834: 
1.912     bisitz   5835: table.LC_data_table tr.LC_odd_row > td {
                   5836:   background-color: $data_table_light;
                   5837:   padding: 2px;
                   5838:   vertical-align: top;
                   5839: }
                   5840: 
1.809     bisitz   5841: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 5842:   background-color: $data_table_light;
1.912     bisitz   5843:   vertical-align: top;
                   5844: }
                   5845: 
                   5846: table.LC_data_table tr.LC_even_row > td {
                   5847:   background-color: $data_table_dark;
1.425     albertel 5848:   padding: 2px;
1.900     bisitz   5849:   vertical-align: top;
1.347     albertel 5850: }
1.795     www      5851: 
1.809     bisitz   5852: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 5853:   background-color: $data_table_dark;
1.900     bisitz   5854:   vertical-align: top;
1.347     albertel 5855: }
1.795     www      5856: 
1.425     albertel 5857: table.LC_data_table tr.LC_data_table_highlight td {
                   5858:   background-color: $data_table_darker;
                   5859: }
1.795     www      5860: 
1.639     raeburn  5861: table.LC_data_table tr td.LC_leftcol_header {
                   5862:   background-color: $data_table_head;
                   5863:   font-weight: bold;
                   5864: }
1.795     www      5865: 
1.451     albertel 5866: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  5867: table.LC_nested tr.LC_empty_row td {
1.421     albertel 5868:   font-weight: bold;
                   5869:   font-style: italic;
                   5870:   text-align: center;
                   5871:   padding: 8px;
1.347     albertel 5872: }
1.795     www      5873: 
1.1075.2.30  raeburn  5874: table.LC_data_table tr.LC_empty_row td,
                   5875: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   5876:   background-color: $sidebg;
                   5877: }
                   5878: 
                   5879: table.LC_nested tr.LC_empty_row td {
                   5880:   background-color: #FFFFFF;
                   5881: }
                   5882: 
1.890     droeschl 5883: table.LC_caption {
                   5884: }
                   5885: 
1.507     raeburn  5886: table.LC_nested tr.LC_empty_row td {
1.465     albertel 5887:   padding: 4ex
                   5888: }
1.795     www      5889: 
1.507     raeburn  5890: table.LC_nested_outer tr th {
                   5891:   font-weight: bold;
1.801     tempelho 5892:   color:$fontmenu;
1.507     raeburn  5893:   background-color: $data_table_head;
1.701     harmsja  5894:   font-size: small;
1.507     raeburn  5895:   border-bottom: 1px solid #000000;
                   5896: }
1.795     www      5897: 
1.507     raeburn  5898: table.LC_nested_outer tr td.LC_subheader {
                   5899:   background-color: $data_table_head;
                   5900:   font-weight: bold;
                   5901:   font-size: small;
                   5902:   border-bottom: 1px solid #000000;
                   5903:   text-align: right;
1.451     albertel 5904: }
1.795     www      5905: 
1.507     raeburn  5906: table.LC_nested tr.LC_info_row td {
1.735     bisitz   5907:   background-color: #CCCCCC;
1.451     albertel 5908:   font-weight: bold;
                   5909:   font-size: small;
1.507     raeburn  5910:   text-align: center;
                   5911: }
1.795     www      5912: 
1.589     raeburn  5913: table.LC_nested tr.LC_info_row td.LC_left_item,
                   5914: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  5915:   text-align: left;
1.451     albertel 5916: }
1.795     www      5917: 
1.507     raeburn  5918: table.LC_nested td {
1.735     bisitz   5919:   background-color: #FFFFFF;
1.451     albertel 5920:   font-size: small;
1.507     raeburn  5921: }
1.795     www      5922: 
1.507     raeburn  5923: table.LC_nested_outer tr th.LC_right_item,
                   5924: table.LC_nested tr.LC_info_row td.LC_right_item,
                   5925: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   5926: table.LC_nested tr td.LC_right_item {
1.451     albertel 5927:   text-align: right;
                   5928: }
                   5929: 
1.507     raeburn  5930: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   5931:   background-color: #EEEEEE;
1.451     albertel 5932: }
                   5933: 
1.473     raeburn  5934: table.LC_createuser {
                   5935: }
                   5936: 
                   5937: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  5938:   font-size: small;
1.473     raeburn  5939: }
                   5940: 
                   5941: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   5942:   background-color: #CCCCCC;
1.473     raeburn  5943:   font-weight: bold;
                   5944:   text-align: center;
                   5945: }
                   5946: 
1.349     albertel 5947: table.LC_calendar {
                   5948:   border: 1px solid #000000;
                   5949:   border-collapse: collapse;
1.917     raeburn  5950:   width: 98%;
1.349     albertel 5951: }
1.795     www      5952: 
1.349     albertel 5953: table.LC_calendar_pickdate {
                   5954:   font-size: xx-small;
                   5955: }
1.795     www      5956: 
1.349     albertel 5957: table.LC_calendar tr td {
                   5958:   border: 1px solid #000000;
                   5959:   vertical-align: top;
1.917     raeburn  5960:   width: 14%;
1.349     albertel 5961: }
1.795     www      5962: 
1.349     albertel 5963: table.LC_calendar tr td.LC_calendar_day_empty {
                   5964:   background-color: $data_table_dark;
                   5965: }
1.795     www      5966: 
1.779     bisitz   5967: table.LC_calendar tr td.LC_calendar_day_current {
                   5968:   background-color: $data_table_highlight;
1.777     tempelho 5969: }
1.795     www      5970: 
1.938     bisitz   5971: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 5972:   background-color: $mail_new;
                   5973: }
1.795     www      5974: 
1.938     bisitz   5975: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 5976:   background-color: $mail_new_hover;
                   5977: }
1.795     www      5978: 
1.938     bisitz   5979: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 5980:   background-color: $mail_read;
                   5981: }
1.795     www      5982: 
1.938     bisitz   5983: /*
                   5984: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 5985:   background-color: $mail_read_hover;
                   5986: }
1.938     bisitz   5987: */
1.795     www      5988: 
1.938     bisitz   5989: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 5990:   background-color: $mail_replied;
                   5991: }
1.795     www      5992: 
1.938     bisitz   5993: /*
                   5994: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 5995:   background-color: $mail_replied_hover;
                   5996: }
1.938     bisitz   5997: */
1.795     www      5998: 
1.938     bisitz   5999: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6000:   background-color: $mail_other;
                   6001: }
1.795     www      6002: 
1.938     bisitz   6003: /*
                   6004: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6005:   background-color: $mail_other_hover;
                   6006: }
1.938     bisitz   6007: */
1.494     raeburn  6008: 
1.777     tempelho 6009: table.LC_data_table tr > td.LC_browser_file,
                   6010: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6011:   background: #AAEE77;
1.389     albertel 6012: }
1.795     www      6013: 
1.777     tempelho 6014: table.LC_data_table tr > td.LC_browser_file_locked,
                   6015: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6016:   background: #FFAA99;
1.387     albertel 6017: }
1.795     www      6018: 
1.777     tempelho 6019: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6020:   background: #888888;
1.779     bisitz   6021: }
1.795     www      6022: 
1.777     tempelho 6023: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6024: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6025:   background: #F8F866;
1.777     tempelho 6026: }
1.795     www      6027: 
1.696     bisitz   6028: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6029:   background: #E0E8FF;
1.387     albertel 6030: }
1.696     bisitz   6031: 
1.707     bisitz   6032: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6033:   /* background: #77FF77; */
1.707     bisitz   6034: }
1.795     www      6035: 
1.707     bisitz   6036: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6037:   border-right: 8px solid #FFFF77;
1.707     bisitz   6038: }
1.795     www      6039: 
1.707     bisitz   6040: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6041:   border-right: 8px solid #FFAA77;
1.707     bisitz   6042: }
1.795     www      6043: 
1.707     bisitz   6044: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6045:   border-right: 8px solid #FF7777;
1.707     bisitz   6046: }
1.795     www      6047: 
1.707     bisitz   6048: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6049:   border-right: 8px solid #AAFF77;
1.707     bisitz   6050: }
1.795     www      6051: 
1.707     bisitz   6052: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6053:   border-right: 8px solid #11CC55;
1.707     bisitz   6054: }
                   6055: 
1.388     albertel 6056: span.LC_current_location {
1.701     harmsja  6057:   font-size:larger;
1.388     albertel 6058:   background: $pgbg;
                   6059: }
1.387     albertel 6060: 
1.1029    www      6061: span.LC_current_nav_location {
                   6062:   font-weight:bold;
                   6063:   background: $sidebg;
                   6064: }
                   6065: 
1.395     albertel 6066: span.LC_parm_menu_item {
                   6067:   font-size: larger;
                   6068: }
1.795     www      6069: 
1.395     albertel 6070: span.LC_parm_scope_all {
                   6071:   color: red;
                   6072: }
1.795     www      6073: 
1.395     albertel 6074: span.LC_parm_scope_folder {
                   6075:   color: green;
                   6076: }
1.795     www      6077: 
1.395     albertel 6078: span.LC_parm_scope_resource {
                   6079:   color: orange;
                   6080: }
1.795     www      6081: 
1.395     albertel 6082: span.LC_parm_part {
                   6083:   color: blue;
                   6084: }
1.795     www      6085: 
1.911     bisitz   6086: span.LC_parm_folder,
                   6087: span.LC_parm_symb {
1.395     albertel 6088:   font-size: x-small;
                   6089:   font-family: $mono;
                   6090:   color: #AAAAAA;
                   6091: }
                   6092: 
1.977     bisitz   6093: ul.LC_parm_parmlist li {
                   6094:   display: inline-block;
                   6095:   padding: 0.3em 0.8em;
                   6096:   vertical-align: top;
                   6097:   width: 150px;
                   6098:   border-top:1px solid $lg_border_color;
                   6099: }
                   6100: 
1.795     www      6101: td.LC_parm_overview_level_menu,
                   6102: td.LC_parm_overview_map_menu,
                   6103: td.LC_parm_overview_parm_selectors,
                   6104: td.LC_parm_overview_restrictions  {
1.396     albertel 6105:   border: 1px solid black;
                   6106:   border-collapse: collapse;
                   6107: }
1.795     www      6108: 
1.396     albertel 6109: table.LC_parm_overview_restrictions td {
                   6110:   border-width: 1px 4px 1px 4px;
                   6111:   border-style: solid;
                   6112:   border-color: $pgbg;
                   6113:   text-align: center;
                   6114: }
1.795     www      6115: 
1.396     albertel 6116: table.LC_parm_overview_restrictions th {
                   6117:   background: $tabbg;
                   6118:   border-width: 1px 4px 1px 4px;
                   6119:   border-style: solid;
                   6120:   border-color: $pgbg;
                   6121: }
1.795     www      6122: 
1.398     albertel 6123: table#LC_helpmenu {
1.803     bisitz   6124:   border: none;
1.398     albertel 6125:   height: 55px;
1.803     bisitz   6126:   border-spacing: 0;
1.398     albertel 6127: }
                   6128: 
                   6129: table#LC_helpmenu fieldset legend {
                   6130:   font-size: larger;
                   6131: }
1.795     www      6132: 
1.397     albertel 6133: table#LC_helpmenu_links {
                   6134:   width: 100%;
                   6135:   border: 1px solid black;
                   6136:   background: $pgbg;
1.803     bisitz   6137:   padding: 0;
1.397     albertel 6138:   border-spacing: 1px;
                   6139: }
1.795     www      6140: 
1.397     albertel 6141: table#LC_helpmenu_links tr td {
                   6142:   padding: 1px;
                   6143:   background: $tabbg;
1.399     albertel 6144:   text-align: center;
                   6145:   font-weight: bold;
1.397     albertel 6146: }
1.396     albertel 6147: 
1.795     www      6148: table#LC_helpmenu_links a:link,
                   6149: table#LC_helpmenu_links a:visited,
1.397     albertel 6150: table#LC_helpmenu_links a:active {
                   6151:   text-decoration: none;
                   6152:   color: $font;
                   6153: }
1.795     www      6154: 
1.397     albertel 6155: table#LC_helpmenu_links a:hover {
                   6156:   text-decoration: underline;
                   6157:   color: $vlink;
                   6158: }
1.396     albertel 6159: 
1.417     albertel 6160: .LC_chrt_popup_exists {
                   6161:   border: 1px solid #339933;
                   6162:   margin: -1px;
                   6163: }
1.795     www      6164: 
1.417     albertel 6165: .LC_chrt_popup_up {
                   6166:   border: 1px solid yellow;
                   6167:   margin: -1px;
                   6168: }
1.795     www      6169: 
1.417     albertel 6170: .LC_chrt_popup {
                   6171:   border: 1px solid #8888FF;
                   6172:   background: #CCCCFF;
                   6173: }
1.795     www      6174: 
1.421     albertel 6175: table.LC_pick_box {
                   6176:   border-collapse: separate;
                   6177:   background: white;
                   6178:   border: 1px solid black;
                   6179:   border-spacing: 1px;
                   6180: }
1.795     www      6181: 
1.421     albertel 6182: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6183:   background: $sidebg;
1.421     albertel 6184:   font-weight: bold;
1.900     bisitz   6185:   text-align: left;
1.740     bisitz   6186:   vertical-align: top;
1.421     albertel 6187:   width: 184px;
                   6188:   padding: 8px;
                   6189: }
1.795     www      6190: 
1.579     raeburn  6191: table.LC_pick_box td.LC_pick_box_value {
                   6192:   text-align: left;
                   6193:   padding: 8px;
                   6194: }
1.795     www      6195: 
1.579     raeburn  6196: table.LC_pick_box td.LC_pick_box_select {
                   6197:   text-align: left;
                   6198:   padding: 8px;
                   6199: }
1.795     www      6200: 
1.424     albertel 6201: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6202:   padding: 0;
1.421     albertel 6203:   height: 1px;
                   6204:   background: black;
                   6205: }
1.795     www      6206: 
1.421     albertel 6207: table.LC_pick_box td.LC_pick_box_submit {
                   6208:   text-align: right;
                   6209: }
1.795     www      6210: 
1.579     raeburn  6211: table.LC_pick_box td.LC_evenrow_value {
                   6212:   text-align: left;
                   6213:   padding: 8px;
                   6214:   background-color: $data_table_light;
                   6215: }
1.795     www      6216: 
1.579     raeburn  6217: table.LC_pick_box td.LC_oddrow_value {
                   6218:   text-align: left;
                   6219:   padding: 8px;
                   6220:   background-color: $data_table_light;
                   6221: }
1.795     www      6222: 
1.579     raeburn  6223: span.LC_helpform_receipt_cat {
                   6224:   font-weight: bold;
                   6225: }
1.795     www      6226: 
1.424     albertel 6227: table.LC_group_priv_box {
                   6228:   background: white;
                   6229:   border: 1px solid black;
                   6230:   border-spacing: 1px;
                   6231: }
1.795     www      6232: 
1.424     albertel 6233: table.LC_group_priv_box td.LC_pick_box_title {
                   6234:   background: $tabbg;
                   6235:   font-weight: bold;
                   6236:   text-align: right;
                   6237:   width: 184px;
                   6238: }
1.795     www      6239: 
1.424     albertel 6240: table.LC_group_priv_box td.LC_groups_fixed {
                   6241:   background: $data_table_light;
                   6242:   text-align: center;
                   6243: }
1.795     www      6244: 
1.424     albertel 6245: table.LC_group_priv_box td.LC_groups_optional {
                   6246:   background: $data_table_dark;
                   6247:   text-align: center;
                   6248: }
1.795     www      6249: 
1.424     albertel 6250: table.LC_group_priv_box td.LC_groups_functionality {
                   6251:   background: $data_table_darker;
                   6252:   text-align: center;
                   6253:   font-weight: bold;
                   6254: }
1.795     www      6255: 
1.424     albertel 6256: table.LC_group_priv td {
                   6257:   text-align: left;
1.803     bisitz   6258:   padding: 0;
1.424     albertel 6259: }
                   6260: 
                   6261: .LC_navbuttons {
                   6262:   margin: 2ex 0ex 2ex 0ex;
                   6263: }
1.795     www      6264: 
1.423     albertel 6265: .LC_topic_bar {
                   6266:   font-weight: bold;
                   6267:   background: $tabbg;
1.918     wenzelju 6268:   margin: 1em 0em 1em 2em;
1.805     bisitz   6269:   padding: 3px;
1.918     wenzelju 6270:   font-size: 1.2em;
1.423     albertel 6271: }
1.795     www      6272: 
1.423     albertel 6273: .LC_topic_bar span {
1.918     wenzelju 6274:   left: 0.5em;
                   6275:   position: absolute;
1.423     albertel 6276:   vertical-align: middle;
1.918     wenzelju 6277:   font-size: 1.2em;
1.423     albertel 6278: }
1.795     www      6279: 
1.423     albertel 6280: table.LC_course_group_status {
                   6281:   margin: 20px;
                   6282: }
1.795     www      6283: 
1.423     albertel 6284: table.LC_status_selector td {
                   6285:   vertical-align: top;
                   6286:   text-align: center;
1.424     albertel 6287:   padding: 4px;
                   6288: }
1.795     www      6289: 
1.599     albertel 6290: div.LC_feedback_link {
1.616     albertel 6291:   clear: both;
1.829     kalberla 6292:   background: $sidebg;
1.779     bisitz   6293:   width: 100%;
1.829     kalberla 6294:   padding-bottom: 10px;
                   6295:   border: 1px $tabbg solid;
1.833     kalberla 6296:   height: 22px;
                   6297:   line-height: 22px;
                   6298:   padding-top: 5px;
                   6299: }
                   6300: 
                   6301: div.LC_feedback_link img {
                   6302:   height: 22px;
1.867     kalberla 6303:   vertical-align:middle;
1.829     kalberla 6304: }
                   6305: 
1.911     bisitz   6306: div.LC_feedback_link a {
1.829     kalberla 6307:   text-decoration: none;
1.489     raeburn  6308: }
1.795     www      6309: 
1.867     kalberla 6310: div.LC_comblock {
1.911     bisitz   6311:   display:inline;
1.867     kalberla 6312:   color:$font;
                   6313:   font-size:90%;
                   6314: }
                   6315: 
                   6316: div.LC_feedback_link div.LC_comblock {
                   6317:   padding-left:5px;
                   6318: }
                   6319: 
                   6320: div.LC_feedback_link div.LC_comblock a {
                   6321:   color:$font;
                   6322: }
                   6323: 
1.489     raeburn  6324: span.LC_feedback_link {
1.858     bisitz   6325:   /* background: $feedback_link_bg; */
1.599     albertel 6326:   font-size: larger;
                   6327: }
1.795     www      6328: 
1.599     albertel 6329: span.LC_message_link {
1.858     bisitz   6330:   /* background: $feedback_link_bg; */
1.599     albertel 6331:   font-size: larger;
                   6332:   position: absolute;
                   6333:   right: 1em;
1.489     raeburn  6334: }
1.421     albertel 6335: 
1.515     albertel 6336: table.LC_prior_tries {
1.524     albertel 6337:   border: 1px solid #000000;
                   6338:   border-collapse: separate;
                   6339:   border-spacing: 1px;
1.515     albertel 6340: }
1.523     albertel 6341: 
1.515     albertel 6342: table.LC_prior_tries td {
1.524     albertel 6343:   padding: 2px;
1.515     albertel 6344: }
1.523     albertel 6345: 
                   6346: .LC_answer_correct {
1.795     www      6347:   background: lightgreen;
                   6348:   color: darkgreen;
                   6349:   padding: 6px;
1.523     albertel 6350: }
1.795     www      6351: 
1.523     albertel 6352: .LC_answer_charged_try {
1.797     www      6353:   background: #FFAAAA;
1.795     www      6354:   color: darkred;
                   6355:   padding: 6px;
1.523     albertel 6356: }
1.795     www      6357: 
1.779     bisitz   6358: .LC_answer_not_charged_try,
1.523     albertel 6359: .LC_answer_no_grade,
                   6360: .LC_answer_late {
1.795     www      6361:   background: lightyellow;
1.523     albertel 6362:   color: black;
1.795     www      6363:   padding: 6px;
1.523     albertel 6364: }
1.795     www      6365: 
1.523     albertel 6366: .LC_answer_previous {
1.795     www      6367:   background: lightblue;
                   6368:   color: darkblue;
                   6369:   padding: 6px;
1.523     albertel 6370: }
1.795     www      6371: 
1.779     bisitz   6372: .LC_answer_no_message {
1.777     tempelho 6373:   background: #FFFFFF;
                   6374:   color: black;
1.795     www      6375:   padding: 6px;
1.779     bisitz   6376: }
1.795     www      6377: 
1.779     bisitz   6378: .LC_answer_unknown {
                   6379:   background: orange;
                   6380:   color: black;
1.795     www      6381:   padding: 6px;
1.777     tempelho 6382: }
1.795     www      6383: 
1.529     albertel 6384: span.LC_prior_numerical,
                   6385: span.LC_prior_string,
                   6386: span.LC_prior_custom,
                   6387: span.LC_prior_reaction,
                   6388: span.LC_prior_math {
1.925     bisitz   6389:   font-family: $mono;
1.523     albertel 6390:   white-space: pre;
                   6391: }
                   6392: 
1.525     albertel 6393: span.LC_prior_string {
1.925     bisitz   6394:   font-family: $mono;
1.525     albertel 6395:   white-space: pre;
                   6396: }
                   6397: 
1.523     albertel 6398: table.LC_prior_option {
                   6399:   width: 100%;
                   6400:   border-collapse: collapse;
                   6401: }
1.795     www      6402: 
1.911     bisitz   6403: table.LC_prior_rank,
1.795     www      6404: table.LC_prior_match {
1.528     albertel 6405:   border-collapse: collapse;
                   6406: }
1.795     www      6407: 
1.528     albertel 6408: table.LC_prior_option tr td,
                   6409: table.LC_prior_rank tr td,
                   6410: table.LC_prior_match tr td {
1.524     albertel 6411:   border: 1px solid #000000;
1.515     albertel 6412: }
                   6413: 
1.855     bisitz   6414: .LC_nobreak {
1.544     albertel 6415:   white-space: nowrap;
1.519     raeburn  6416: }
                   6417: 
1.576     raeburn  6418: span.LC_cusr_emph {
                   6419:   font-style: italic;
                   6420: }
                   6421: 
1.633     raeburn  6422: span.LC_cusr_subheading {
                   6423:   font-weight: normal;
                   6424:   font-size: 85%;
                   6425: }
                   6426: 
1.861     bisitz   6427: div.LC_docs_entry_move {
1.859     bisitz   6428:   border: 1px solid #BBBBBB;
1.545     albertel 6429:   background: #DDDDDD;
1.861     bisitz   6430:   width: 22px;
1.859     bisitz   6431:   padding: 1px;
                   6432:   margin: 0;
1.545     albertel 6433: }
                   6434: 
1.861     bisitz   6435: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6436: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6437:   font-size: x-small;
                   6438: }
1.795     www      6439: 
1.861     bisitz   6440: .LC_docs_entry_parameter {
                   6441:   white-space: nowrap;
                   6442: }
                   6443: 
1.544     albertel 6444: .LC_docs_copy {
1.545     albertel 6445:   color: #000099;
1.544     albertel 6446: }
1.795     www      6447: 
1.544     albertel 6448: .LC_docs_cut {
1.545     albertel 6449:   color: #550044;
1.544     albertel 6450: }
1.795     www      6451: 
1.544     albertel 6452: .LC_docs_rename {
1.545     albertel 6453:   color: #009900;
1.544     albertel 6454: }
1.795     www      6455: 
1.544     albertel 6456: .LC_docs_remove {
1.545     albertel 6457:   color: #990000;
                   6458: }
                   6459: 
1.547     albertel 6460: .LC_docs_reinit_warn,
                   6461: .LC_docs_ext_edit {
                   6462:   font-size: x-small;
                   6463: }
                   6464: 
1.545     albertel 6465: table.LC_docs_adddocs td,
                   6466: table.LC_docs_adddocs th {
                   6467:   border: 1px solid #BBBBBB;
                   6468:   padding: 4px;
                   6469:   background: #DDDDDD;
1.543     albertel 6470: }
                   6471: 
1.584     albertel 6472: table.LC_sty_begin {
                   6473:   background: #BBFFBB;
                   6474: }
1.795     www      6475: 
1.584     albertel 6476: table.LC_sty_end {
                   6477:   background: #FFBBBB;
                   6478: }
                   6479: 
1.589     raeburn  6480: table.LC_double_column {
1.803     bisitz   6481:   border-width: 0;
1.589     raeburn  6482:   border-collapse: collapse;
                   6483:   width: 100%;
                   6484:   padding: 2px;
                   6485: }
                   6486: 
                   6487: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6488:   top: 2px;
1.589     raeburn  6489:   left: 2px;
                   6490:   width: 47%;
                   6491:   vertical-align: top;
                   6492: }
                   6493: 
                   6494: table.LC_double_column tr td.LC_right_col {
                   6495:   top: 2px;
1.779     bisitz   6496:   right: 2px;
1.589     raeburn  6497:   width: 47%;
                   6498:   vertical-align: top;
                   6499: }
                   6500: 
1.591     raeburn  6501: div.LC_left_float {
                   6502:   float: left;
                   6503:   padding-right: 5%;
1.597     albertel 6504:   padding-bottom: 4px;
1.591     raeburn  6505: }
                   6506: 
                   6507: div.LC_clear_float_header {
1.597     albertel 6508:   padding-bottom: 2px;
1.591     raeburn  6509: }
                   6510: 
                   6511: div.LC_clear_float_footer {
1.597     albertel 6512:   padding-top: 10px;
1.591     raeburn  6513:   clear: both;
                   6514: }
                   6515: 
1.597     albertel 6516: div.LC_grade_show_user {
1.941     bisitz   6517: /*  border-left: 5px solid $sidebg; */
                   6518:   border-top: 5px solid #000000;
                   6519:   margin: 50px 0 0 0;
1.936     bisitz   6520:   padding: 15px 0 5px 10px;
1.597     albertel 6521: }
1.795     www      6522: 
1.936     bisitz   6523: div.LC_grade_show_user_odd_row {
1.941     bisitz   6524: /*  border-left: 5px solid #000000; */
                   6525: }
                   6526: 
                   6527: div.LC_grade_show_user div.LC_Box {
                   6528:   margin-right: 50px;
1.597     albertel 6529: }
                   6530: 
                   6531: div.LC_grade_submissions,
                   6532: div.LC_grade_message_center,
1.936     bisitz   6533: div.LC_grade_info_links {
1.597     albertel 6534:   margin: 5px;
                   6535:   width: 99%;
                   6536:   background: #FFFFFF;
                   6537: }
1.795     www      6538: 
1.597     albertel 6539: div.LC_grade_submissions_header,
1.936     bisitz   6540: div.LC_grade_message_center_header {
1.705     tempelho 6541:   font-weight: bold;
                   6542:   font-size: large;
1.597     albertel 6543: }
1.795     www      6544: 
1.597     albertel 6545: div.LC_grade_submissions_body,
1.936     bisitz   6546: div.LC_grade_message_center_body {
1.597     albertel 6547:   border: 1px solid black;
                   6548:   width: 99%;
                   6549:   background: #FFFFFF;
                   6550: }
1.795     www      6551: 
1.613     albertel 6552: table.LC_scantron_action {
                   6553:   width: 100%;
                   6554: }
1.795     www      6555: 
1.613     albertel 6556: table.LC_scantron_action tr th {
1.698     harmsja  6557:   font-weight:bold;
                   6558:   font-style:normal;
1.613     albertel 6559: }
1.795     www      6560: 
1.779     bisitz   6561: .LC_edit_problem_header,
1.614     albertel 6562: div.LC_edit_problem_footer {
1.705     tempelho 6563:   font-weight: normal;
                   6564:   font-size:  medium;
1.602     albertel 6565:   margin: 2px;
1.1060    bisitz   6566:   background-color: $sidebg;
1.600     albertel 6567: }
1.795     www      6568: 
1.600     albertel 6569: div.LC_edit_problem_header,
1.602     albertel 6570: div.LC_edit_problem_header div,
1.614     albertel 6571: div.LC_edit_problem_footer,
                   6572: div.LC_edit_problem_footer div,
1.602     albertel 6573: div.LC_edit_problem_editxml_header,
                   6574: div.LC_edit_problem_editxml_header div {
1.600     albertel 6575:   margin-top: 5px;
                   6576: }
1.795     www      6577: 
1.600     albertel 6578: div.LC_edit_problem_header_title {
1.705     tempelho 6579:   font-weight: bold;
                   6580:   font-size: larger;
1.602     albertel 6581:   background: $tabbg;
                   6582:   padding: 3px;
1.1060    bisitz   6583:   margin: 0 0 5px 0;
1.602     albertel 6584: }
1.795     www      6585: 
1.602     albertel 6586: table.LC_edit_problem_header_title {
                   6587:   width: 100%;
1.600     albertel 6588:   background: $tabbg;
1.602     albertel 6589: }
                   6590: 
                   6591: div.LC_edit_problem_discards {
                   6592:   float: left;
                   6593:   padding-bottom: 5px;
                   6594: }
1.795     www      6595: 
1.602     albertel 6596: div.LC_edit_problem_saves {
                   6597:   float: right;
                   6598:   padding-bottom: 5px;
1.600     albertel 6599: }
1.795     www      6600: 
1.1075.2.34  raeburn  6601: .LC_edit_opt {
                   6602:   padding-left: 1em;
                   6603:   white-space: nowrap;
                   6604: }
                   6605: 
1.1075.2.57  raeburn  6606: .LC_edit_problem_latexhelper{
                   6607:     text-align: right;
                   6608: }
                   6609: 
                   6610: #LC_edit_problem_colorful div{
                   6611:     margin-left: 40px;
                   6612: }
                   6613: 
1.911     bisitz   6614: img.stift {
1.803     bisitz   6615:   border-width: 0;
                   6616:   vertical-align: middle;
1.677     riegler  6617: }
1.680     riegler  6618: 
1.923     bisitz   6619: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6620:   vertical-align: top;
1.777     tempelho 6621: }
1.795     www      6622: 
1.716     raeburn  6623: div.LC_createcourse {
1.911     bisitz   6624:   margin: 10px 10px 10px 10px;
1.716     raeburn  6625: }
                   6626: 
1.917     raeburn  6627: .LC_dccid {
1.1075.2.38  raeburn  6628:   float: right;
1.917     raeburn  6629:   margin: 0.2em 0 0 0;
                   6630:   padding: 0;
                   6631:   font-size: 90%;
                   6632:   display:none;
                   6633: }
                   6634: 
1.897     wenzelju 6635: ol.LC_primary_menu a:hover,
1.721     harmsja  6636: ol#LC_MenuBreadcrumbs a:hover,
                   6637: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6638: ul#LC_secondary_menu a:hover,
1.721     harmsja  6639: .LC_FormSectionClearButton input:hover
1.795     www      6640: ul.LC_TabContent   li:hover a {
1.952     onken    6641:   color:$button_hover;
1.911     bisitz   6642:   text-decoration:none;
1.693     droeschl 6643: }
                   6644: 
1.779     bisitz   6645: h1 {
1.911     bisitz   6646:   padding: 0;
                   6647:   line-height:130%;
1.693     droeschl 6648: }
1.698     harmsja  6649: 
1.911     bisitz   6650: h2,
                   6651: h3,
                   6652: h4,
                   6653: h5,
                   6654: h6 {
                   6655:   margin: 5px 0 5px 0;
                   6656:   padding: 0;
                   6657:   line-height:130%;
1.693     droeschl 6658: }
1.795     www      6659: 
                   6660: .LC_hcell {
1.911     bisitz   6661:   padding:3px 15px 3px 15px;
                   6662:   margin: 0;
                   6663:   background-color:$tabbg;
                   6664:   color:$fontmenu;
                   6665:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6666: }
1.795     www      6667: 
1.840     bisitz   6668: .LC_Box > .LC_hcell {
1.911     bisitz   6669:   margin: 0 -10px 10px -10px;
1.835     bisitz   6670: }
                   6671: 
1.721     harmsja  6672: .LC_noBorder {
1.911     bisitz   6673:   border: 0;
1.698     harmsja  6674: }
1.693     droeschl 6675: 
1.721     harmsja  6676: .LC_FormSectionClearButton input {
1.911     bisitz   6677:   background-color:transparent;
                   6678:   border: none;
                   6679:   cursor:pointer;
                   6680:   text-decoration:underline;
1.693     droeschl 6681: }
1.763     bisitz   6682: 
                   6683: .LC_help_open_topic {
1.911     bisitz   6684:   color: #FFFFFF;
                   6685:   background-color: #EEEEFF;
                   6686:   margin: 1px;
                   6687:   padding: 4px;
                   6688:   border: 1px solid #000033;
                   6689:   white-space: nowrap;
                   6690:   /* vertical-align: middle; */
1.759     neumanie 6691: }
1.693     droeschl 6692: 
1.911     bisitz   6693: dl,
                   6694: ul,
                   6695: div,
                   6696: fieldset {
                   6697:   margin: 10px 10px 10px 0;
                   6698:   /* overflow: hidden; */
1.693     droeschl 6699: }
1.795     www      6700: 
1.1075.2.90  raeburn  6701: article.geogebraweb div {
                   6702:     margin: 0;
                   6703: }
                   6704: 
1.838     bisitz   6705: fieldset > legend {
1.911     bisitz   6706:   font-weight: bold;
                   6707:   padding: 0 5px 0 5px;
1.838     bisitz   6708: }
                   6709: 
1.813     bisitz   6710: #LC_nav_bar {
1.911     bisitz   6711:   float: left;
1.995     raeburn  6712:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   6713:   margin: 0 0 2px 0;
1.807     droeschl 6714: }
                   6715: 
1.916     droeschl 6716: #LC_realm {
                   6717:   margin: 0.2em 0 0 0;
                   6718:   padding: 0;
                   6719:   font-weight: bold;
                   6720:   text-align: center;
1.995     raeburn  6721:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 6722: }
                   6723: 
1.911     bisitz   6724: #LC_nav_bar em {
                   6725:   font-weight: bold;
                   6726:   font-style: normal;
1.807     droeschl 6727: }
                   6728: 
1.897     wenzelju 6729: ol.LC_primary_menu {
1.934     droeschl 6730:   margin: 0;
1.1075.2.2  raeburn  6731:   padding: 0;
1.995     raeburn  6732:   background-color: $pgbg_or_bgcolor;
1.807     droeschl 6733: }
                   6734: 
1.852     droeschl 6735: ol#LC_PathBreadcrumbs {
1.911     bisitz   6736:   margin: 0;
1.693     droeschl 6737: }
                   6738: 
1.897     wenzelju 6739: ol.LC_primary_menu li {
1.1075.2.2  raeburn  6740:   color: RGB(80, 80, 80);
                   6741:   vertical-align: middle;
                   6742:   text-align: left;
                   6743:   list-style: none;
                   6744:   float: left;
                   6745: }
                   6746: 
                   6747: ol.LC_primary_menu li a {
                   6748:   display: block;
                   6749:   margin: 0;
                   6750:   padding: 0 5px 0 10px;
                   6751:   text-decoration: none;
                   6752: }
                   6753: 
                   6754: ol.LC_primary_menu li ul {
                   6755:   display: none;
                   6756:   width: 10em;
                   6757:   background-color: $data_table_light;
                   6758: }
                   6759: 
                   6760: ol.LC_primary_menu li:hover ul, ol.LC_primary_menu li.hover ul {
                   6761:   display: block;
                   6762:   position: absolute;
                   6763:   margin: 0;
                   6764:   padding: 0;
1.1075.2.5  raeburn  6765:   z-index: 2;
1.1075.2.2  raeburn  6766: }
                   6767: 
                   6768: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
                   6769:   font-size: 90%;
1.911     bisitz   6770:   vertical-align: top;
1.1075.2.2  raeburn  6771:   float: none;
1.1075.2.5  raeburn  6772:   border-left: 1px solid black;
                   6773:   border-right: 1px solid black;
1.1075.2.2  raeburn  6774: }
                   6775: 
                   6776: ol.LC_primary_menu li:hover li a, ol.LC_primary_menu li.hover li a {
1.1075.2.5  raeburn  6777:   background-color:$data_table_light;
1.1075.2.2  raeburn  6778: }
                   6779: 
                   6780: ol.LC_primary_menu li li a:hover {
                   6781:    color:$button_hover;
                   6782:    background-color:$data_table_dark;
1.693     droeschl 6783: }
                   6784: 
1.897     wenzelju 6785: ol.LC_primary_menu li img {
1.911     bisitz   6786:   vertical-align: bottom;
1.934     droeschl 6787:   height: 1.1em;
1.1075.2.3  raeburn  6788:   margin: 0.2em 0 0 0;
1.693     droeschl 6789: }
                   6790: 
1.897     wenzelju 6791: ol.LC_primary_menu a {
1.911     bisitz   6792:   color: RGB(80, 80, 80);
                   6793:   text-decoration: none;
1.693     droeschl 6794: }
1.795     www      6795: 
1.949     droeschl 6796: ol.LC_primary_menu a.LC_new_message {
                   6797:   font-weight:bold;
                   6798:   color: darkred;
                   6799: }
                   6800: 
1.975     raeburn  6801: ol.LC_docs_parameters {
                   6802:   margin-left: 0;
                   6803:   padding: 0;
                   6804:   list-style: none;
                   6805: }
                   6806: 
                   6807: ol.LC_docs_parameters li {
                   6808:   margin: 0;
                   6809:   padding-right: 20px;
                   6810:   display: inline;
                   6811: }
                   6812: 
1.976     raeburn  6813: ol.LC_docs_parameters li:before {
                   6814:   content: "\\002022 \\0020";
                   6815: }
                   6816: 
                   6817: li.LC_docs_parameters_title {
                   6818:   font-weight: bold;
                   6819: }
                   6820: 
                   6821: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   6822:   content: "";
                   6823: }
                   6824: 
1.897     wenzelju 6825: ul#LC_secondary_menu {
1.1075.2.23  raeburn  6826:   clear: right;
1.911     bisitz   6827:   color: $fontmenu;
                   6828:   background: $tabbg;
                   6829:   list-style: none;
                   6830:   padding: 0;
                   6831:   margin: 0;
                   6832:   width: 100%;
1.995     raeburn  6833:   text-align: left;
1.1075.2.4  raeburn  6834:   float: left;
1.808     droeschl 6835: }
                   6836: 
1.897     wenzelju 6837: ul#LC_secondary_menu li {
1.911     bisitz   6838:   font-weight: bold;
                   6839:   line-height: 1.8em;
                   6840:   border-right: 1px solid black;
                   6841:   vertical-align: middle;
1.1075.2.4  raeburn  6842:   float: left;
                   6843: }
                   6844: 
                   6845: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   6846:   background-color: $data_table_light;
                   6847: }
                   6848: 
                   6849: ul#LC_secondary_menu li a {
                   6850:   padding: 0 0.8em;
                   6851: }
                   6852: 
                   6853: ul#LC_secondary_menu li ul {
                   6854:   display: none;
                   6855: }
                   6856: 
                   6857: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   6858:   display: block;
                   6859:   position: absolute;
                   6860:   margin: 0;
                   6861:   padding: 0;
                   6862:   list-style:none;
                   6863:   float: none;
                   6864:   background-color: $data_table_light;
1.1075.2.5  raeburn  6865:   z-index: 2;
1.1075.2.10  raeburn  6866:   margin-left: -1px;
1.1075.2.4  raeburn  6867: }
                   6868: 
                   6869: ul#LC_secondary_menu li ul li {
                   6870:   font-size: 90%;
                   6871:   vertical-align: top;
                   6872:   border-left: 1px solid black;
                   6873:   border-right: 1px solid black;
1.1075.2.33  raeburn  6874:   background-color: $data_table_light;
1.1075.2.4  raeburn  6875:   list-style:none;
                   6876:   float: none;
                   6877: }
                   6878: 
                   6879: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   6880:   background-color: $data_table_dark;
1.807     droeschl 6881: }
                   6882: 
1.847     tempelho 6883: ul.LC_TabContent {
1.911     bisitz   6884:   display:block;
                   6885:   background: $sidebg;
                   6886:   border-bottom: solid 1px $lg_border_color;
                   6887:   list-style:none;
1.1020    raeburn  6888:   margin: -1px -10px 0 -10px;
1.911     bisitz   6889:   padding: 0;
1.693     droeschl 6890: }
                   6891: 
1.795     www      6892: ul.LC_TabContent li,
                   6893: ul.LC_TabContentBigger li {
1.911     bisitz   6894:   float:left;
1.741     harmsja  6895: }
1.795     www      6896: 
1.897     wenzelju 6897: ul#LC_secondary_menu li a {
1.911     bisitz   6898:   color: $fontmenu;
                   6899:   text-decoration: none;
1.693     droeschl 6900: }
1.795     www      6901: 
1.721     harmsja  6902: ul.LC_TabContent {
1.952     onken    6903:   min-height:20px;
1.721     harmsja  6904: }
1.795     www      6905: 
                   6906: ul.LC_TabContent li {
1.911     bisitz   6907:   vertical-align:middle;
1.959     onken    6908:   padding: 0 16px 0 10px;
1.911     bisitz   6909:   background-color:$tabbg;
                   6910:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  6911:   border-left: solid 1px $font;
1.721     harmsja  6912: }
1.795     www      6913: 
1.847     tempelho 6914: ul.LC_TabContent .right {
1.911     bisitz   6915:   float:right;
1.847     tempelho 6916: }
                   6917: 
1.911     bisitz   6918: ul.LC_TabContent li a,
                   6919: ul.LC_TabContent li {
                   6920:   color:rgb(47,47,47);
                   6921:   text-decoration:none;
                   6922:   font-size:95%;
                   6923:   font-weight:bold;
1.952     onken    6924:   min-height:20px;
                   6925: }
                   6926: 
1.959     onken    6927: ul.LC_TabContent li a:hover,
                   6928: ul.LC_TabContent li a:focus {
1.952     onken    6929:   color: $button_hover;
1.959     onken    6930:   background:none;
                   6931:   outline:none;
1.952     onken    6932: }
                   6933: 
                   6934: ul.LC_TabContent li:hover {
                   6935:   color: $button_hover;
                   6936:   cursor:pointer;
1.721     harmsja  6937: }
1.795     www      6938: 
1.911     bisitz   6939: ul.LC_TabContent li.active {
1.952     onken    6940:   color: $font;
1.911     bisitz   6941:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    6942:   border-bottom:solid 1px #FFFFFF;
                   6943:   cursor: default;
1.744     ehlerst  6944: }
1.795     www      6945: 
1.959     onken    6946: ul.LC_TabContent li.active a {
                   6947:   color:$font;
                   6948:   background:#FFFFFF;
                   6949:   outline: none;
                   6950: }
1.1047    raeburn  6951: 
                   6952: ul.LC_TabContent li.goback {
                   6953:   float: left;
                   6954:   border-left: none;
                   6955: }
                   6956: 
1.870     tempelho 6957: #maincoursedoc {
1.911     bisitz   6958:   clear:both;
1.870     tempelho 6959: }
                   6960: 
                   6961: ul.LC_TabContentBigger {
1.911     bisitz   6962:   display:block;
                   6963:   list-style:none;
                   6964:   padding: 0;
1.870     tempelho 6965: }
                   6966: 
1.795     www      6967: ul.LC_TabContentBigger li {
1.911     bisitz   6968:   vertical-align:bottom;
                   6969:   height: 30px;
                   6970:   font-size:110%;
                   6971:   font-weight:bold;
                   6972:   color: #737373;
1.841     tempelho 6973: }
                   6974: 
1.957     onken    6975: ul.LC_TabContentBigger li.active {
                   6976:   position: relative;
                   6977:   top: 1px;
                   6978: }
                   6979: 
1.870     tempelho 6980: ul.LC_TabContentBigger li a {
1.911     bisitz   6981:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   6982:   height: 30px;
                   6983:   line-height: 30px;
                   6984:   text-align: center;
                   6985:   display: block;
                   6986:   text-decoration: none;
1.958     onken    6987:   outline: none;  
1.741     harmsja  6988: }
1.795     www      6989: 
1.870     tempelho 6990: ul.LC_TabContentBigger li.active a {
1.911     bisitz   6991:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   6992:   color:$font;
1.744     ehlerst  6993: }
1.795     www      6994: 
1.870     tempelho 6995: ul.LC_TabContentBigger li b {
1.911     bisitz   6996:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   6997:   display: block;
                   6998:   float: left;
                   6999:   padding: 0 30px;
1.957     onken    7000:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7001: }
                   7002: 
1.956     onken    7003: ul.LC_TabContentBigger li:hover b {
                   7004:   color:$button_hover;
                   7005: }
                   7006: 
1.870     tempelho 7007: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7008:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7009:   color:$font;
1.957     onken    7010:   border: 0;
1.741     harmsja  7011: }
1.693     droeschl 7012: 
1.870     tempelho 7013: 
1.862     bisitz   7014: ul.LC_CourseBreadcrumbs {
                   7015:   background: $sidebg;
1.1020    raeburn  7016:   height: 2em;
1.862     bisitz   7017:   padding-left: 10px;
1.1020    raeburn  7018:   margin: 0;
1.862     bisitz   7019:   list-style-position: inside;
                   7020: }
                   7021: 
1.911     bisitz   7022: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7023: ol#LC_PathBreadcrumbs {
1.911     bisitz   7024:   padding-left: 10px;
                   7025:   margin: 0;
1.933     droeschl 7026:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7027: }
                   7028: 
1.911     bisitz   7029: ol#LC_MenuBreadcrumbs li,
                   7030: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7031: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7032:   display: inline;
1.933     droeschl 7033:   white-space: normal;  
1.693     droeschl 7034: }
                   7035: 
1.823     bisitz   7036: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7037: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7038:   text-decoration: none;
                   7039:   font-size:90%;
1.693     droeschl 7040: }
1.795     www      7041: 
1.969     droeschl 7042: ol#LC_MenuBreadcrumbs h1 {
                   7043:   display: inline;
                   7044:   font-size: 90%;
                   7045:   line-height: 2.5em;
                   7046:   margin: 0;
                   7047:   padding: 0;
                   7048: }
                   7049: 
1.795     www      7050: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7051:   text-decoration:none;
                   7052:   font-size:100%;
                   7053:   font-weight:bold;
1.693     droeschl 7054: }
1.795     www      7055: 
1.840     bisitz   7056: .LC_Box {
1.911     bisitz   7057:   border: solid 1px $lg_border_color;
                   7058:   padding: 0 10px 10px 10px;
1.746     neumanie 7059: }
1.795     www      7060: 
1.1020    raeburn  7061: .LC_DocsBox {
                   7062:   border: solid 1px $lg_border_color;
                   7063:   padding: 0 0 10px 10px;
                   7064: }
                   7065: 
1.795     www      7066: .LC_AboutMe_Image {
1.911     bisitz   7067:   float:left;
                   7068:   margin-right:10px;
1.747     neumanie 7069: }
1.795     www      7070: 
                   7071: .LC_Clear_AboutMe_Image {
1.911     bisitz   7072:   clear:left;
1.747     neumanie 7073: }
1.795     www      7074: 
1.721     harmsja  7075: dl.LC_ListStyleClean dt {
1.911     bisitz   7076:   padding-right: 5px;
                   7077:   display: table-header-group;
1.693     droeschl 7078: }
                   7079: 
1.721     harmsja  7080: dl.LC_ListStyleClean dd {
1.911     bisitz   7081:   display: table-row;
1.693     droeschl 7082: }
                   7083: 
1.721     harmsja  7084: .LC_ListStyleClean,
                   7085: .LC_ListStyleSimple,
                   7086: .LC_ListStyleNormal,
1.795     www      7087: .LC_ListStyleSpecial {
1.911     bisitz   7088:   /* display:block; */
                   7089:   list-style-position: inside;
                   7090:   list-style-type: none;
                   7091:   overflow: hidden;
                   7092:   padding: 0;
1.693     droeschl 7093: }
                   7094: 
1.721     harmsja  7095: .LC_ListStyleSimple li,
                   7096: .LC_ListStyleSimple dd,
                   7097: .LC_ListStyleNormal li,
                   7098: .LC_ListStyleNormal dd,
                   7099: .LC_ListStyleSpecial li,
1.795     www      7100: .LC_ListStyleSpecial dd {
1.911     bisitz   7101:   margin: 0;
                   7102:   padding: 5px 5px 5px 10px;
                   7103:   clear: both;
1.693     droeschl 7104: }
                   7105: 
1.721     harmsja  7106: .LC_ListStyleClean li,
                   7107: .LC_ListStyleClean dd {
1.911     bisitz   7108:   padding-top: 0;
                   7109:   padding-bottom: 0;
1.693     droeschl 7110: }
                   7111: 
1.721     harmsja  7112: .LC_ListStyleSimple dd,
1.795     www      7113: .LC_ListStyleSimple li {
1.911     bisitz   7114:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7115: }
                   7116: 
1.721     harmsja  7117: .LC_ListStyleSpecial li,
                   7118: .LC_ListStyleSpecial dd {
1.911     bisitz   7119:   list-style-type: none;
                   7120:   background-color: RGB(220, 220, 220);
                   7121:   margin-bottom: 4px;
1.693     droeschl 7122: }
                   7123: 
1.721     harmsja  7124: table.LC_SimpleTable {
1.911     bisitz   7125:   margin:5px;
                   7126:   border:solid 1px $lg_border_color;
1.795     www      7127: }
1.693     droeschl 7128: 
1.721     harmsja  7129: table.LC_SimpleTable tr {
1.911     bisitz   7130:   padding: 0;
                   7131:   border:solid 1px $lg_border_color;
1.693     droeschl 7132: }
1.795     www      7133: 
                   7134: table.LC_SimpleTable thead {
1.911     bisitz   7135:   background:rgb(220,220,220);
1.693     droeschl 7136: }
                   7137: 
1.721     harmsja  7138: div.LC_columnSection {
1.911     bisitz   7139:   display: block;
                   7140:   clear: both;
                   7141:   overflow: hidden;
                   7142:   margin: 0;
1.693     droeschl 7143: }
                   7144: 
1.721     harmsja  7145: div.LC_columnSection>* {
1.911     bisitz   7146:   float: left;
                   7147:   margin: 10px 20px 10px 0;
                   7148:   overflow:hidden;
1.693     droeschl 7149: }
1.721     harmsja  7150: 
1.795     www      7151: table em {
1.911     bisitz   7152:   font-weight: bold;
                   7153:   font-style: normal;
1.748     schulted 7154: }
1.795     www      7155: 
1.779     bisitz   7156: table.LC_tableBrowseRes,
1.795     www      7157: table.LC_tableOfContent {
1.911     bisitz   7158:   border:none;
                   7159:   border-spacing: 1px;
                   7160:   padding: 3px;
                   7161:   background-color: #FFFFFF;
                   7162:   font-size: 90%;
1.753     droeschl 7163: }
1.789     droeschl 7164: 
1.911     bisitz   7165: table.LC_tableOfContent {
                   7166:   border-collapse: collapse;
1.789     droeschl 7167: }
                   7168: 
1.771     droeschl 7169: table.LC_tableBrowseRes a,
1.768     schulted 7170: table.LC_tableOfContent a {
1.911     bisitz   7171:   background-color: transparent;
                   7172:   text-decoration: none;
1.753     droeschl 7173: }
                   7174: 
1.795     www      7175: table.LC_tableOfContent img {
1.911     bisitz   7176:   border: none;
                   7177:   height: 1.3em;
                   7178:   vertical-align: text-bottom;
                   7179:   margin-right: 0.3em;
1.753     droeschl 7180: }
1.757     schulted 7181: 
1.795     www      7182: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7183:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7184: }
                   7185: 
1.795     www      7186: a#LC_content_toolbar_everything {
1.911     bisitz   7187:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7188: }
                   7189: 
1.795     www      7190: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7191:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7192: }
                   7193: 
1.795     www      7194: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7195:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7196: }
                   7197: 
1.795     www      7198: a#LC_content_toolbar_changefolder {
1.911     bisitz   7199:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7200: }
                   7201: 
1.795     www      7202: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7203:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7204: }
                   7205: 
1.1043    raeburn  7206: a#LC_content_toolbar_edittoplevel {
                   7207:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7208: }
                   7209: 
1.795     www      7210: ul#LC_toolbar li a:hover {
1.911     bisitz   7211:   background-position: bottom center;
1.757     schulted 7212: }
                   7213: 
1.795     www      7214: ul#LC_toolbar {
1.911     bisitz   7215:   padding: 0;
                   7216:   margin: 2px;
                   7217:   list-style:none;
                   7218:   position:relative;
                   7219:   background-color:white;
1.1075.2.9  raeburn  7220:   overflow: auto;
1.757     schulted 7221: }
                   7222: 
1.795     www      7223: ul#LC_toolbar li {
1.911     bisitz   7224:   border:1px solid white;
                   7225:   padding: 0;
                   7226:   margin: 0;
                   7227:   float: left;
                   7228:   display:inline;
                   7229:   vertical-align:middle;
1.1075.2.9  raeburn  7230:   white-space: nowrap;
1.911     bisitz   7231: }
1.757     schulted 7232: 
1.783     amueller 7233: 
1.795     www      7234: a.LC_toolbarItem {
1.911     bisitz   7235:   display:block;
                   7236:   padding: 0;
                   7237:   margin: 0;
                   7238:   height: 32px;
                   7239:   width: 32px;
                   7240:   color:white;
                   7241:   border: none;
                   7242:   background-repeat:no-repeat;
                   7243:   background-color:transparent;
1.757     schulted 7244: }
                   7245: 
1.915     droeschl 7246: ul.LC_funclist {
                   7247:     margin: 0;
                   7248:     padding: 0.5em 1em 0.5em 0;
                   7249: }
                   7250: 
1.933     droeschl 7251: ul.LC_funclist > li:first-child {
                   7252:     font-weight:bold; 
                   7253:     margin-left:0.8em;
                   7254: }
                   7255: 
1.915     droeschl 7256: ul.LC_funclist + ul.LC_funclist {
                   7257:     /* 
                   7258:        left border as a seperator if we have more than
                   7259:        one list 
                   7260:     */
                   7261:     border-left: 1px solid $sidebg;
                   7262:     /* 
                   7263:        this hides the left border behind the border of the 
                   7264:        outer box if element is wrapped to the next 'line' 
                   7265:     */
                   7266:     margin-left: -1px;
                   7267: }
                   7268: 
1.843     bisitz   7269: ul.LC_funclist li {
1.915     droeschl 7270:   display: inline;
1.782     bisitz   7271:   white-space: nowrap;
1.915     droeschl 7272:   margin: 0 0 0 25px;
                   7273:   line-height: 150%;
1.782     bisitz   7274: }
                   7275: 
1.974     wenzelju 7276: .LC_hidden {
                   7277:   display: none;
                   7278: }
                   7279: 
1.1030    www      7280: .LCmodal-overlay {
                   7281: 		position:fixed;
                   7282: 		top:0;
                   7283: 		right:0;
                   7284: 		bottom:0;
                   7285: 		left:0;
                   7286: 		height:100%;
                   7287: 		width:100%;
                   7288: 		margin:0;
                   7289: 		padding:0;
                   7290: 		background:#999;
                   7291: 		opacity:.75;
                   7292: 		filter: alpha(opacity=75);
                   7293: 		-moz-opacity: 0.75;
                   7294: 		z-index:101;
                   7295: }
                   7296: 
                   7297: * html .LCmodal-overlay {   
                   7298: 		position: absolute;
                   7299: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7300: }
                   7301: 
                   7302: .LCmodal-window {
                   7303: 		position:fixed;
                   7304: 		top:50%;
                   7305: 		left:50%;
                   7306: 		margin:0;
                   7307: 		padding:0;
                   7308: 		z-index:102;
                   7309: 	}
                   7310: 
                   7311: * html .LCmodal-window {
                   7312: 		position:absolute;
                   7313: }
                   7314: 
                   7315: .LCclose-window {
                   7316: 		position:absolute;
                   7317: 		width:32px;
                   7318: 		height:32px;
                   7319: 		right:8px;
                   7320: 		top:8px;
                   7321: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7322: 		text-indent:-99999px;
                   7323: 		overflow:hidden;
                   7324: 		cursor:pointer;
                   7325: }
                   7326: 
1.1075.2.17  raeburn  7327: /*
                   7328:   styles used by TTH when "Default set of options to pass to tth/m
                   7329:   when converting TeX" in course settings has been set
                   7330: 
                   7331:   option passed: -t
                   7332: 
                   7333: */
                   7334: 
                   7335: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7336: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7337: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7338: td div.norm {line-height:normal;}
                   7339: 
                   7340: /*
                   7341:   option passed -y3
                   7342: */
                   7343: 
                   7344: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7345: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7346: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7347: 
1.343     albertel 7348: END
                   7349: }
                   7350: 
1.306     albertel 7351: =pod
                   7352: 
                   7353: =item * &headtag()
                   7354: 
                   7355: Returns a uniform footer for LON-CAPA web pages.
                   7356: 
1.307     albertel 7357: Inputs: $title - optional title for the head
                   7358:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7359:         $args - optional arguments
1.319     albertel 7360:             force_register - if is true call registerurl so the remote is 
                   7361:                              informed
1.415     albertel 7362:             redirect       -> array ref of
                   7363:                                    1- seconds before redirect occurs
                   7364:                                    2- url to redirect to
                   7365:                                    3- whether the side effect should occur
1.315     albertel 7366:                            (side effect of setting 
                   7367:                                $env{'internal.head.redirect'} to the url 
                   7368:                                redirected too)
1.352     albertel 7369:             domain         -> force to color decorate a page for a specific
                   7370:                                domain
                   7371:             function       -> force usage of a specific rolish color scheme
                   7372:             bgcolor        -> override the default page bgcolor
1.460     albertel 7373:             no_auto_mt_title
                   7374:                            -> prevent &mt()ing the title arg
1.464     albertel 7375: 
1.306     albertel 7376: =cut
                   7377: 
                   7378: sub headtag {
1.313     albertel 7379:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7380:     
1.363     albertel 7381:     my $function = $args->{'function'} || &get_users_function();
                   7382:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7383:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7384:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7385:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7386: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7387: 		   #time(),
1.418     albertel 7388: 		   $env{'environment.color.timestamp'},
1.363     albertel 7389: 		   $function,$domain,$bgcolor);
                   7390: 
1.369     www      7391:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7392: 
1.308     albertel 7393:     my $result =
                   7394: 	'<head>'.
1.1075.2.56  raeburn  7395: 	&font_settings($args);
1.319     albertel 7396: 
1.1075.2.72  raeburn  7397:     my $inhibitprint;
                   7398:     if ($args->{'print_suppress'}) {
                   7399:         $inhibitprint = &print_suppression();
                   7400:     }
1.1064    raeburn  7401: 
1.461     albertel 7402:     if (!$args->{'frameset'}) {
                   7403: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7404:     }
1.1075.2.12  raeburn  7405:     if ($args->{'force_register'}) {
                   7406:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7407:     }
1.436     albertel 7408:     if (!$args->{'no_nav_bar'} 
                   7409: 	&& !$args->{'only_body'}
                   7410: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7411: 	$result .= &help_menu_js($httphost);
1.1032    www      7412:         $result.=&modal_window();
1.1038    www      7413:         $result.=&togglebox_script();
1.1034    www      7414:         $result.=&wishlist_window();
1.1041    www      7415:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7416:     } else {
                   7417:         if ($args->{'add_modal'}) {
                   7418:            $result.=&modal_window();
                   7419:         }
                   7420:         if ($args->{'add_wishlist'}) {
                   7421:            $result.=&wishlist_window();
                   7422:         }
1.1038    www      7423:         if ($args->{'add_togglebox'}) {
                   7424:            $result.=&togglebox_script();
                   7425:         }
1.1041    www      7426:         if ($args->{'add_progressbar'}) {
                   7427:            $result.=&LCprogressbarUpdate_script();
                   7428:         }
1.436     albertel 7429:     }
1.314     albertel 7430:     if (ref($args->{'redirect'})) {
1.414     albertel 7431: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7432: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7433: 	if (!$inhibit_continue) {
                   7434: 	    $env{'internal.head.redirect'} = $url;
                   7435: 	}
1.313     albertel 7436: 	$result.=<<ADDMETA
                   7437: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7438: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7439: ADDMETA
1.1075.2.89  raeburn  7440:     } else {
                   7441:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7442:             my $requrl = $env{'request.uri'};
                   7443:             if ($requrl eq '') {
                   7444:                 $requrl = $ENV{'REQUEST_URI'};
                   7445:                 $requrl =~ s/\?.+$//;
                   7446:             }
                   7447:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7448:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7449:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7450:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7451:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7452:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7453:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7454:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7455:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7456:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7457:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7458:                                 my $numsec = 5;
                   7459:                                 my $timeout = $numsec * 1000;
                   7460:                                 my ($newurl,$locknum,%locks,$msg);
                   7461:                                 if ($env{'request.role.adv'}) {
                   7462:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7463:                                 }
                   7464:                                 my $disable_submit = 0;
                   7465:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7466:                                     $disable_submit = 1;
                   7467:                                 }
                   7468:                                 if ($locknum) {
                   7469:                                     my @lockinfo = sort(values(%locks));
                   7470:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7471:                                            join(", ",sort(values(%locks)))."\\n".
                   7472:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7473:                                 } else {
                   7474:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7475:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7476:                                     }
                   7477:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7478:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7479:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7480:                                         $newurl .= '&role='.$env{'request.role'};
                   7481:                                     }
                   7482:                                     if ($env{'request.symb'}) {
                   7483:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7484:                                     } else {
                   7485:                                         $newurl .= '&origurl='.$requrl;
                   7486:                                     }
                   7487:                                 }
1.1075.2.98  raeburn  7488:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7489:                                 $result.=<<OFFLOAD
                   7490: <meta http-equiv="pragma" content="no-cache" />
                   7491: <script type="text/javascript">
1.1075.2.92  raeburn  7492: // <![CDATA[
1.1075.2.89  raeburn  7493: function LC_Offload_Now() {
                   7494:     var dest = "$newurl";
                   7495:     if (dest != '') {
                   7496:         window.location.href="$newurl";
                   7497:     }
                   7498: }
1.1075.2.92  raeburn  7499: \$(document).ready(function () {
                   7500:     window.alert('$msg');
                   7501:     if ($disable_submit) {
1.1075.2.89  raeburn  7502:         \$(".LC_hwk_submit").prop("disabled", true);
                   7503:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7504:     }
                   7505:     setTimeout('LC_Offload_Now()', $timeout);
                   7506: });
                   7507: // ]]>
1.1075.2.89  raeburn  7508: </script>
                   7509: OFFLOAD
                   7510:                             }
                   7511:                         }
                   7512:                     }
                   7513:                 }
                   7514:             }
                   7515:         }
1.313     albertel 7516:     }
1.306     albertel 7517:     if (!defined($title)) {
                   7518: 	$title = 'The LearningOnline Network with CAPA';
                   7519:     }
1.460     albertel 7520:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7521:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7522: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7523:     if (!$args->{'frameset'}) {
                   7524:         $result .= ' /';
                   7525:     }
                   7526:     $result .= '>'
1.1064    raeburn  7527:         .$inhibitprint
1.414     albertel 7528: 	.$head_extra;
1.1075.2.42  raeburn  7529:     if ($env{'browser.mobile'}) {
                   7530:         $result .= '
                   7531: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7532: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7533:     }
1.962     droeschl 7534:     return $result.'</head>';
1.306     albertel 7535: }
                   7536: 
                   7537: =pod
                   7538: 
1.340     albertel 7539: =item * &font_settings()
                   7540: 
                   7541: Returns neccessary <meta> to set the proper encoding
                   7542: 
1.1075.2.56  raeburn  7543: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7544: 
                   7545: =cut
                   7546: 
                   7547: sub font_settings {
1.1075.2.56  raeburn  7548:     my ($args) = @_;
1.340     albertel 7549:     my $headerstring='';
1.1075.2.56  raeburn  7550:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7551:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7552: 	$headerstring.=
1.1075.2.61  raeburn  7553: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7554:         if (!$args->{'frameset'}) {
                   7555:             $headerstring.= ' /';
                   7556:         }
                   7557:         $headerstring .= '>'."\n";
1.340     albertel 7558:     }
                   7559:     return $headerstring;
                   7560: }
                   7561: 
1.341     albertel 7562: =pod
                   7563: 
1.1064    raeburn  7564: =item * &print_suppression()
                   7565: 
                   7566: In course context returns css which causes the body to be blank when media="print",
                   7567: if printout generation is unavailable for the current resource.
                   7568: 
                   7569: This could be because:
                   7570: 
                   7571: (a) printstartdate is in the future
                   7572: 
                   7573: (b) printenddate is in the past
                   7574: 
                   7575: (c) there is an active exam block with "printout"
                   7576: functionality blocked
                   7577: 
                   7578: Users with pav, pfo or evb privileges are exempt.
                   7579: 
                   7580: Inputs: none
                   7581: 
                   7582: =cut
                   7583: 
                   7584: 
                   7585: sub print_suppression {
                   7586:     my $noprint;
                   7587:     if ($env{'request.course.id'}) {
                   7588:         my $scope = $env{'request.course.id'};
                   7589:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7590:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7591:             return;
                   7592:         }
                   7593:         if ($env{'request.course.sec'} ne '') {
                   7594:             $scope .= "/$env{'request.course.sec'}";
                   7595:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7596:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7597:                 return;
1.1064    raeburn  7598:             }
                   7599:         }
                   7600:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7601:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7602:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7603:         if ($blocked) {
                   7604:             my $checkrole = "cm./$cdom/$cnum";
                   7605:             if ($env{'request.course.sec'} ne '') {
                   7606:                 $checkrole .= "/$env{'request.course.sec'}";
                   7607:             }
                   7608:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7609:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7610:                 $noprint = 1;
                   7611:             }
                   7612:         }
                   7613:         unless ($noprint) {
                   7614:             my $symb = &Apache::lonnet::symbread();
                   7615:             if ($symb ne '') {
                   7616:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7617:                 if (ref($navmap)) {
                   7618:                     my $res = $navmap->getBySymb($symb);
                   7619:                     if (ref($res)) {
                   7620:                         if (!$res->resprintable()) {
                   7621:                             $noprint = 1;
                   7622:                         }
                   7623:                     }
                   7624:                 }
                   7625:             }
                   7626:         }
                   7627:         if ($noprint) {
                   7628:             return <<"ENDSTYLE";
                   7629: <style type="text/css" media="print">
                   7630:     body { display:none }
                   7631: </style>
                   7632: ENDSTYLE
                   7633:         }
                   7634:     }
                   7635:     return;
                   7636: }
                   7637: 
                   7638: =pod
                   7639: 
1.341     albertel 7640: =item * &xml_begin()
                   7641: 
                   7642: Returns the needed doctype and <html>
                   7643: 
                   7644: Inputs: none
                   7645: 
                   7646: =cut
                   7647: 
                   7648: sub xml_begin {
1.1075.2.61  raeburn  7649:     my ($is_frameset) = @_;
1.341     albertel 7650:     my $output='';
                   7651: 
                   7652:     if ($env{'browser.mathml'}) {
                   7653: 	$output='<?xml version="1.0"?>'
                   7654:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   7655: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   7656:             
                   7657: #	    .'<!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">] >'
                   7658: 	    .'<!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">'
                   7659:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   7660: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  7661:     } elsif ($is_frameset) {
                   7662:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   7663:                 '<html>'."\n";
1.341     albertel 7664:     } else {
1.1075.2.61  raeburn  7665: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   7666:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 7667:     }
                   7668:     return $output;
                   7669: }
1.340     albertel 7670: 
                   7671: =pod
                   7672: 
1.306     albertel 7673: =item * &start_page()
                   7674: 
                   7675: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   7676: 
1.648     raeburn  7677: Inputs:
                   7678: 
                   7679: =over 4
                   7680: 
                   7681: $title - optional title for the page
                   7682: 
                   7683: $head_extra - optional extra HTML to incude inside the <head>
                   7684: 
                   7685: $args - additional optional args supported are:
                   7686: 
                   7687: =over 8
                   7688: 
                   7689:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 7690:                                     arg on
1.814     bisitz   7691:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  7692:              add_entries    -> additional attributes to add to the  <body>
                   7693:              domain         -> force to color decorate a page for a 
1.317     albertel 7694:                                     specific domain
1.648     raeburn  7695:              function       -> force usage of a specific rolish color
1.317     albertel 7696:                                     scheme
1.648     raeburn  7697:              redirect       -> see &headtag()
                   7698:              bgcolor        -> override the default page bg color
                   7699:              js_ready       -> return a string ready for being used in 
1.317     albertel 7700:                                     a javascript writeln
1.648     raeburn  7701:              html_encode    -> return a string ready for being used in 
1.320     albertel 7702:                                     a html attribute
1.648     raeburn  7703:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 7704:                                     $forcereg arg
1.648     raeburn  7705:              frameset       -> if true will start with a <frameset>
1.330     albertel 7706:                                     rather than <body>
1.648     raeburn  7707:              skip_phases    -> hash ref of 
1.338     albertel 7708:                                     head -> skip the <html><head> generation
                   7709:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  7710:              no_inline_link -> if true and in remote mode, don't show the
                   7711:                                     'Switch To Inline Menu' link
1.648     raeburn  7712:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 7713:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  7714:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.15  raeburn  7715:              group          -> includes the current group, if page is for a
                   7716:                                specific group
1.361     albertel 7717: 
1.648     raeburn  7718: =back
1.460     albertel 7719: 
1.648     raeburn  7720: =back
1.562     albertel 7721: 
1.306     albertel 7722: =cut
                   7723: 
                   7724: sub start_page {
1.309     albertel 7725:     my ($title,$head_extra,$args) = @_;
1.318     albertel 7726:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 7727: 
1.315     albertel 7728:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  7729:     my ($result,@advtools);
1.964     droeschl 7730: 
1.338     albertel 7731:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  7732:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 7733:     }
                   7734:     
                   7735:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   7736: 	if ($args->{'frameset'}) {
                   7737: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   7738: 						$args->{'add_entries'});
                   7739: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   7740:         } else {
                   7741:             $result .=
                   7742:                 &bodytag($title, 
                   7743:                          $args->{'function'},       $args->{'add_entries'},
                   7744:                          $args->{'only_body'},      $args->{'domain'},
                   7745:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  7746:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  7747:                          $args,                     \@advtools);
1.831     bisitz   7748:         }
1.330     albertel 7749:     }
1.338     albertel 7750: 
1.315     albertel 7751:     if ($args->{'js_ready'}) {
1.713     kaisler  7752: 		$result = &js_ready($result);
1.315     albertel 7753:     }
1.320     albertel 7754:     if ($args->{'html_encode'}) {
1.713     kaisler  7755: 		$result = &html_encode($result);
                   7756:     }
                   7757: 
1.813     bisitz   7758:     # Preparation for new and consistent functionlist at top of screen
                   7759:     # if ($args->{'functionlist'}) {
                   7760:     #            $result .= &build_functionlist();
                   7761:     #}
                   7762: 
1.964     droeschl 7763:     # Don't add anything more if only_body wanted or in const space
                   7764:     return $result if    $args->{'only_body'} 
                   7765:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   7766: 
                   7767:     #Breadcrumbs
1.758     kaisler  7768:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   7769: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   7770: 		#if any br links exists, add them to the breadcrumbs
                   7771: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   7772: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   7773: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   7774: 			}
                   7775: 		}
1.1075.2.19  raeburn  7776:                 # if @advtools array contains items add then to the breadcrumbs
                   7777:                 if (@advtools > 0) {
                   7778:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   7779:                 }
1.758     kaisler  7780: 
                   7781: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   7782: 		if(exists($args->{'bread_crumbs_component'})){
                   7783: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'});
                   7784: 		}else{
                   7785: 			$result .= &Apache::lonhtmlcommon::breadcrumbs();
                   7786: 		}
1.1075.2.24  raeburn  7787:     } elsif (($env{'environment.remote'} eq 'on') &&
                   7788:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   7789:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   7790:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  7791:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 7792:     }
1.315     albertel 7793:     return $result;
1.306     albertel 7794: }
                   7795: 
                   7796: sub end_page {
1.315     albertel 7797:     my ($args) = @_;
                   7798:     $env{'internal.end_page'}++;
1.330     albertel 7799:     my $result;
1.335     albertel 7800:     if ($args->{'discussion'}) {
                   7801: 	my ($target,$parser);
                   7802: 	if (ref($args->{'discussion'})) {
                   7803: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   7804: 				$args->{'discussion'}{'parser'});
                   7805: 	}
                   7806: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   7807:     }
1.330     albertel 7808:     if ($args->{'frameset'}) {
                   7809: 	$result .= '</frameset>';
                   7810:     } else {
1.635     raeburn  7811: 	$result .= &endbodytag($args);
1.330     albertel 7812:     }
1.1075.2.6  raeburn  7813:     unless ($args->{'notbody'}) {
                   7814:         $result .= "\n</html>";
                   7815:     }
1.330     albertel 7816: 
1.315     albertel 7817:     if ($args->{'js_ready'}) {
1.317     albertel 7818: 	$result = &js_ready($result);
1.315     albertel 7819:     }
1.335     albertel 7820: 
1.320     albertel 7821:     if ($args->{'html_encode'}) {
                   7822: 	$result = &html_encode($result);
                   7823:     }
1.335     albertel 7824: 
1.315     albertel 7825:     return $result;
                   7826: }
                   7827: 
1.1034    www      7828: sub wishlist_window {
                   7829:     return(<<'ENDWISHLIST');
1.1046    raeburn  7830: <script type="text/javascript">
1.1034    www      7831: // <![CDATA[
                   7832: // <!-- BEGIN LON-CAPA Internal
                   7833: function set_wishlistlink(title, path) {
                   7834:     if (!title) {
                   7835:         title = document.title;
                   7836:         title = title.replace(/^LON-CAPA /,'');
                   7837:     }
1.1075.2.65  raeburn  7838:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  7839:     title = title.replace("'","\\\'");
1.1034    www      7840:     if (!path) {
                   7841:         path = location.pathname;
                   7842:     }
1.1075.2.65  raeburn  7843:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  7844:     path = path.replace("'","\\\'");
1.1034    www      7845:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   7846:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   7847: }
                   7848: // END LON-CAPA Internal -->
                   7849: // ]]>
                   7850: </script>
                   7851: ENDWISHLIST
                   7852: }
                   7853: 
1.1030    www      7854: sub modal_window {
                   7855:     return(<<'ENDMODAL');
1.1046    raeburn  7856: <script type="text/javascript">
1.1030    www      7857: // <![CDATA[
                   7858: // <!-- BEGIN LON-CAPA Internal
                   7859: var modalWindow = {
                   7860: 	parent:"body",
                   7861: 	windowId:null,
                   7862: 	content:null,
                   7863: 	width:null,
                   7864: 	height:null,
                   7865: 	close:function()
                   7866: 	{
                   7867: 	        $(".LCmodal-window").remove();
                   7868: 	        $(".LCmodal-overlay").remove();
                   7869: 	},
                   7870: 	open:function()
                   7871: 	{
                   7872: 		var modal = "";
                   7873: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   7874: 		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;\">";
                   7875: 		modal += this.content;
                   7876: 		modal += "</div>";	
                   7877: 
                   7878: 		$(this.parent).append(modal);
                   7879: 
                   7880: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   7881: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   7882: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   7883: 	}
                   7884: };
1.1075.2.42  raeburn  7885: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      7886: 	{
1.1075.2.83  raeburn  7887:                 source = source.replace("'","&#39;");
1.1030    www      7888: 		modalWindow.windowId = "myModal";
                   7889: 		modalWindow.width = width;
                   7890: 		modalWindow.height = height;
1.1075.2.80  raeburn  7891: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      7892: 		modalWindow.open();
1.1075.2.87  raeburn  7893: 	};
1.1030    www      7894: // END LON-CAPA Internal -->
                   7895: // ]]>
                   7896: </script>
                   7897: ENDMODAL
                   7898: }
                   7899: 
                   7900: sub modal_link {
1.1075.2.42  raeburn  7901:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      7902:     unless ($width) { $width=480; }
                   7903:     unless ($height) { $height=400; }
1.1031    www      7904:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  7905:     unless ($transparency) { $transparency='true'; }
                   7906: 
1.1074    raeburn  7907:     my $target_attr;
                   7908:     if (defined($target)) {
                   7909:         $target_attr = 'target="'.$target.'"';
                   7910:     }
                   7911:     return <<"ENDLINK";
1.1075.2.42  raeburn  7912: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  7913:            $linktext</a>
                   7914: ENDLINK
1.1030    www      7915: }
                   7916: 
1.1032    www      7917: sub modal_adhoc_script {
                   7918:     my ($funcname,$width,$height,$content)=@_;
                   7919:     return (<<ENDADHOC);
1.1046    raeburn  7920: <script type="text/javascript">
1.1032    www      7921: // <![CDATA[
                   7922:         var $funcname = function()
                   7923:         {
                   7924:                 modalWindow.windowId = "myModal";
                   7925:                 modalWindow.width = $width;
                   7926:                 modalWindow.height = $height;
                   7927:                 modalWindow.content = '$content';
                   7928:                 modalWindow.open();
                   7929:         };  
                   7930: // ]]>
                   7931: </script>
                   7932: ENDADHOC
                   7933: }
                   7934: 
1.1041    www      7935: sub modal_adhoc_inner {
                   7936:     my ($funcname,$width,$height,$content)=@_;
                   7937:     my $innerwidth=$width-20;
                   7938:     $content=&js_ready(
1.1042    www      7939:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  7940:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   7941:                  $content.
1.1041    www      7942:                  &end_scrollbox().
1.1075.2.42  raeburn  7943:                  &end_page()
1.1041    www      7944:              );
                   7945:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   7946: }
                   7947: 
                   7948: sub modal_adhoc_window {
                   7949:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   7950:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   7951:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   7952: }
                   7953: 
                   7954: sub modal_adhoc_launch {
                   7955:     my ($funcname,$width,$height,$content)=@_;
                   7956:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   7957: <script type="text/javascript">
                   7958: // <![CDATA[
                   7959: $funcname();
                   7960: // ]]>
                   7961: </script>
                   7962: ENDLAUNCH
                   7963: }
                   7964: 
                   7965: sub modal_adhoc_close {
                   7966:     return (<<ENDCLOSE);
                   7967: <script type="text/javascript">
                   7968: // <![CDATA[
                   7969: modalWindow.close();
                   7970: // ]]>
                   7971: </script>
                   7972: ENDCLOSE
                   7973: }
                   7974: 
1.1038    www      7975: sub togglebox_script {
                   7976:    return(<<ENDTOGGLE);
                   7977: <script type="text/javascript"> 
                   7978: // <![CDATA[
                   7979: function LCtoggleDisplay(id,hidetext,showtext) {
                   7980:    link = document.getElementById(id + "link").childNodes[0];
                   7981:    with (document.getElementById(id).style) {
                   7982:       if (display == "none" ) {
                   7983:           display = "inline";
                   7984:           link.nodeValue = hidetext;
                   7985:         } else {
                   7986:           display = "none";
                   7987:           link.nodeValue = showtext;
                   7988:        }
                   7989:    }
                   7990: }
                   7991: // ]]>
                   7992: </script>
                   7993: ENDTOGGLE
                   7994: }
                   7995: 
1.1039    www      7996: sub start_togglebox {
                   7997:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   7998:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   7999:     unless ($showtext) { $showtext=&mt('show'); }
                   8000:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8001:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8002:     return &start_data_table().
                   8003:            &start_data_table_header_row().
                   8004:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8005:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8006:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8007:            &end_data_table_header_row().
                   8008:            '<tr id="'.$id.'" style="display:none""><td>';
                   8009: }
                   8010: 
                   8011: sub end_togglebox {
                   8012:     return '</td></tr>'.&end_data_table();
                   8013: }
                   8014: 
1.1041    www      8015: sub LCprogressbar_script {
1.1045    www      8016:    my ($id)=@_;
1.1041    www      8017:    return(<<ENDPROGRESS);
                   8018: <script type="text/javascript">
                   8019: // <![CDATA[
1.1045    www      8020: \$('#progressbar$id').progressbar({
1.1041    www      8021:   value: 0,
                   8022:   change: function(event, ui) {
                   8023:     var newVal = \$(this).progressbar('option', 'value');
                   8024:     \$('.pblabel', this).text(LCprogressTxt);
                   8025:   }
                   8026: });
                   8027: // ]]>
                   8028: </script>
                   8029: ENDPROGRESS
                   8030: }
                   8031: 
                   8032: sub LCprogressbarUpdate_script {
                   8033:    return(<<ENDPROGRESSUPDATE);
                   8034: <style type="text/css">
                   8035: .ui-progressbar { position:relative; }
                   8036: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8037: </style>
                   8038: <script type="text/javascript">
                   8039: // <![CDATA[
1.1045    www      8040: var LCprogressTxt='---';
                   8041: 
                   8042: function LCupdateProgress(percent,progresstext,id) {
1.1041    www      8043:    LCprogressTxt=progresstext;
1.1045    www      8044:    \$('#progressbar'+id).progressbar('value',percent);
1.1041    www      8045: }
                   8046: // ]]>
                   8047: </script>
                   8048: ENDPROGRESSUPDATE
                   8049: }
                   8050: 
1.1042    www      8051: my $LClastpercent;
1.1045    www      8052: my $LCidcnt;
                   8053: my $LCcurrentid;
1.1042    www      8054: 
1.1041    www      8055: sub LCprogressbar {
1.1042    www      8056:     my ($r)=(@_);
                   8057:     $LClastpercent=0;
1.1045    www      8058:     $LCidcnt++;
                   8059:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1041    www      8060:     my $starting=&mt('Starting');
                   8061:     my $content=(<<ENDPROGBAR);
1.1045    www      8062:   <div id="progressbar$LCcurrentid">
1.1041    www      8063:     <span class="pblabel">$starting</span>
                   8064:   </div>
                   8065: ENDPROGBAR
1.1045    www      8066:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid));
1.1041    www      8067: }
                   8068: 
                   8069: sub LCprogressbarUpdate {
1.1042    www      8070:     my ($r,$val,$text)=@_;
                   8071:     unless ($val) { 
                   8072:        if ($LClastpercent) {
                   8073:            $val=$LClastpercent;
                   8074:        } else {
                   8075:            $val=0;
                   8076:        }
                   8077:     }
1.1041    www      8078:     if ($val<0) { $val=0; }
                   8079:     if ($val>100) { $val=0; }
1.1042    www      8080:     $LClastpercent=$val;
1.1041    www      8081:     unless ($text) { $text=$val.'%'; }
                   8082:     $text=&js_ready($text);
1.1044    www      8083:     &r_print($r,<<ENDUPDATE);
1.1041    www      8084: <script type="text/javascript">
                   8085: // <![CDATA[
1.1045    www      8086: LCupdateProgress($val,'$text','$LCcurrentid');
1.1041    www      8087: // ]]>
                   8088: </script>
                   8089: ENDUPDATE
1.1035    www      8090: }
                   8091: 
1.1042    www      8092: sub LCprogressbarClose {
                   8093:     my ($r)=@_;
                   8094:     $LClastpercent=0;
1.1044    www      8095:     &r_print($r,<<ENDCLOSE);
1.1042    www      8096: <script type="text/javascript">
                   8097: // <![CDATA[
1.1045    www      8098: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8099: // ]]>
                   8100: </script>
                   8101: ENDCLOSE
1.1044    www      8102: }
                   8103: 
                   8104: sub r_print {
                   8105:     my ($r,$to_print)=@_;
                   8106:     if ($r) {
                   8107:       $r->print($to_print);
                   8108:       $r->rflush();
                   8109:     } else {
                   8110:       print($to_print);
                   8111:     }
1.1042    www      8112: }
                   8113: 
1.320     albertel 8114: sub html_encode {
                   8115:     my ($result) = @_;
                   8116: 
1.322     albertel 8117:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8118:     
                   8119:     return $result;
                   8120: }
1.1044    www      8121: 
1.317     albertel 8122: sub js_ready {
                   8123:     my ($result) = @_;
                   8124: 
1.323     albertel 8125:     $result =~ s/[\n\r]/ /xmsg;
                   8126:     $result =~ s/\\/\\\\/xmsg;
                   8127:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8128:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8129:     
                   8130:     return $result;
                   8131: }
                   8132: 
1.315     albertel 8133: sub validate_page {
                   8134:     if (  exists($env{'internal.start_page'})
1.316     albertel 8135: 	  &&     $env{'internal.start_page'} > 1) {
                   8136: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8137: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8138: 				 $ENV{'request.filename'});
1.315     albertel 8139:     }
                   8140:     if (  exists($env{'internal.end_page'})
1.316     albertel 8141: 	  &&     $env{'internal.end_page'} > 1) {
                   8142: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8143: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8144: 				 $env{'request.filename'});
1.315     albertel 8145:     }
                   8146:     if (     exists($env{'internal.start_page'})
                   8147: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8148: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8149: 				 $env{'request.filename'});
1.315     albertel 8150:     }
                   8151:     if (   ! exists($env{'internal.start_page'})
                   8152: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8153: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8154: 				 $env{'request.filename'});
1.315     albertel 8155:     }
1.306     albertel 8156: }
1.315     albertel 8157: 
1.996     www      8158: 
                   8159: sub start_scrollbox {
1.1075.2.56  raeburn  8160:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8161:     unless ($outerwidth) { $outerwidth='520px'; }
                   8162:     unless ($width) { $width='500px'; }
                   8163:     unless ($height) { $height='200px'; }
1.1075    raeburn  8164:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8165:     if ($id ne '') {
1.1075.2.42  raeburn  8166:         $table_id = ' id="table_'.$id.'"';
                   8167:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8168:     }
1.1075    raeburn  8169:     if ($bgcolor ne '') {
                   8170:         $tdcol = "background-color: $bgcolor;";
                   8171:     }
1.1075.2.42  raeburn  8172:     my $nicescroll_js;
                   8173:     if ($env{'browser.mobile'}) {
                   8174:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8175:     }
1.1075    raeburn  8176:     return <<"END";
1.1075.2.42  raeburn  8177: $nicescroll_js
                   8178: 
                   8179: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8180: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8181: END
1.996     www      8182: }
                   8183: 
                   8184: sub end_scrollbox {
1.1036    www      8185:     return '</div></td></tr></table>';
1.996     www      8186: }
                   8187: 
1.1075.2.42  raeburn  8188: sub nicescroll_javascript {
                   8189:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8190:     my %options;
                   8191:     if (ref($cursor) eq 'HASH') {
                   8192:         %options = %{$cursor};
                   8193:     }
                   8194:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8195:         $options{'railalign'} = 'left';
                   8196:     }
                   8197:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8198:         my $function  = &get_users_function();
                   8199:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8200:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8201:             $options{'cursorcolor'} = '#00F';
                   8202:         }
                   8203:     }
                   8204:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8205:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8206:             $options{'cursoropacity'}='1.0';
                   8207:         }
                   8208:     } else {
                   8209:         $options{'cursoropacity'}='1.0';
                   8210:     }
                   8211:     if ($options{'cursorfixedheight'} eq 'none') {
                   8212:         delete($options{'cursorfixedheight'});
                   8213:     } else {
                   8214:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8215:     }
                   8216:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8217:         delete($options{'railoffset'});
                   8218:     }
                   8219:     my @niceoptions;
                   8220:     while (my($key,$value) = each(%options)) {
                   8221:         if ($value =~ /^\{.+\}$/) {
                   8222:             push(@niceoptions,$key.':'.$value);
                   8223:         } else {
                   8224:             push(@niceoptions,$key.':"'.$value.'"');
                   8225:         }
                   8226:     }
                   8227:     my $nicescroll_js = '
                   8228: $(document).ready(
                   8229:       function() {
                   8230:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8231:       }
                   8232: );
                   8233: ';
                   8234:     if ($framecheck) {
                   8235:         $nicescroll_js .= '
                   8236: function expand_div(caller) {
                   8237:     if (top === self) {
                   8238:         document.getElementById("'.$id.'").style.width = "auto";
                   8239:         document.getElementById("'.$id.'").style.height = "auto";
                   8240:     } else {
                   8241:         try {
                   8242:             if (parent.frames) {
                   8243:                 if (parent.frames.length > 1) {
                   8244:                     var framesrc = parent.frames[1].location.href;
                   8245:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8246:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8247:                         document.getElementById("'.$id.'").style.width = "auto";
                   8248:                         document.getElementById("'.$id.'").style.height = "auto";
                   8249:                     }
                   8250:                 }
                   8251:             }
                   8252:         } catch (e) {
                   8253:             return;
                   8254:         }
                   8255:     }
                   8256:     return;
                   8257: }
                   8258: ';
                   8259:     }
                   8260:     if ($needjsready) {
                   8261:         $nicescroll_js = '
                   8262: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8263:     } else {
                   8264:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8265:     }
                   8266:     return $nicescroll_js;
                   8267: }
                   8268: 
1.318     albertel 8269: sub simple_error_page {
1.1075.2.49  raeburn  8270:     my ($r,$title,$msg,$args) = @_;
                   8271:     if (ref($args) eq 'HASH') {
                   8272:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8273:     } else {
                   8274:         $msg = &mt($msg);
                   8275:     }
                   8276: 
1.318     albertel 8277:     my $page =
                   8278: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8279: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8280: 	&Apache::loncommon::end_page();
                   8281:     if (ref($r)) {
                   8282: 	$r->print($page);
1.327     albertel 8283: 	return;
1.318     albertel 8284:     }
                   8285:     return $page;
                   8286: }
1.347     albertel 8287: 
                   8288: {
1.610     albertel 8289:     my @row_count;
1.961     onken    8290: 
                   8291:     sub start_data_table_count {
                   8292:         unshift(@row_count, 0);
                   8293:         return;
                   8294:     }
                   8295: 
                   8296:     sub end_data_table_count {
                   8297:         shift(@row_count);
                   8298:         return;
                   8299:     }
                   8300: 
1.347     albertel 8301:     sub start_data_table {
1.1018    raeburn  8302: 	my ($add_class,$id) = @_;
1.422     albertel 8303: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8304:         my $table_id;
                   8305:         if (defined($id)) {
                   8306:             $table_id = ' id="'.$id.'"';
                   8307:         }
1.961     onken    8308: 	&start_data_table_count();
1.1018    raeburn  8309: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8310:     }
                   8311: 
                   8312:     sub end_data_table {
1.961     onken    8313: 	&end_data_table_count();
1.389     albertel 8314: 	return '</table>'."\n";;
1.347     albertel 8315:     }
                   8316: 
                   8317:     sub start_data_table_row {
1.974     wenzelju 8318: 	my ($add_class, $id) = @_;
1.610     albertel 8319: 	$row_count[0]++;
                   8320: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8321: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8322:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8323:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8324:     }
1.471     banghart 8325:     
                   8326:     sub continue_data_table_row {
1.974     wenzelju 8327: 	my ($add_class, $id) = @_;
1.610     albertel 8328: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8329: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8330:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8331:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8332:     }
1.347     albertel 8333: 
                   8334:     sub end_data_table_row {
1.389     albertel 8335: 	return '</tr>'."\n";;
1.347     albertel 8336:     }
1.367     www      8337: 
1.421     albertel 8338:     sub start_data_table_empty_row {
1.707     bisitz   8339: #	$row_count[0]++;
1.421     albertel 8340: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8341:     }
                   8342: 
                   8343:     sub end_data_table_empty_row {
                   8344: 	return '</tr>'."\n";;
                   8345:     }
                   8346: 
1.367     www      8347:     sub start_data_table_header_row {
1.389     albertel 8348: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8349:     }
                   8350: 
                   8351:     sub end_data_table_header_row {
1.389     albertel 8352: 	return '</tr>'."\n";;
1.367     www      8353:     }
1.890     droeschl 8354: 
                   8355:     sub data_table_caption {
                   8356:         my $caption = shift;
                   8357:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8358:     }
1.347     albertel 8359: }
                   8360: 
1.548     albertel 8361: =pod
                   8362: 
                   8363: =item * &inhibit_menu_check($arg)
                   8364: 
                   8365: Checks for a inhibitmenu state and generates output to preserve it
                   8366: 
                   8367: Inputs:         $arg - can be any of
                   8368:                      - undef - in which case the return value is a string 
                   8369:                                to add  into arguments list of a uri
                   8370:                      - 'input' - in which case the return value is a HTML
                   8371:                                  <form> <input> field of type hidden to
                   8372:                                  preserve the value
                   8373:                      - a url - in which case the return value is the url with
                   8374:                                the neccesary cgi args added to preserve the
                   8375:                                inhibitmenu state
                   8376:                      - a ref to a url - no return value, but the string is
                   8377:                                         updated to include the neccessary cgi
                   8378:                                         args to preserve the inhibitmenu state
                   8379: 
                   8380: =cut
                   8381: 
                   8382: sub inhibit_menu_check {
                   8383:     my ($arg) = @_;
                   8384:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8385:     if ($arg eq 'input') {
                   8386: 	if ($env{'form.inhibitmenu'}) {
                   8387: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8388: 	} else {
                   8389: 	    return
                   8390: 	}
                   8391:     }
                   8392:     if ($env{'form.inhibitmenu'}) {
                   8393: 	if (ref($arg)) {
                   8394: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8395: 	} elsif ($arg eq '') {
                   8396: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8397: 	} else {
                   8398: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8399: 	}
                   8400:     }
                   8401:     if (!ref($arg)) {
                   8402: 	return $arg;
                   8403:     }
                   8404: }
                   8405: 
1.251     albertel 8406: ###############################################
1.182     matthew  8407: 
                   8408: =pod
                   8409: 
1.549     albertel 8410: =back
                   8411: 
                   8412: =head1 User Information Routines
                   8413: 
                   8414: =over 4
                   8415: 
1.405     albertel 8416: =item * &get_users_function()
1.182     matthew  8417: 
                   8418: Used by &bodytag to determine the current users primary role.
                   8419: Returns either 'student','coordinator','admin', or 'author'.
                   8420: 
                   8421: =cut
                   8422: 
                   8423: ###############################################
                   8424: sub get_users_function {
1.815     tempelho 8425:     my $function = 'norole';
1.818     tempelho 8426:     if ($env{'request.role'}=~/^(st)/) {
                   8427:         $function='student';
                   8428:     }
1.907     raeburn  8429:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8430:         $function='coordinator';
                   8431:     }
1.258     albertel 8432:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8433:         $function='admin';
                   8434:     }
1.826     bisitz   8435:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8436:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8437:         $function='author';
                   8438:     }
                   8439:     return $function;
1.54      www      8440: }
1.99      www      8441: 
                   8442: ###############################################
                   8443: 
1.233     raeburn  8444: =pod
                   8445: 
1.821     raeburn  8446: =item * &show_course()
                   8447: 
                   8448: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8449: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8450: 
                   8451: Inputs:
                   8452: None
                   8453: 
                   8454: Outputs:
                   8455: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8456: 
                   8457: =cut
                   8458: 
                   8459: ###############################################
                   8460: sub show_course {
                   8461:     my $course = !$env{'user.adv'};
                   8462:     if (!$env{'user.adv'}) {
                   8463:         foreach my $env (keys(%env)) {
                   8464:             next if ($env !~ m/^user\.priv\./);
                   8465:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8466:                 $course = 0;
                   8467:                 last;
                   8468:             }
                   8469:         }
                   8470:     }
                   8471:     return $course;
                   8472: }
                   8473: 
                   8474: ###############################################
                   8475: 
                   8476: =pod
                   8477: 
1.542     raeburn  8478: =item * &check_user_status()
1.274     raeburn  8479: 
                   8480: Determines current status of supplied role for a
                   8481: specific user. Roles can be active, previous or future.
                   8482: 
                   8483: Inputs: 
                   8484: user's domain, user's username, course's domain,
1.375     raeburn  8485: course's number, optional section ID.
1.274     raeburn  8486: 
                   8487: Outputs:
                   8488: role status: active, previous or future. 
                   8489: 
                   8490: =cut
                   8491: 
                   8492: sub check_user_status {
1.412     raeburn  8493:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8494:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8495:     my @uroles = keys(%userinfo);
1.274     raeburn  8496:     my $srchstr;
                   8497:     my $active_chk = 'none';
1.412     raeburn  8498:     my $now = time;
1.274     raeburn  8499:     if (@uroles > 0) {
1.908     raeburn  8500:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8501:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8502:         } else {
1.412     raeburn  8503:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8504:         }
                   8505:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8506:             my $role_end = 0;
                   8507:             my $role_start = 0;
                   8508:             $active_chk = 'active';
1.412     raeburn  8509:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8510:                 $role_end = $1;
                   8511:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8512:                     $role_start = $1;
1.274     raeburn  8513:                 }
                   8514:             }
                   8515:             if ($role_start > 0) {
1.412     raeburn  8516:                 if ($now < $role_start) {
1.274     raeburn  8517:                     $active_chk = 'future';
                   8518:                 }
                   8519:             }
                   8520:             if ($role_end > 0) {
1.412     raeburn  8521:                 if ($now > $role_end) {
1.274     raeburn  8522:                     $active_chk = 'previous';
                   8523:                 }
                   8524:             }
                   8525:         }
                   8526:     }
                   8527:     return $active_chk;
                   8528: }
                   8529: 
                   8530: ###############################################
                   8531: 
                   8532: =pod
                   8533: 
1.405     albertel 8534: =item * &get_sections()
1.233     raeburn  8535: 
                   8536: Determines all the sections for a course including
                   8537: sections with students and sections containing other roles.
1.419     raeburn  8538: Incoming parameters: 
                   8539: 
                   8540: 1. domain
                   8541: 2. course number 
                   8542: 3. reference to array containing roles for which sections should 
                   8543: be gathered (optional).
                   8544: 4. reference to array containing status types for which sections 
                   8545: should be gathered (optional).
                   8546: 
                   8547: If the third argument is undefined, sections are gathered for any role. 
                   8548: If the fourth argument is undefined, sections are gathered for any status.
                   8549: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8550:  
1.374     raeburn  8551: Returns section hash (keys are section IDs, values are
                   8552: number of users in each section), subject to the
1.419     raeburn  8553: optional roles filter, optional status filter 
1.233     raeburn  8554: 
                   8555: =cut
                   8556: 
                   8557: ###############################################
                   8558: sub get_sections {
1.419     raeburn  8559:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8560:     if (!defined($cdom) || !defined($cnum)) {
                   8561:         my $cid =  $env{'request.course.id'};
                   8562: 
                   8563: 	return if (!defined($cid));
                   8564: 
                   8565:         $cdom = $env{'course.'.$cid.'.domain'};
                   8566:         $cnum = $env{'course.'.$cid.'.num'};
                   8567:     }
                   8568: 
                   8569:     my %sectioncount;
1.419     raeburn  8570:     my $now = time;
1.240     albertel 8571: 
1.1075.2.33  raeburn  8572:     my $check_students = 1;
                   8573:     my $only_students = 0;
                   8574:     if (ref($possible_roles) eq 'ARRAY') {
                   8575:         if (grep(/^st$/,@{$possible_roles})) {
                   8576:             if (@{$possible_roles} == 1) {
                   8577:                 $only_students = 1;
                   8578:             }
                   8579:         } else {
                   8580:             $check_students = 0;
                   8581:         }
                   8582:     }
                   8583: 
                   8584:     if ($check_students) {
1.276     albertel 8585: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 8586: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   8587: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  8588:         my $start_index = &Apache::loncoursedata::CL_START();
                   8589:         my $end_index = &Apache::loncoursedata::CL_END();
                   8590:         my $status;
1.366     albertel 8591: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  8592: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   8593: 				                     $data->[$status_index],
                   8594:                                                      $data->[$start_index],
                   8595:                                                      $data->[$end_index]);
                   8596:             if ($stu_status eq 'Active') {
                   8597:                 $status = 'active';
                   8598:             } elsif ($end < $now) {
                   8599:                 $status = 'previous';
                   8600:             } elsif ($start > $now) {
                   8601:                 $status = 'future';
                   8602:             } 
                   8603: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   8604:                 if ((!defined($possible_status)) || (($status ne '') && 
                   8605:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   8606: 		    $sectioncount{$section}++;
                   8607:                 }
1.240     albertel 8608: 	    }
                   8609: 	}
                   8610:     }
1.1075.2.33  raeburn  8611:     if ($only_students) {
                   8612:         return %sectioncount;
                   8613:     }
1.240     albertel 8614:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8615:     foreach my $user (sort(keys(%courseroles))) {
                   8616: 	if ($user !~ /^(\w{2})/) { next; }
                   8617: 	my ($role) = ($user =~ /^(\w{2})/);
                   8618: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  8619: 	my ($section,$status);
1.240     albertel 8620: 	if ($role eq 'cr' &&
                   8621: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   8622: 	    $section=$1;
                   8623: 	}
                   8624: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   8625: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  8626:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   8627:         if ($end == -1 && $start == -1) {
                   8628:             next; #deleted role
                   8629:         }
                   8630:         if (!defined($possible_status)) { 
                   8631:             $sectioncount{$section}++;
                   8632:         } else {
                   8633:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   8634:                 $status = 'active';
                   8635:             } elsif ($end < $now) {
                   8636:                 $status = 'future';
                   8637:             } elsif ($start > $now) {
                   8638:                 $status = 'previous';
                   8639:             }
                   8640:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   8641:                 $sectioncount{$section}++;
                   8642:             }
                   8643:         }
1.233     raeburn  8644:     }
1.366     albertel 8645:     return %sectioncount;
1.233     raeburn  8646: }
                   8647: 
1.274     raeburn  8648: ###############################################
1.294     raeburn  8649: 
                   8650: =pod
1.405     albertel 8651: 
                   8652: =item * &get_course_users()
                   8653: 
1.275     raeburn  8654: Retrieves usernames:domains for users in the specified course
                   8655: with specific role(s), and access status. 
                   8656: 
                   8657: Incoming parameters:
1.277     albertel 8658: 1. course domain
                   8659: 2. course number
                   8660: 3. access status: users must have - either active, 
1.275     raeburn  8661: previous, future, or all.
1.277     albertel 8662: 4. reference to array of permissible roles
1.288     raeburn  8663: 5. reference to array of section restrictions (optional)
                   8664: 6. reference to results object (hash of hashes).
                   8665: 7. reference to optional userdata hash
1.609     raeburn  8666: 8. reference to optional statushash
1.630     raeburn  8667: 9. flag if privileged users (except those set to unhide in
                   8668:    course settings) should be excluded    
1.609     raeburn  8669: Keys of top level results hash are roles.
1.275     raeburn  8670: Keys of inner hashes are username:domain, with 
                   8671: values set to access type.
1.288     raeburn  8672: Optional userdata hash returns an array with arguments in the 
                   8673: same order as loncoursedata::get_classlist() for student data.
                   8674: 
1.609     raeburn  8675: Optional statushash returns
                   8676: 
1.288     raeburn  8677: Entries for end, start, section and status are blank because
                   8678: of the possibility of multiple values for non-student roles.
                   8679: 
1.275     raeburn  8680: =cut
1.405     albertel 8681: 
1.275     raeburn  8682: ###############################################
1.405     albertel 8683: 
1.275     raeburn  8684: sub get_course_users {
1.630     raeburn  8685:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  8686:     my %idx = ();
1.419     raeburn  8687:     my %seclists;
1.288     raeburn  8688: 
                   8689:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   8690:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   8691:     $idx{end} = &Apache::loncoursedata::CL_END();
                   8692:     $idx{start} = &Apache::loncoursedata::CL_START();
                   8693:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   8694:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   8695:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   8696:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   8697: 
1.290     albertel 8698:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 8699:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  8700:         my $now = time;
1.277     albertel 8701:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  8702:             my $match = 0;
1.412     raeburn  8703:             my $secmatch = 0;
1.419     raeburn  8704:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  8705:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  8706:             if ($section eq '') {
                   8707:                 $section = 'none';
                   8708:             }
1.291     albertel 8709:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8710:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8711:                     $secmatch = 1;
                   8712:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 8713:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8714:                         $secmatch = 1;
                   8715:                     }
                   8716:                 } else {  
1.419     raeburn  8717: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  8718: 		        $secmatch = 1;
                   8719:                     }
1.290     albertel 8720: 		}
1.412     raeburn  8721:                 if (!$secmatch) {
                   8722:                     next;
                   8723:                 }
1.419     raeburn  8724:             }
1.275     raeburn  8725:             if (defined($$types{'active'})) {
1.288     raeburn  8726:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  8727:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  8728:                     $match = 1;
1.275     raeburn  8729:                 }
                   8730:             }
                   8731:             if (defined($$types{'previous'})) {
1.609     raeburn  8732:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  8733:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  8734:                     $match = 1;
1.275     raeburn  8735:                 }
                   8736:             }
                   8737:             if (defined($$types{'future'})) {
1.609     raeburn  8738:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  8739:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  8740:                     $match = 1;
1.275     raeburn  8741:                 }
                   8742:             }
1.609     raeburn  8743:             if ($match) {
                   8744:                 push(@{$seclists{$student}},$section);
                   8745:                 if (ref($userdata) eq 'HASH') {
                   8746:                     $$userdata{$student} = $$classlist{$student};
                   8747:                 }
                   8748:                 if (ref($statushash) eq 'HASH') {
                   8749:                     $statushash->{$student}{'st'}{$section} = $status;
                   8750:                 }
1.288     raeburn  8751:             }
1.275     raeburn  8752:         }
                   8753:     }
1.412     raeburn  8754:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  8755:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   8756:         my $now = time;
1.609     raeburn  8757:         my %displaystatus = ( previous => 'Expired',
                   8758:                               active   => 'Active',
                   8759:                               future   => 'Future',
                   8760:                             );
1.1075.2.36  raeburn  8761:         my (%nothide,@possdoms);
1.630     raeburn  8762:         if ($hidepriv) {
                   8763:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   8764:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   8765:                 if ($user !~ /:/) {
                   8766:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   8767:                 } else {
                   8768:                     $nothide{$user} = 1;
                   8769:                 }
                   8770:             }
1.1075.2.36  raeburn  8771:             my @possdoms = ($cdom);
                   8772:             if ($coursehash{'checkforpriv'}) {
                   8773:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   8774:             }
1.630     raeburn  8775:         }
1.439     raeburn  8776:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  8777:             my $match = 0;
1.412     raeburn  8778:             my $secmatch = 0;
1.439     raeburn  8779:             my $status;
1.412     raeburn  8780:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  8781:             $user =~ s/:$//;
1.439     raeburn  8782:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   8783:             if ($end == -1 || $start == -1) {
                   8784:                 next;
                   8785:             }
                   8786:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   8787:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  8788:                 my ($uname,$udom) = split(/:/,$user);
                   8789:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 8790:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  8791:                         $secmatch = 1;
                   8792:                     } elsif ($usec eq '') {
1.420     albertel 8793:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  8794:                             $secmatch = 1;
                   8795:                         }
                   8796:                     } else {
                   8797:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   8798:                             $secmatch = 1;
                   8799:                         }
                   8800:                     }
                   8801:                     if (!$secmatch) {
                   8802:                         next;
                   8803:                     }
1.288     raeburn  8804:                 }
1.419     raeburn  8805:                 if ($usec eq '') {
                   8806:                     $usec = 'none';
                   8807:                 }
1.275     raeburn  8808:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  8809:                     if ($hidepriv) {
1.1075.2.36  raeburn  8810:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  8811:                             (!$nothide{$uname.':'.$udom})) {
                   8812:                             next;
                   8813:                         }
                   8814:                     }
1.503     raeburn  8815:                     if ($end > 0 && $end < $now) {
1.439     raeburn  8816:                         $status = 'previous';
                   8817:                     } elsif ($start > $now) {
                   8818:                         $status = 'future';
                   8819:                     } else {
                   8820:                         $status = 'active';
                   8821:                     }
1.277     albertel 8822:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  8823:                         if ($status eq $type) {
1.420     albertel 8824:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  8825:                                 push(@{$$users{$role}{$user}},$type);
                   8826:                             }
1.288     raeburn  8827:                             $match = 1;
                   8828:                         }
                   8829:                     }
1.419     raeburn  8830:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   8831:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   8832: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   8833:                         }
1.420     albertel 8834:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  8835:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   8836:                         }
1.609     raeburn  8837:                         if (ref($statushash) eq 'HASH') {
                   8838:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   8839:                         }
1.275     raeburn  8840:                     }
                   8841:                 }
                   8842:             }
                   8843:         }
1.290     albertel 8844:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  8845:             if ((defined($cdom)) && (defined($cnum))) {
                   8846:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   8847:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   8848:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  8849:                     next if ($owner eq '');
                   8850:                     my ($ownername,$ownerdom);
                   8851:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   8852:                         $ownername = $1;
                   8853:                         $ownerdom = $2;
                   8854:                     } else {
                   8855:                         $ownername = $owner;
                   8856:                         $ownerdom = $cdom;
                   8857:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  8858:                     }
                   8859:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 8860:                     if (defined($userdata) && 
1.609     raeburn  8861: 			!exists($$userdata{$owner})) {
                   8862: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   8863:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   8864:                             push(@{$seclists{$owner}},'none');
                   8865:                         }
                   8866:                         if (ref($statushash) eq 'HASH') {
                   8867:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  8868:                         }
1.290     albertel 8869: 		    }
1.279     raeburn  8870:                 }
                   8871:             }
                   8872:         }
1.419     raeburn  8873:         foreach my $user (keys(%seclists)) {
                   8874:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   8875:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   8876:         }
1.275     raeburn  8877:     }
                   8878:     return;
                   8879: }
                   8880: 
1.288     raeburn  8881: sub get_user_info {
                   8882:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 8883:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   8884: 	&plainname($uname,$udom,'lastname');
1.291     albertel 8885:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  8886:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  8887:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   8888:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  8889:     return;
                   8890: }
1.275     raeburn  8891: 
1.472     raeburn  8892: ###############################################
                   8893: 
                   8894: =pod
                   8895: 
                   8896: =item * &get_user_quota()
                   8897: 
1.1075.2.41  raeburn  8898: Retrieves quota assigned for storage of user files.
                   8899: Default is to report quota for portfolio files.
1.472     raeburn  8900: 
                   8901: Incoming parameters:
                   8902: 1. user's username
                   8903: 2. user's domain
1.1075.2.41  raeburn  8904: 3. quota name - portfolio, author, or course
                   8905:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  8906: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  8907:    course
1.472     raeburn  8908: 
                   8909: Returns:
1.1075.2.58  raeburn  8910: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  8911: 2. (Optional) Type of setting: custom or default
                   8912:    (individually assigned or default for user's 
                   8913:    institutional status).
                   8914: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   8915:    or student - types as defined in localenroll::inst_usertypes 
                   8916:    for user's domain, which determines default quota for user.
                   8917: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  8918: 
                   8919: If a value has been stored in the user's environment, 
1.536     raeburn  8920: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  8921: defined for the user's institutional status(es) in the domain.
1.472     raeburn  8922: 
                   8923: =cut
                   8924: 
                   8925: ###############################################
                   8926: 
                   8927: 
                   8928: sub get_user_quota {
1.1075.2.42  raeburn  8929:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  8930:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  8931:     if (!defined($udom)) {
                   8932:         $udom = $env{'user.domain'};
                   8933:     }
                   8934:     if (!defined($uname)) {
                   8935:         $uname = $env{'user.name'};
                   8936:     }
                   8937:     if (($udom eq '' || $uname eq '') ||
                   8938:         ($udom eq 'public') && ($uname eq 'public')) {
                   8939:         $quota = 0;
1.536     raeburn  8940:         $quotatype = 'default';
                   8941:         $defquota = 0; 
1.472     raeburn  8942:     } else {
1.536     raeburn  8943:         my $inststatus;
1.1075.2.41  raeburn  8944:         if ($quotaname eq 'course') {
                   8945:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   8946:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   8947:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   8948:             } else {
                   8949:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   8950:                 $quota = $cenv{'internal.uploadquota'};
                   8951:             }
1.536     raeburn  8952:         } else {
1.1075.2.41  raeburn  8953:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   8954:                 if ($quotaname eq 'author') {
                   8955:                     $quota = $env{'environment.authorquota'};
                   8956:                 } else {
                   8957:                     $quota = $env{'environment.portfolioquota'};
                   8958:                 }
                   8959:                 $inststatus = $env{'environment.inststatus'};
                   8960:             } else {
                   8961:                 my %userenv = 
                   8962:                     &Apache::lonnet::get('environment',['portfolioquota',
                   8963:                                          'authorquota','inststatus'],$udom,$uname);
                   8964:                 my ($tmp) = keys(%userenv);
                   8965:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   8966:                     if ($quotaname eq 'author') {
                   8967:                         $quota = $userenv{'authorquota'};
                   8968:                     } else {
                   8969:                         $quota = $userenv{'portfolioquota'};
                   8970:                     }
                   8971:                     $inststatus = $userenv{'inststatus'};
                   8972:                 } else {
                   8973:                     undef(%userenv);
                   8974:                 }
                   8975:             }
                   8976:         }
                   8977:         if ($quota eq '' || wantarray) {
                   8978:             if ($quotaname eq 'course') {
                   8979:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  8980:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   8981:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  8982:                     $defquota = $domdefs{$crstype.'quota'};
                   8983:                 }
                   8984:                 if ($defquota eq '') {
                   8985:                     $defquota = 500;
                   8986:                 }
1.1075.2.41  raeburn  8987:             } else {
                   8988:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   8989:             }
                   8990:             if ($quota eq '') {
                   8991:                 $quota = $defquota;
                   8992:                 $quotatype = 'default';
                   8993:             } else {
                   8994:                 $quotatype = 'custom';
                   8995:             }
1.472     raeburn  8996:         }
                   8997:     }
1.536     raeburn  8998:     if (wantarray) {
                   8999:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9000:     } else {
                   9001:         return $quota;
                   9002:     }
1.472     raeburn  9003: }
                   9004: 
                   9005: ###############################################
                   9006: 
                   9007: =pod
                   9008: 
                   9009: =item * &default_quota()
                   9010: 
1.536     raeburn  9011: Retrieves default quota assigned for storage of user portfolio files,
                   9012: given an (optional) user's institutional status.
1.472     raeburn  9013: 
                   9014: Incoming parameters:
1.1075.2.42  raeburn  9015: 
1.472     raeburn  9016: 1. domain
1.536     raeburn  9017: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9018:    status types (e.g., faculty, staff, student etc.)
                   9019:    which apply to the user for whom the default is being retrieved.
                   9020:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9021:    default quota will be returned.
                   9022: 3.  quota name - portfolio, author, or course
                   9023:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9024: 
                   9025: Returns:
1.1075.2.42  raeburn  9026: 
1.1075.2.58  raeburn  9027: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9028: 2. (Optional) institutional type which determined the value of the
                   9029:    default quota.
1.472     raeburn  9030: 
                   9031: If a value has been stored in the domain's configuration db,
                   9032: it will return that, otherwise it returns 20 (for backwards 
                   9033: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9034: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9035: 
1.536     raeburn  9036: If the user's status includes multiple types (e.g., staff and student),
                   9037: the largest default quota which applies to the user determines the
                   9038: default quota returned.
                   9039: 
1.472     raeburn  9040: =cut
                   9041: 
                   9042: ###############################################
                   9043: 
                   9044: 
                   9045: sub default_quota {
1.1075.2.41  raeburn  9046:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9047:     my ($defquota,$settingstatus);
                   9048:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9049:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9050:     my $key = 'defaultquota';
                   9051:     if ($quotaname eq 'author') {
                   9052:         $key = 'authorquota';
                   9053:     }
1.622     raeburn  9054:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9055:         if ($inststatus ne '') {
1.765     raeburn  9056:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9057:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9058:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9059:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9060:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9061:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9062:                             $settingstatus = $item;
1.1075.2.41  raeburn  9063:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9064:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9065:                             $settingstatus = $item;
                   9066:                         }
                   9067:                     }
1.1075.2.41  raeburn  9068:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9069:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9070:                         if ($defquota eq '') {
                   9071:                             $defquota = $quotahash{'quotas'}{$item};
                   9072:                             $settingstatus = $item;
                   9073:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9074:                             $defquota = $quotahash{'quotas'}{$item};
                   9075:                             $settingstatus = $item;
                   9076:                         }
1.536     raeburn  9077:                     }
                   9078:                 }
                   9079:             }
                   9080:         }
                   9081:         if ($defquota eq '') {
1.1075.2.41  raeburn  9082:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9083:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9084:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9085:                 $defquota = $quotahash{'quotas'}{'default'};
                   9086:             }
1.536     raeburn  9087:             $settingstatus = 'default';
1.1075.2.42  raeburn  9088:             if ($defquota eq '') {
                   9089:                 if ($quotaname eq 'author') {
                   9090:                     $defquota = 500;
                   9091:                 }
                   9092:             }
1.536     raeburn  9093:         }
                   9094:     } else {
                   9095:         $settingstatus = 'default';
1.1075.2.41  raeburn  9096:         if ($quotaname eq 'author') {
                   9097:             $defquota = 500;
                   9098:         } else {
                   9099:             $defquota = 20;
                   9100:         }
1.536     raeburn  9101:     }
                   9102:     if (wantarray) {
                   9103:         return ($defquota,$settingstatus);
1.472     raeburn  9104:     } else {
1.536     raeburn  9105:         return $defquota;
1.472     raeburn  9106:     }
                   9107: }
                   9108: 
1.1075.2.41  raeburn  9109: ###############################################
                   9110: 
                   9111: =pod
                   9112: 
1.1075.2.42  raeburn  9113: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9114: 
                   9115: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9116: of existing file within authoring space will cause quota for the authoring
                   9117: space to be exceeded.
                   9118: 
                   9119: Same, if upload of a file directly to a course/community via Course Editor
                   9120: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9121: 
1.1075.2.61  raeburn  9122: Inputs: 7 
1.1075.2.42  raeburn  9123: 1. username or coursenum
1.1075.2.41  raeburn  9124: 2. domain
1.1075.2.42  raeburn  9125: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9126: 4. filename of file for which action is being requested
                   9127: 5. filesize (kB) of file
                   9128: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9129: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9130: 
                   9131: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9132:          otherwise return null.
                   9133: 
1.1075.2.42  raeburn  9134: =back
                   9135: 
1.1075.2.41  raeburn  9136: =cut
                   9137: 
1.1075.2.42  raeburn  9138: sub excess_filesize_warning {
1.1075.2.59  raeburn  9139:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9140:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9141:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9142:     if ($context eq 'author') {
                   9143:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9144:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9145:     } else {
                   9146:         foreach my $subdir ('docs','supplemental') {
                   9147:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9148:         }
                   9149:     }
1.1075.2.41  raeburn  9150:     $disk_quota = int($disk_quota * 1000);
                   9151:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9152:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9153:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9154:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9155:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9156:                             $disk_quota,$current_disk_usage).
                   9157:                '</p>';
                   9158:     }
                   9159:     return;
                   9160: }
                   9161: 
                   9162: ###############################################
                   9163: 
                   9164: 
1.384     raeburn  9165: sub get_secgrprole_info {
                   9166:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9167:     my %sections_count = &get_sections($cdom,$cnum);
                   9168:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9169:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9170:     my @groups = sort(keys(%curr_groups));
                   9171:     my $allroles = [];
                   9172:     my $rolehash;
                   9173:     my $accesshash = {
                   9174:                      active => 'Currently has access',
                   9175:                      future => 'Will have future access',
                   9176:                      previous => 'Previously had access',
                   9177:                   };
                   9178:     if ($needroles) {
                   9179:         $rolehash = {'all' => 'all'};
1.385     albertel 9180:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9181: 	if (&Apache::lonnet::error(%user_roles)) {
                   9182: 	    undef(%user_roles);
                   9183: 	}
                   9184:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9185:             my ($role)=split(/\:/,$item,2);
                   9186:             if ($role eq 'cr') { next; }
                   9187:             if ($role =~ /^cr/) {
                   9188:                 $$rolehash{$role} = (split('/',$role))[3];
                   9189:             } else {
                   9190:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9191:             }
                   9192:         }
                   9193:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9194:             push(@{$allroles},$key);
                   9195:         }
                   9196:         push (@{$allroles},'st');
                   9197:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9198:     }
                   9199:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9200: }
                   9201: 
1.555     raeburn  9202: sub user_picker {
1.994     raeburn  9203:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context) = @_;
1.555     raeburn  9204:     my $currdom = $dom;
                   9205:     my %curr_selected = (
                   9206:                         srchin => 'dom',
1.580     raeburn  9207:                         srchby => 'lastname',
1.555     raeburn  9208:                       );
                   9209:     my $srchterm;
1.625     raeburn  9210:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9211:         if ($srch->{'srchby'} ne '') {
                   9212:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9213:         }
                   9214:         if ($srch->{'srchin'} ne '') {
                   9215:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9216:         }
                   9217:         if ($srch->{'srchtype'} ne '') {
                   9218:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9219:         }
                   9220:         if ($srch->{'srchdomain'} ne '') {
                   9221:             $currdom = $srch->{'srchdomain'};
                   9222:         }
                   9223:         $srchterm = $srch->{'srchterm'};
                   9224:     }
1.1075.2.98  raeburn  9225:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9226:                     'usr'       => 'Search criteria',
1.563     raeburn  9227:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9228:                     'uname'     => 'username',
                   9229:                     'lastname'  => 'last name',
1.555     raeburn  9230:                     'lastfirst' => 'last name, first name',
1.558     albertel 9231:                     'crs'       => 'in this course',
1.576     raeburn  9232:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9233:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9234:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9235:                     'exact'     => 'is',
                   9236:                     'contains'  => 'contains',
1.569     raeburn  9237:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9238:                                        );
                   9239:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9240:                     'youm'      => "You must include some text to search for.",
                   9241:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9242:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9243:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9244:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9245:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9246:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9247:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9248:                                        );
1.1075.2.98  raeburn  9249:     &html_escape(\%html_lt);
                   9250:     &js_escape(\%js_lt);
1.563     raeburn  9251:     my $domform = &select_dom_form($currdom,'srchdomain',1,1);
                   9252:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9253: 
                   9254:     my @srchins = ('crs','dom','alc','instd');
                   9255: 
                   9256:     foreach my $option (@srchins) {
                   9257:         # FIXME 'alc' option unavailable until 
                   9258:         #       loncreateuser::print_user_query_page()
                   9259:         #       has been completed.
                   9260:         next if ($option eq 'alc');
1.880     raeburn  9261:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9262:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.563     raeburn  9263:         if ($curr_selected{'srchin'} eq $option) {
                   9264:             $srchinsel .= ' 
1.1075.2.98  raeburn  9265:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9266:         } else {
                   9267:             $srchinsel .= '
1.1075.2.98  raeburn  9268:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9269:         }
1.555     raeburn  9270:     }
1.563     raeburn  9271:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9272: 
                   9273:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9274:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9275:         if ($curr_selected{'srchby'} eq $option) {
                   9276:             $srchbysel .= '
1.1075.2.98  raeburn  9277:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9278:         } else {
                   9279:             $srchbysel .= '
1.1075.2.98  raeburn  9280:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9281:          }
                   9282:     }
                   9283:     $srchbysel .= "\n  </select>\n";
                   9284: 
                   9285:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9286:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9287:         if ($curr_selected{'srchtype'} eq $option) {
                   9288:             $srchtypesel .= '
1.1075.2.98  raeburn  9289:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9290:         } else {
                   9291:             $srchtypesel .= '
1.1075.2.98  raeburn  9292:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9293:         }
                   9294:     }
                   9295:     $srchtypesel .= "\n  </select>\n";
                   9296: 
1.558     albertel 9297:     my ($newuserscript,$new_user_create);
1.994     raeburn  9298:     my $context_dom = $env{'request.role.domain'};
                   9299:     if ($context eq 'requestcrs') {
                   9300:         if ($env{'form.coursedom'} ne '') { 
                   9301:             $context_dom = $env{'form.coursedom'};
                   9302:         }
                   9303:     }
1.556     raeburn  9304:     if ($forcenewuser) {
1.576     raeburn  9305:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9306:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9307:                 if ($cancreate) {
                   9308:                     $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>';
                   9309:                 } else {
1.799     bisitz   9310:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9311:                     my %usertypetext = (
                   9312:                         official   => 'institutional',
                   9313:                         unofficial => 'non-institutional',
                   9314:                     );
1.799     bisitz   9315:                     $new_user_create = '<p class="LC_warning">'
                   9316:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9317:                                       .' '
                   9318:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9319:                                           ,'<a href="'.$helplink.'">','</a>')
                   9320:                                       .'</p><br />';
1.627     raeburn  9321:                 }
1.576     raeburn  9322:             }
                   9323:         }
                   9324: 
1.556     raeburn  9325:         $newuserscript = <<"ENDSCRIPT";
                   9326: 
1.570     raeburn  9327: function setSearch(createnew,callingForm) {
1.556     raeburn  9328:     if (createnew == 1) {
1.570     raeburn  9329:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9330:             if (callingForm.srchby.options[i].value == 'uname') {
                   9331:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9332:             }
                   9333:         }
1.570     raeburn  9334:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9335:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9336: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9337:             }
                   9338:         }
1.570     raeburn  9339:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9340:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9341:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9342:             }
                   9343:         }
1.570     raeburn  9344:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9345:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9346:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9347:             }
                   9348:         }
                   9349:     }
                   9350: }
                   9351: ENDSCRIPT
1.558     albertel 9352: 
1.556     raeburn  9353:     }
                   9354: 
1.555     raeburn  9355:     my $output = <<"END_BLOCK";
1.556     raeburn  9356: <script type="text/javascript">
1.824     bisitz   9357: // <![CDATA[
1.570     raeburn  9358: function validateEntry(callingForm) {
1.558     albertel 9359: 
1.556     raeburn  9360:     var checkok = 1;
1.558     albertel 9361:     var srchin;
1.570     raeburn  9362:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9363: 	if ( callingForm.srchin[i].checked ) {
                   9364: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9365: 	}
                   9366:     }
                   9367: 
1.570     raeburn  9368:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9369:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9370:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9371:     var srchterm =  callingForm.srchterm.value;
                   9372:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9373:     var msg = "";
                   9374: 
                   9375:     if (srchterm == "") {
                   9376:         checkok = 0;
1.1075.2.98  raeburn  9377:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9378:     }
                   9379: 
1.569     raeburn  9380:     if (srchtype== 'begins') {
                   9381:         if (srchterm.length < 2) {
                   9382:             checkok = 0;
1.1075.2.98  raeburn  9383:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9384:         }
                   9385:     }
                   9386: 
1.556     raeburn  9387:     if (srchtype== 'contains') {
                   9388:         if (srchterm.length < 3) {
                   9389:             checkok = 0;
1.1075.2.98  raeburn  9390:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9391:         }
                   9392:     }
                   9393:     if (srchin == 'instd') {
                   9394:         if (srchdomain == '') {
                   9395:             checkok = 0;
1.1075.2.98  raeburn  9396:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9397:         }
                   9398:     }
                   9399:     if (srchin == 'dom') {
                   9400:         if (srchdomain == '') {
                   9401:             checkok = 0;
1.1075.2.98  raeburn  9402:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9403:         }
                   9404:     }
                   9405:     if (srchby == 'lastfirst') {
                   9406:         if (srchterm.indexOf(",") == -1) {
                   9407:             checkok = 0;
1.1075.2.98  raeburn  9408:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9409:         }
                   9410:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9411:             checkok = 0;
1.1075.2.98  raeburn  9412:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9413:         }
                   9414:     }
                   9415:     if (checkok == 0) {
1.1075.2.98  raeburn  9416:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9417:         return;
                   9418:     }
                   9419:     if (checkok == 1) {
1.570     raeburn  9420:         callingForm.submit();
1.556     raeburn  9421:     }
                   9422: }
                   9423: 
                   9424: $newuserscript
                   9425: 
1.824     bisitz   9426: // ]]>
1.556     raeburn  9427: </script>
1.558     albertel 9428: 
                   9429: $new_user_create
                   9430: 
1.555     raeburn  9431: END_BLOCK
1.558     albertel 9432: 
1.876     raeburn  9433:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9434:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9435:                $domform.
                   9436:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9437:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9438:                $srchbysel.
                   9439:                $srchtypesel. 
                   9440:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9441:                $srchinsel.
                   9442:                &Apache::lonhtmlcommon::row_closure(1). 
                   9443:                &Apache::lonhtmlcommon::end_pick_box().
                   9444:                '<br />';
1.555     raeburn  9445:     return $output;
                   9446: }
                   9447: 
1.612     raeburn  9448: sub user_rule_check {
1.615     raeburn  9449:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9450:     my ($response,%inst_response);
1.612     raeburn  9451:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9452:         if (keys(%{$usershash}) > 1) {
                   9453:             my (%by_username,%by_id,%userdoms);
                   9454:             my $checkid;
1.612     raeburn  9455:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9456:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9457:                     $checkid = 1;
                   9458:                 }
                   9459:             }
                   9460:             foreach my $user (keys(%{$usershash})) {
                   9461:                 my ($uname,$udom) = split(/:/,$user);
                   9462:                 if ($checkid) {
                   9463:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9464:                         if ($usershash->{$user}->{'id'} ne '') {
                   9465:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9466:                             $userdoms{$udom} = 1;
                   9467:                             if (ref($inst_results) eq 'HASH') {
                   9468:                                 $inst_results->{$uname.':'.$udom} = {};
                   9469:                             }
                   9470:                         }
                   9471:                     }
                   9472:                 } else {
                   9473:                     $by_username{$udom}{$uname} = 1;
                   9474:                     $userdoms{$udom} = 1;
                   9475:                     if (ref($inst_results) eq 'HASH') {
                   9476:                         $inst_results->{$uname.':'.$udom} = {};
                   9477:                     }
                   9478:                 }
                   9479:             }
                   9480:             foreach my $udom (keys(%userdoms)) {
                   9481:                 if (!$got_rules->{$udom}) {
                   9482:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9483:                                                              ['usercreation'],$udom);
                   9484:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9485:                         foreach my $item ('username','id') {
                   9486:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9487:                                 $$curr_rules{$udom}{$item} =
                   9488:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9489:                             }
                   9490:                         }
                   9491:                     }
                   9492:                     $got_rules->{$udom} = 1;
                   9493:                 }
                   9494:             }
                   9495:             if ($checkid) {
                   9496:                 foreach my $udom (keys(%by_id)) {
                   9497:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9498:                     if ($outcome eq 'ok') {
                   9499:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9500:                             my $uname = $by_id{$udom}{$id};
                   9501:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9502:                         }
                   9503:                         if (ref($results) eq 'HASH') {
                   9504:                             foreach my $uname (keys(%{$results})) {
                   9505:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9506:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9507:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9508:                                 }
                   9509:                             }
                   9510:                         }
                   9511:                     }
1.612     raeburn  9512:                 }
1.615     raeburn  9513:             } else {
1.1075.2.99  raeburn  9514:                 foreach my $udom (keys(%by_username)) {
                   9515:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9516:                     if ($outcome eq 'ok') {
                   9517:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9518:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9519:                         }
                   9520:                         if (ref($results) eq 'HASH') {
                   9521:                             foreach my $uname (keys(%{$results})) {
                   9522:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9523:                             }
                   9524:                         }
                   9525:                     }
                   9526:                 }
1.612     raeburn  9527:             }
1.1075.2.99  raeburn  9528:         } elsif (keys(%{$usershash}) == 1) {
                   9529:             my $user = (keys(%{$usershash}))[0];
                   9530:             my ($uname,$udom) = split(/:/,$user);
                   9531:             if (($udom ne '') && ($uname ne '')) {
                   9532:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9533:                     if (ref($checks) eq 'HASH') {
                   9534:                         if (defined($checks->{'username'})) {
                   9535:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   9536:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9537:                         } elsif (defined($checks->{'id'})) {
                   9538:                             if ($usershash->{$user}->{'id'} ne '') {
                   9539:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9540:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9541:                                                                   $usershash->{$user}->{'id'});
                   9542:                             } else {
                   9543:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9544:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   9545:                             }
                   9546:                         }
                   9547:                     } else {
                   9548:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   9549:                             &Apache::lonnet::get_instuser($udom,$uname);
                   9550:                        return;
                   9551:                     }
                   9552:                     if (!$got_rules->{$udom}) {
                   9553:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9554:                                                                  ['usercreation'],$udom);
                   9555:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9556:                             foreach my $item ('username','id') {
                   9557:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9558:                                    $$curr_rules{$udom}{$item} =
                   9559:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   9560:                                 }
                   9561:                             }
1.585     raeburn  9562:                         }
1.1075.2.99  raeburn  9563:                         $got_rules->{$udom} = 1;
1.585     raeburn  9564:                     }
                   9565:                 }
1.1075.2.99  raeburn  9566:             } else {
                   9567:                 return;
                   9568:             }
                   9569:         } else {
                   9570:             return;
                   9571:         }
                   9572:         foreach my $user (keys(%{$usershash})) {
                   9573:             my ($uname,$udom) = split(/:/,$user);
                   9574:             next if (($udom eq '') || ($uname eq ''));
                   9575:             my $id;
                   9576:             if (ref($inst_results) eq 'HASH') {
                   9577:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   9578:                     $id = $inst_results->{$user}->{'id'};
                   9579:                 }
                   9580:             }
                   9581:             if ($id eq '') {
                   9582:                 if (ref($usershash->{$user})) {
                   9583:                     $id = $usershash->{$user}->{'id'};
                   9584:                 }
1.585     raeburn  9585:             }
1.612     raeburn  9586:             foreach my $item (keys(%{$checks})) {
                   9587:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   9588:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   9589:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  9590:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   9591:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  9592:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   9593:                                 if ($rule_check{$rule}) {
                   9594:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  9595:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  9596:                                         if (ref($inst_results) eq 'HASH') {
                   9597:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   9598:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   9599:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  9600:                                                 } elsif ($item eq 'id') {
                   9601:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   9602:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   9603:                                                     }
1.615     raeburn  9604:                                                 }
1.612     raeburn  9605:                                             }
                   9606:                                         }
1.615     raeburn  9607:                                     }
                   9608:                                     last;
1.585     raeburn  9609:                                 }
                   9610:                             }
                   9611:                         }
                   9612:                     }
                   9613:                 }
                   9614:             }
                   9615:         }
                   9616:     }
1.612     raeburn  9617:     return;
                   9618: }
                   9619: 
                   9620: sub user_rule_formats {
                   9621:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   9622:     my %text = ( 
                   9623:                  'username' => 'Usernames',
                   9624:                  'id'       => 'IDs',
                   9625:                );
                   9626:     my $output;
                   9627:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   9628:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   9629:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  9630:             $output = '<br />'.
                   9631:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   9632:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   9633:                       ' <ul>';
1.612     raeburn  9634:             foreach my $rule (@{$ruleorder}) {
                   9635:                 if (ref($curr_rules) eq 'ARRAY') {
                   9636:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   9637:                         if (ref($rules->{$rule}) eq 'HASH') {
                   9638:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   9639:                                         $rules->{$rule}{'desc'}.'</li>';
                   9640:                         }
                   9641:                     }
                   9642:                 }
                   9643:             }
                   9644:             $output .= '</ul>';
                   9645:         }
                   9646:     }
                   9647:     return $output;
                   9648: }
                   9649: 
                   9650: sub instrule_disallow_msg {
1.615     raeburn  9651:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  9652:     my $response;
                   9653:     my %text = (
                   9654:                   item   => 'username',
                   9655:                   items  => 'usernames',
                   9656:                   match  => 'matches',
                   9657:                   do     => 'does',
                   9658:                   action => 'a username',
                   9659:                   one    => 'one',
                   9660:                );
                   9661:     if ($count > 1) {
                   9662:         $text{'item'} = 'usernames';
                   9663:         $text{'match'} ='match';
                   9664:         $text{'do'} = 'do';
                   9665:         $text{'action'} = 'usernames',
                   9666:         $text{'one'} = 'ones';
                   9667:     }
                   9668:     if ($checkitem eq 'id') {
                   9669:         $text{'items'} = 'IDs';
                   9670:         $text{'item'} = 'ID';
                   9671:         $text{'action'} = 'an ID';
1.615     raeburn  9672:         if ($count > 1) {
                   9673:             $text{'item'} = 'IDs';
                   9674:             $text{'action'} = 'IDs';
                   9675:         }
1.612     raeburn  9676:     }
1.674     bisitz   9677:     $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  9678:     if ($mode eq 'upload') {
                   9679:         if ($checkitem eq 'username') {
                   9680:             $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'}.");
                   9681:         } elsif ($checkitem eq 'id') {
1.674     bisitz   9682:             $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  9683:         }
1.669     raeburn  9684:     } elsif ($mode eq 'selfcreate') {
                   9685:         if ($checkitem eq 'id') {
                   9686:             $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.");
                   9687:         }
1.615     raeburn  9688:     } else {
                   9689:         if ($checkitem eq 'username') {
                   9690:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   9691:         } elsif ($checkitem eq 'id') {
                   9692:             $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.");
                   9693:         }
1.612     raeburn  9694:     }
                   9695:     return $response;
1.585     raeburn  9696: }
                   9697: 
1.624     raeburn  9698: sub personal_data_fieldtitles {
                   9699:     my %fieldtitles = &Apache::lonlocal::texthash (
                   9700:                         id => 'Student/Employee ID',
                   9701:                         permanentemail => 'E-mail address',
                   9702:                         lastname => 'Last Name',
                   9703:                         firstname => 'First Name',
                   9704:                         middlename => 'Middle Name',
                   9705:                         generation => 'Generation',
                   9706:                         gen => 'Generation',
1.765     raeburn  9707:                         inststatus => 'Affiliation',
1.624     raeburn  9708:                    );
                   9709:     return %fieldtitles;
                   9710: }
                   9711: 
1.642     raeburn  9712: sub sorted_inst_types {
                   9713:     my ($dom) = @_;
1.1075.2.70  raeburn  9714:     my ($usertypes,$order);
                   9715:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   9716:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   9717:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   9718:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   9719:     } else {
                   9720:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   9721:     }
1.642     raeburn  9722:     my $othertitle = &mt('All users');
                   9723:     if ($env{'request.course.id'}) {
1.668     raeburn  9724:         $othertitle  = &mt('Any users');
1.642     raeburn  9725:     }
                   9726:     my @types;
                   9727:     if (ref($order) eq 'ARRAY') {
                   9728:         @types = @{$order};
                   9729:     }
                   9730:     if (@types == 0) {
                   9731:         if (ref($usertypes) eq 'HASH') {
                   9732:             @types = sort(keys(%{$usertypes}));
                   9733:         }
                   9734:     }
                   9735:     if (keys(%{$usertypes}) > 0) {
                   9736:         $othertitle = &mt('Other users');
                   9737:     }
                   9738:     return ($othertitle,$usertypes,\@types);
                   9739: }
                   9740: 
1.645     raeburn  9741: sub get_institutional_codes {
                   9742:     my ($settings,$allcourses,$LC_code) = @_;
                   9743: # Get complete list of course sections to update
                   9744:     my @currsections = ();
                   9745:     my @currxlists = ();
                   9746:     my $coursecode = $$settings{'internal.coursecode'};
                   9747: 
                   9748:     if ($$settings{'internal.sectionnums'} ne '') {
                   9749:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   9750:     }
                   9751: 
                   9752:     if ($$settings{'internal.crosslistings'} ne '') {
                   9753:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   9754:     }
                   9755: 
                   9756:     if (@currxlists > 0) {
                   9757:         foreach (@currxlists) {
                   9758:             if (m/^([^:]+):(\w*)$/) {
                   9759:                 unless (grep/^$1$/,@{$allcourses}) {
                   9760:                     push @{$allcourses},$1;
                   9761:                     $$LC_code{$1} = $2;
                   9762:                 }
                   9763:             }
                   9764:         }
                   9765:     }
                   9766:  
                   9767:     if (@currsections > 0) {
                   9768:         foreach (@currsections) {
                   9769:             if (m/^(\w+):(\w*)$/) {
                   9770:                 my $sec = $coursecode.$1;
                   9771:                 my $lc_sec = $2;
                   9772:                 unless (grep/^$sec$/,@{$allcourses}) {
                   9773:                     push @{$allcourses},$sec;
                   9774:                     $$LC_code{$sec} = $lc_sec;
                   9775:                 }
                   9776:             }
                   9777:         }
                   9778:     }
                   9779:     return;
                   9780: }
                   9781: 
1.971     raeburn  9782: sub get_standard_codeitems {
                   9783:     return ('Year','Semester','Department','Number','Section');
                   9784: }
                   9785: 
1.112     bowersj2 9786: =pod
                   9787: 
1.780     raeburn  9788: =head1 Slot Helpers
                   9789: 
                   9790: =over 4
                   9791: 
                   9792: =item * sorted_slots()
                   9793: 
1.1040    raeburn  9794: Sorts an array of slot names in order of an optional sort key,
                   9795: default sort is by slot start time (earliest first). 
1.780     raeburn  9796: 
                   9797: Inputs:
                   9798: 
                   9799: =over 4
                   9800: 
                   9801: slotsarr  - Reference to array of unsorted slot names.
                   9802: 
                   9803: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   9804: 
1.1040    raeburn  9805: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   9806: 
1.549     albertel 9807: =back
                   9808: 
1.780     raeburn  9809: Returns:
                   9810: 
                   9811: =over 4
                   9812: 
1.1040    raeburn  9813: sorted   - An array of slot names sorted by a specified sort key 
                   9814:            (default sort key is start time of the slot).
1.780     raeburn  9815: 
                   9816: =back
                   9817: 
                   9818: =cut
                   9819: 
                   9820: 
                   9821: sub sorted_slots {
1.1040    raeburn  9822:     my ($slotsarr,$slots,$sortkey) = @_;
                   9823:     if ($sortkey eq '') {
                   9824:         $sortkey = 'starttime';
                   9825:     }
1.780     raeburn  9826:     my @sorted;
                   9827:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   9828:         @sorted =
                   9829:             sort {
                   9830:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  9831:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  9832:                      }
                   9833:                      if (ref($slots->{$a})) { return -1;}
                   9834:                      if (ref($slots->{$b})) { return 1;}
                   9835:                      return 0;
                   9836:                  } @{$slotsarr};
                   9837:     }
                   9838:     return @sorted;
                   9839: }
                   9840: 
1.1040    raeburn  9841: =pod
                   9842: 
                   9843: =item * get_future_slots()
                   9844: 
                   9845: Inputs:
                   9846: 
                   9847: =over 4
                   9848: 
                   9849: cnum - course number
                   9850: 
                   9851: cdom - course domain
                   9852: 
                   9853: now - current UNIX time
                   9854: 
                   9855: symb - optional symb
                   9856: 
                   9857: =back
                   9858: 
                   9859: Returns:
                   9860: 
                   9861: =over 4
                   9862: 
                   9863: sorted_reservable - ref to array of student_schedulable slots currently 
                   9864:                     reservable, ordered by end date of reservation period.
                   9865: 
                   9866: reservable_now - ref to hash of student_schedulable slots currently
                   9867:                  reservable.
                   9868: 
                   9869:     Keys in inner hash are:
                   9870:     (a) symb: either blank or symb to which slot use is restricted.
                   9871:     (b) endreserve: end date of reservation period. 
                   9872: 
                   9873: sorted_future - ref to array of student_schedulable slots reservable in
                   9874:                 the future, ordered by start date of reservation period.
                   9875: 
                   9876: future_reservable - ref to hash of student_schedulable slots reservable
                   9877:                     in the future.
                   9878: 
                   9879:     Keys in inner hash are:
                   9880:     (a) symb: either blank or symb to which slot use is restricted.
                   9881:     (b) startreserve:  start date of reservation period.
                   9882: 
                   9883: =back
                   9884: 
                   9885: =cut
                   9886: 
                   9887: sub get_future_slots {
                   9888:     my ($cnum,$cdom,$now,$symb) = @_;
                   9889:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   9890:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   9891:     foreach my $slot (keys(%slots)) {
                   9892:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   9893:         if ($symb) {
                   9894:             next if (($slots{$slot}->{'symb'} ne '') && 
                   9895:                      ($slots{$slot}->{'symb'} ne $symb));
                   9896:         }
                   9897:         if (($slots{$slot}->{'starttime'} > $now) &&
                   9898:             ($slots{$slot}->{'endtime'} > $now)) {
                   9899:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   9900:                 my $userallowed = 0;
                   9901:                 if ($slots{$slot}->{'allowedsections'}) {
                   9902:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   9903:                     if (!defined($env{'request.role.sec'})
                   9904:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   9905:                         $userallowed=1;
                   9906:                     } else {
                   9907:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   9908:                             $userallowed=1;
                   9909:                         }
                   9910:                     }
                   9911:                     unless ($userallowed) {
                   9912:                         if (defined($env{'request.course.groups'})) {
                   9913:                             my @groups = split(/:/,$env{'request.course.groups'});
                   9914:                             foreach my $group (@groups) {
                   9915:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   9916:                                     $userallowed=1;
                   9917:                                     last;
                   9918:                                 }
                   9919:                             }
                   9920:                         }
                   9921:                     }
                   9922:                 }
                   9923:                 if ($slots{$slot}->{'allowedusers'}) {
                   9924:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   9925:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   9926:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   9927:                         $userallowed = 1;
                   9928:                     }
                   9929:                 }
                   9930:                 next unless($userallowed);
                   9931:             }
                   9932:             my $startreserve = $slots{$slot}->{'startreserve'};
                   9933:             my $endreserve = $slots{$slot}->{'endreserve'};
                   9934:             my $symb = $slots{$slot}->{'symb'};
                   9935:             if (($startreserve < $now) &&
                   9936:                 (!$endreserve || $endreserve > $now)) {
                   9937:                 my $lastres = $endreserve;
                   9938:                 if (!$lastres) {
                   9939:                     $lastres = $slots{$slot}->{'starttime'};
                   9940:                 }
                   9941:                 $reservable_now{$slot} = {
                   9942:                                            symb       => $symb,
                   9943:                                            endreserve => $lastres
                   9944:                                          };
                   9945:             } elsif (($startreserve > $now) &&
                   9946:                      (!$endreserve || $endreserve > $startreserve)) {
                   9947:                 $future_reservable{$slot} = {
                   9948:                                               symb         => $symb,
                   9949:                                               startreserve => $startreserve
                   9950:                                             };
                   9951:             }
                   9952:         }
                   9953:     }
                   9954:     my @unsorted_reservable = keys(%reservable_now);
                   9955:     if (@unsorted_reservable > 0) {
                   9956:         @sorted_reservable = 
                   9957:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   9958:     }
                   9959:     my @unsorted_future = keys(%future_reservable);
                   9960:     if (@unsorted_future > 0) {
                   9961:         @sorted_future =
                   9962:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   9963:     }
                   9964:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   9965: }
1.780     raeburn  9966: 
                   9967: =pod
                   9968: 
1.1057    foxr     9969: =back
                   9970: 
1.549     albertel 9971: =head1 HTTP Helpers
                   9972: 
                   9973: =over 4
                   9974: 
1.648     raeburn  9975: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 9976: 
1.258     albertel 9977: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 9978: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 9979: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 9980: 
                   9981: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   9982: $possible_names is an ref to an array of form element names.  As an example:
                   9983: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 9984: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 9985: 
                   9986: =cut
1.1       albertel 9987: 
1.6       albertel 9988: sub get_unprocessed_cgi {
1.25      albertel 9989:   my ($query,$possible_names)= @_;
1.26      matthew  9990:   # $Apache::lonxml::debug=1;
1.356     albertel 9991:   foreach my $pair (split(/&/,$query)) {
                   9992:     my ($name, $value) = split(/=/,$pair);
1.369     www      9993:     $name = &unescape($name);
1.25      albertel 9994:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   9995:       $value =~ tr/+/ /;
                   9996:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 9997:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 9998:     }
1.16      harris41 9999:   }
1.6       albertel 10000: }
                   10001: 
1.112     bowersj2 10002: =pod
                   10003: 
1.648     raeburn  10004: =item * &cacheheader() 
1.112     bowersj2 10005: 
                   10006: returns cache-controlling header code
                   10007: 
                   10008: =cut
                   10009: 
1.7       albertel 10010: sub cacheheader {
1.258     albertel 10011:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10012:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10013:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10014:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10015:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10016:     return $output;
1.7       albertel 10017: }
                   10018: 
1.112     bowersj2 10019: =pod
                   10020: 
1.648     raeburn  10021: =item * &no_cache($r) 
1.112     bowersj2 10022: 
                   10023: specifies header code to not have cache
                   10024: 
                   10025: =cut
                   10026: 
1.9       albertel 10027: sub no_cache {
1.216     albertel 10028:     my ($r) = @_;
                   10029:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10030: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10031:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10032:     $r->no_cache(1);
                   10033:     $r->header_out("Expires" => $date);
                   10034:     $r->header_out("Pragma" => "no-cache");
1.123     www      10035: }
                   10036: 
                   10037: sub content_type {
1.181     albertel 10038:     my ($r,$type,$charset) = @_;
1.299     foxr     10039:     if ($r) {
                   10040: 	#  Note that printout.pl calls this with undef for $r.
                   10041: 	&no_cache($r);
                   10042:     }
1.258     albertel 10043:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10044:     unless ($charset) {
                   10045: 	$charset=&Apache::lonlocal::current_encoding;
                   10046:     }
                   10047:     if ($charset) { $type.='; charset='.$charset; }
                   10048:     if ($r) {
                   10049: 	$r->content_type($type);
                   10050:     } else {
                   10051: 	print("Content-type: $type\n\n");
                   10052:     }
1.9       albertel 10053: }
1.25      albertel 10054: 
1.112     bowersj2 10055: =pod
                   10056: 
1.648     raeburn  10057: =item * &add_to_env($name,$value) 
1.112     bowersj2 10058: 
1.258     albertel 10059: adds $name to the %env hash with value
1.112     bowersj2 10060: $value, if $name already exists, the entry is converted to an array
                   10061: reference and $value is added to the array.
                   10062: 
                   10063: =cut
                   10064: 
1.25      albertel 10065: sub add_to_env {
                   10066:   my ($name,$value)=@_;
1.258     albertel 10067:   if (defined($env{$name})) {
                   10068:     if (ref($env{$name})) {
1.25      albertel 10069:       #already have multiple values
1.258     albertel 10070:       push(@{ $env{$name} },$value);
1.25      albertel 10071:     } else {
                   10072:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10073:       my $first=$env{$name};
                   10074:       undef($env{$name});
                   10075:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10076:     }
                   10077:   } else {
1.258     albertel 10078:     $env{$name}=$value;
1.25      albertel 10079:   }
1.31      albertel 10080: }
1.149     albertel 10081: 
                   10082: =pod
                   10083: 
1.648     raeburn  10084: =item * &get_env_multiple($name) 
1.149     albertel 10085: 
1.258     albertel 10086: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10087: values may be defined and end up as an array ref.
                   10088: 
                   10089: returns an array of values
                   10090: 
                   10091: =cut
                   10092: 
                   10093: sub get_env_multiple {
                   10094:     my ($name) = @_;
                   10095:     my @values;
1.258     albertel 10096:     if (defined($env{$name})) {
1.149     albertel 10097:         # exists is it an array
1.258     albertel 10098:         if (ref($env{$name})) {
                   10099:             @values=@{ $env{$name} };
1.149     albertel 10100:         } else {
1.258     albertel 10101:             $values[0]=$env{$name};
1.149     albertel 10102:         }
                   10103:     }
                   10104:     return(@values);
                   10105: }
                   10106: 
1.660     raeburn  10107: sub ask_for_embedded_content {
                   10108:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10109:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10110:         %currsubfile,%unused,$rem);
1.1071    raeburn  10111:     my $counter = 0;
                   10112:     my $numnew = 0;
1.987     raeburn  10113:     my $numremref = 0;
                   10114:     my $numinvalid = 0;
                   10115:     my $numpathchg = 0;
                   10116:     my $numexisting = 0;
1.1071    raeburn  10117:     my $numunused = 0;
                   10118:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10119:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10120:     my $heading = &mt('Upload embedded files');
                   10121:     my $buttontext = &mt('Upload');
                   10122: 
1.1075.2.11  raeburn  10123:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10124:         if ($actionurl eq '/adm/dependencies') {
                   10125:             $navmap = Apache::lonnavmaps::navmap->new();
                   10126:         }
                   10127:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10128:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10129:     }
1.1075.2.35  raeburn  10130:     if (($actionurl eq '/adm/portfolio') ||
                   10131:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10132:         my $current_path='/';
                   10133:         if ($env{'form.currentpath'}) {
                   10134:             $current_path = $env{'form.currentpath'};
                   10135:         }
                   10136:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10137:             $udom = $cdom;
                   10138:             $uname = $cnum;
1.984     raeburn  10139:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10140:         } else {
                   10141:             $udom = $env{'user.domain'};
                   10142:             $uname = $env{'user.name'};
                   10143:             $url = '/userfiles/portfolio';
                   10144:         }
1.987     raeburn  10145:         $toplevel = $url.'/';
1.984     raeburn  10146:         $url .= $current_path;
                   10147:         $getpropath = 1;
1.987     raeburn  10148:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10149:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10150:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10151:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10152:         $toplevel = $url;
1.984     raeburn  10153:         if ($rest ne '') {
1.987     raeburn  10154:             $url .= $rest;
                   10155:         }
                   10156:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10157:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10158:             $url = $args->{'docs_url'};
                   10159:             $toplevel = $url;
1.1075.2.11  raeburn  10160:             if ($args->{'context'} eq 'paste') {
                   10161:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10162:                 ($path) =
                   10163:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10164:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10165:                 $fileloc =~ s{^/}{};
                   10166:             }
1.1071    raeburn  10167:         }
                   10168:     } elsif ($actionurl eq '/adm/dependencies') {
                   10169:         if ($env{'request.course.id'} ne '') {
                   10170:             if (ref($args) eq 'HASH') {
                   10171:                 $url = $args->{'docs_url'};
                   10172:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10173:                 $toplevel = $url;
                   10174:                 unless ($toplevel =~ m{^/}) {
                   10175:                     $toplevel = "/$url";
                   10176:                 }
1.1075.2.11  raeburn  10177:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10178:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10179:                     $path = $1;
                   10180:                 } else {
                   10181:                     ($path) =
                   10182:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10183:                 }
1.1075.2.79  raeburn  10184:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10185:                     $fileloc = $toplevel;
                   10186:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10187:                     my ($udom,$uname,$fname) =
                   10188:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10189:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10190:                 } else {
                   10191:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10192:                 }
1.1071    raeburn  10193:                 $fileloc =~ s{^/}{};
                   10194:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10195:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10196:             }
1.987     raeburn  10197:         }
1.1075.2.35  raeburn  10198:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10199:         $udom = $cdom;
                   10200:         $uname = $cnum;
                   10201:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10202:         $toplevel = $url;
                   10203:         $path = $url;
                   10204:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10205:         $fileloc =~ s{^/}{};
                   10206:     }
                   10207:     foreach my $file (keys(%{$allfiles})) {
                   10208:         my $embed_file;
                   10209:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10210:             $embed_file = $1;
                   10211:         } else {
                   10212:             $embed_file = $file;
                   10213:         }
1.1075.2.55  raeburn  10214:         my ($absolutepath,$cleaned_file);
                   10215:         if ($embed_file =~ m{^\w+://}) {
                   10216:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10217:             $newfiles{$cleaned_file} = 1;
                   10218:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10219:         } else {
1.1075.2.55  raeburn  10220:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10221:             if ($embed_file =~ m{^/}) {
                   10222:                 $absolutepath = $embed_file;
                   10223:             }
1.1075.2.47  raeburn  10224:             if ($cleaned_file =~ m{/}) {
                   10225:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10226:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10227:                 my $item = $fname;
                   10228:                 if ($path ne '') {
                   10229:                     $item = $path.'/'.$fname;
                   10230:                     $subdependencies{$path}{$fname} = 1;
                   10231:                 } else {
                   10232:                     $dependencies{$item} = 1;
                   10233:                 }
                   10234:                 if ($absolutepath) {
                   10235:                     $mapping{$item} = $absolutepath;
                   10236:                 } else {
                   10237:                     $mapping{$item} = $embed_file;
                   10238:                 }
                   10239:             } else {
                   10240:                 $dependencies{$embed_file} = 1;
                   10241:                 if ($absolutepath) {
1.1075.2.47  raeburn  10242:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10243:                 } else {
1.1075.2.47  raeburn  10244:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10245:                 }
                   10246:             }
1.984     raeburn  10247:         }
                   10248:     }
1.1071    raeburn  10249:     my $dirptr = 16384;
1.984     raeburn  10250:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10251:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10252:         if (($actionurl eq '/adm/portfolio') ||
                   10253:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10254:             my ($sublistref,$listerror) =
                   10255:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10256:             if (ref($sublistref) eq 'ARRAY') {
                   10257:                 foreach my $line (@{$sublistref}) {
                   10258:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10259:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10260:                 }
1.984     raeburn  10261:             }
1.987     raeburn  10262:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10263:             if (opendir(my $dir,$url.'/'.$path)) {
                   10264:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10265:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10266:             }
1.1075.2.11  raeburn  10267:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10268:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10269:                   ($args->{'context'} eq 'paste')) ||
                   10270:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10271:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10272:                 my $dir;
                   10273:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10274:                     $dir = $fileloc;
                   10275:                 } else {
                   10276:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10277:                 }
1.1071    raeburn  10278:                 if ($dir ne '') {
                   10279:                     my ($sublistref,$listerror) =
                   10280:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10281:                     if (ref($sublistref) eq 'ARRAY') {
                   10282:                         foreach my $line (@{$sublistref}) {
                   10283:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10284:                                 undef,$mtime)=split(/\&/,$line,12);
                   10285:                             unless (($testdir&$dirptr) ||
                   10286:                                     ($file_name =~ /^\.\.?$/)) {
                   10287:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10288:                             }
                   10289:                         }
                   10290:                     }
                   10291:                 }
1.984     raeburn  10292:             }
                   10293:         }
                   10294:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10295:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10296:                 my $item = $path.'/'.$file;
                   10297:                 unless ($mapping{$item} eq $item) {
                   10298:                     $pathchanges{$item} = 1;
                   10299:                 }
                   10300:                 $existing{$item} = 1;
                   10301:                 $numexisting ++;
                   10302:             } else {
                   10303:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10304:             }
                   10305:         }
1.1071    raeburn  10306:         if ($actionurl eq '/adm/dependencies') {
                   10307:             foreach my $path (keys(%currsubfile)) {
                   10308:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10309:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10310:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10311:                              next if (($rem ne '') &&
                   10312:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10313:                                        (ref($navmap) &&
                   10314:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10315:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10316:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10317:                              $unused{$path.'/'.$file} = 1; 
                   10318:                          }
                   10319:                     }
                   10320:                 }
                   10321:             }
                   10322:         }
1.984     raeburn  10323:     }
1.987     raeburn  10324:     my %currfile;
1.1075.2.35  raeburn  10325:     if (($actionurl eq '/adm/portfolio') ||
                   10326:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10327:         my ($dirlistref,$listerror) =
                   10328:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10329:         if (ref($dirlistref) eq 'ARRAY') {
                   10330:             foreach my $line (@{$dirlistref}) {
                   10331:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10332:                 $currfile{$file_name} = 1;
                   10333:             }
1.984     raeburn  10334:         }
1.987     raeburn  10335:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10336:         if (opendir(my $dir,$url)) {
1.987     raeburn  10337:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10338:             map {$currfile{$_} = 1;} @dir_list;
                   10339:         }
1.1075.2.11  raeburn  10340:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10341:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10342:               ($args->{'context'} eq 'paste')) ||
                   10343:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10344:         if ($env{'request.course.id'} ne '') {
                   10345:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10346:             if ($dir ne '') {
                   10347:                 my ($dirlistref,$listerror) =
                   10348:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10349:                 if (ref($dirlistref) eq 'ARRAY') {
                   10350:                     foreach my $line (@{$dirlistref}) {
                   10351:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10352:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10353:                         unless (($testdir&$dirptr) ||
                   10354:                                 ($file_name =~ /^\.\.?$/)) {
                   10355:                             $currfile{$file_name} = [$size,$mtime];
                   10356:                         }
                   10357:                     }
                   10358:                 }
                   10359:             }
                   10360:         }
1.984     raeburn  10361:     }
                   10362:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10363:         if (exists($currfile{$file})) {
1.987     raeburn  10364:             unless ($mapping{$file} eq $file) {
                   10365:                 $pathchanges{$file} = 1;
                   10366:             }
                   10367:             $existing{$file} = 1;
                   10368:             $numexisting ++;
                   10369:         } else {
1.984     raeburn  10370:             $newfiles{$file} = 1;
                   10371:         }
                   10372:     }
1.1071    raeburn  10373:     foreach my $file (keys(%currfile)) {
                   10374:         unless (($file eq $filename) ||
                   10375:                 ($file eq $filename.'.bak') ||
                   10376:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10377:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10378:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10379:                     next if (($rem ne '') &&
                   10380:                              (($env{"httpref.$rem".$file} ne '') ||
                   10381:                               (ref($navmap) &&
                   10382:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10383:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10384:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10385:                 }
1.1075.2.11  raeburn  10386:             }
1.1071    raeburn  10387:             $unused{$file} = 1;
                   10388:         }
                   10389:     }
1.1075.2.11  raeburn  10390:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10391:         ($args->{'context'} eq 'paste')) {
                   10392:         $counter = scalar(keys(%existing));
                   10393:         $numpathchg = scalar(keys(%pathchanges));
                   10394:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10395:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10396:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10397:         $counter = scalar(keys(%existing));
                   10398:         $numpathchg = scalar(keys(%pathchanges));
                   10399:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10400:     }
1.984     raeburn  10401:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10402:         if ($actionurl eq '/adm/dependencies') {
                   10403:             next if ($embed_file =~ m{^\w+://});
                   10404:         }
1.660     raeburn  10405:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10406:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10407:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10408:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10409:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10410:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10411:         }
1.1075.2.35  raeburn  10412:         $upload_output .= '</td>';
1.1071    raeburn  10413:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10414:             $upload_output.='<td align="right">'.
                   10415:                             '<span class="LC_info LC_fontsize_medium">'.
                   10416:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10417:             $numremref++;
1.660     raeburn  10418:         } elsif ($args->{'error_on_invalid_names'}
                   10419:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10420:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10421:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10422:             $numinvalid++;
1.660     raeburn  10423:         } else {
1.1075.2.35  raeburn  10424:             $upload_output .= '<td>'.
                   10425:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10426:                                                      $embed_file,\%mapping,
1.1071    raeburn  10427:                                                      $allfiles,$codebase,'upload');
                   10428:             $counter ++;
                   10429:             $numnew ++;
1.987     raeburn  10430:         }
                   10431:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10432:     }
                   10433:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10434:         if ($actionurl eq '/adm/dependencies') {
                   10435:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10436:             $modify_output .= &start_data_table_row().
                   10437:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10438:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10439:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10440:                               '<td>'.$size.'</td>'.
                   10441:                               '<td>'.$mtime.'</td>'.
                   10442:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10443:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10444:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10445:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10446:                               &embedded_file_element('upload_embedded',$counter,
                   10447:                                                      $embed_file,\%mapping,
                   10448:                                                      $allfiles,$codebase,'modify').
                   10449:                               '</div></td>'.
                   10450:                               &end_data_table_row()."\n";
                   10451:             $counter ++;
                   10452:         } else {
                   10453:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10454:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10455:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10456:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10457:                               &Apache::loncommon::end_data_table_row()."\n";
                   10458:         }
                   10459:     }
                   10460:     my $delidx = $counter;
                   10461:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10462:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10463:         $delete_output .= &start_data_table_row().
                   10464:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10465:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10466:                           '<td>'.$size.'</td>'.
                   10467:                           '<td>'.$mtime.'</td>'.
                   10468:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10469:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10470:                           &embedded_file_element('upload_embedded',$delidx,
                   10471:                                                  $oldfile,\%mapping,$allfiles,
                   10472:                                                  $codebase,'delete').'</td>'.
                   10473:                           &end_data_table_row()."\n"; 
                   10474:         $numunused ++;
                   10475:         $delidx ++;
1.987     raeburn  10476:     }
                   10477:     if ($upload_output) {
                   10478:         $upload_output = &start_data_table().
                   10479:                          $upload_output.
                   10480:                          &end_data_table()."\n";
                   10481:     }
1.1071    raeburn  10482:     if ($modify_output) {
                   10483:         $modify_output = &start_data_table().
                   10484:                          &start_data_table_header_row().
                   10485:                          '<th>'.&mt('File').'</th>'.
                   10486:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10487:                          '<th>'.&mt('Modified').'</th>'.
                   10488:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10489:                          &end_data_table_header_row().
                   10490:                          $modify_output.
                   10491:                          &end_data_table()."\n";
                   10492:     }
                   10493:     if ($delete_output) {
                   10494:         $delete_output = &start_data_table().
                   10495:                          &start_data_table_header_row().
                   10496:                          '<th>'.&mt('File').'</th>'.
                   10497:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10498:                          '<th>'.&mt('Modified').'</th>'.
                   10499:                          '<th>'.&mt('Delete?').'</th>'.
                   10500:                          &end_data_table_header_row().
                   10501:                          $delete_output.
                   10502:                          &end_data_table()."\n";
                   10503:     }
1.987     raeburn  10504:     my $applies = 0;
                   10505:     if ($numremref) {
                   10506:         $applies ++;
                   10507:     }
                   10508:     if ($numinvalid) {
                   10509:         $applies ++;
                   10510:     }
                   10511:     if ($numexisting) {
                   10512:         $applies ++;
                   10513:     }
1.1071    raeburn  10514:     if ($counter || $numunused) {
1.987     raeburn  10515:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10516:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10517:                   $state.'<h3>'.$heading.'</h3>'; 
                   10518:         if ($actionurl eq '/adm/dependencies') {
                   10519:             if ($numnew) {
                   10520:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10521:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10522:                            $upload_output.'<br />'."\n";
                   10523:             }
                   10524:             if ($numexisting) {
                   10525:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10526:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10527:                            $modify_output.'<br />'."\n";
                   10528:                            $buttontext = &mt('Save changes');
                   10529:             }
                   10530:             if ($numunused) {
                   10531:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10532:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10533:                            $delete_output.'<br />'."\n";
                   10534:                            $buttontext = &mt('Save changes');
                   10535:             }
                   10536:         } else {
                   10537:             $output .= $upload_output.'<br />'."\n";
                   10538:         }
                   10539:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   10540:                    $counter.'" />'."\n";
                   10541:         if ($actionurl eq '/adm/dependencies') { 
                   10542:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   10543:                        $numnew.'" />'."\n";
                   10544:         } elsif ($actionurl eq '') {
1.987     raeburn  10545:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   10546:         }
                   10547:     } elsif ($applies) {
                   10548:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   10549:         if ($applies > 1) {
                   10550:             $output .=  
1.1075.2.35  raeburn  10551:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  10552:             if ($numremref) {
                   10553:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   10554:             }
                   10555:             if ($numinvalid) {
                   10556:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   10557:             }
                   10558:             if ($numexisting) {
                   10559:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   10560:             }
                   10561:             $output .= '</ul><br />';
                   10562:         } elsif ($numremref) {
                   10563:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   10564:         } elsif ($numinvalid) {
                   10565:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   10566:         } elsif ($numexisting) {
                   10567:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   10568:         }
                   10569:         $output .= $upload_output.'<br />';
                   10570:     }
                   10571:     my ($pathchange_output,$chgcount);
1.1071    raeburn  10572:     $chgcount = $counter;
1.987     raeburn  10573:     if (keys(%pathchanges) > 0) {
                   10574:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  10575:             if ($counter) {
1.987     raeburn  10576:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   10577:                                                   $embed_file,\%mapping,
1.1071    raeburn  10578:                                                   $allfiles,$codebase,'change');
1.987     raeburn  10579:             } else {
                   10580:                 $pathchange_output .= 
                   10581:                     &start_data_table_row().
                   10582:                     '<td><input type ="checkbox" name="namechange" value="'.
                   10583:                     $chgcount.'" checked="checked" /></td>'.
                   10584:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   10585:                     '<td>'.$embed_file.
                   10586:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  10587:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  10588:                     '</td>'.&end_data_table_row();
1.660     raeburn  10589:             }
1.987     raeburn  10590:             $numpathchg ++;
                   10591:             $chgcount ++;
1.660     raeburn  10592:         }
                   10593:     }
1.1075.2.35  raeburn  10594:     if (($counter) || ($numunused)) {
1.987     raeburn  10595:         if ($numpathchg) {
                   10596:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   10597:                        $numpathchg.'" />'."\n";
                   10598:         }
                   10599:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   10600:             ($actionurl eq '/adm/imsimport')) {
                   10601:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   10602:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   10603:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  10604:         } elsif ($actionurl eq '/adm/dependencies') {
                   10605:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  10606:         }
1.1075.2.35  raeburn  10607:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  10608:     } elsif ($numpathchg) {
                   10609:         my %pathchange = ();
                   10610:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   10611:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10612:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  10613:         }
1.987     raeburn  10614:     }
1.1071    raeburn  10615:     return ($output,$counter,$numpathchg);
1.987     raeburn  10616: }
                   10617: 
1.1075.2.47  raeburn  10618: =pod
                   10619: 
                   10620: =item * clean_path($name)
                   10621: 
                   10622: Performs clean-up of directories, subdirectories and filename in an
                   10623: embedded object, referenced in an HTML file which is being uploaded
                   10624: to a course or portfolio, where
                   10625: "Upload embedded images/multimedia files if HTML file" checkbox was
                   10626: checked.
                   10627: 
                   10628: Clean-up is similar to replacements in lonnet::clean_filename()
                   10629: except each / between sub-directory and next level is preserved.
                   10630: 
                   10631: =cut
                   10632: 
                   10633: sub clean_path {
                   10634:     my ($embed_file) = @_;
                   10635:     $embed_file =~s{^/+}{};
                   10636:     my @contents;
                   10637:     if ($embed_file =~ m{/}) {
                   10638:         @contents = split(/\//,$embed_file);
                   10639:     } else {
                   10640:         @contents = ($embed_file);
                   10641:     }
                   10642:     my $lastidx = scalar(@contents)-1;
                   10643:     for (my $i=0; $i<=$lastidx; $i++) {
                   10644:         $contents[$i]=~s{\\}{/}g;
                   10645:         $contents[$i]=~s/\s+/\_/g;
                   10646:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   10647:         if ($i == $lastidx) {
                   10648:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   10649:         }
                   10650:     }
                   10651:     if ($lastidx > 0) {
                   10652:         return join('/',@contents);
                   10653:     } else {
                   10654:         return $contents[0];
                   10655:     }
                   10656: }
                   10657: 
1.987     raeburn  10658: sub embedded_file_element {
1.1071    raeburn  10659:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  10660:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   10661:                    (ref($codebase) eq 'HASH'));
                   10662:     my $output;
1.1071    raeburn  10663:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  10664:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   10665:     }
                   10666:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   10667:                &escape($embed_file).'" />';
                   10668:     unless (($context eq 'upload_embedded') && 
                   10669:             ($mapping->{$embed_file} eq $embed_file)) {
                   10670:         $output .='
                   10671:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   10672:     }
                   10673:     my $attrib;
                   10674:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   10675:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   10676:     }
                   10677:     $output .=
                   10678:         "\n\t\t".
                   10679:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   10680:         $attrib.'" />';
                   10681:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   10682:         $output .=
                   10683:             "\n\t\t".
                   10684:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   10685:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  10686:     }
1.987     raeburn  10687:     return $output;
1.660     raeburn  10688: }
                   10689: 
1.1071    raeburn  10690: sub get_dependency_details {
                   10691:     my ($currfile,$currsubfile,$embed_file) = @_;
                   10692:     my ($size,$mtime,$showsize,$showmtime);
                   10693:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   10694:         if ($embed_file =~ m{/}) {
                   10695:             my ($path,$fname) = split(/\//,$embed_file);
                   10696:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   10697:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   10698:             }
                   10699:         } else {
                   10700:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   10701:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   10702:             }
                   10703:         }
                   10704:         $showsize = $size/1024.0;
                   10705:         $showsize = sprintf("%.1f",$showsize);
                   10706:         if ($mtime > 0) {
                   10707:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   10708:         }
                   10709:     }
                   10710:     return ($showsize,$showmtime);
                   10711: }
                   10712: 
                   10713: sub ask_embedded_js {
                   10714:     return <<"END";
                   10715: <script type="text/javascript"">
                   10716: // <![CDATA[
                   10717: function toggleBrowse(counter) {
                   10718:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   10719:     var fileid = document.getElementById('embedded_item_'+counter);
                   10720:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   10721:     if (chkboxid.checked == true) {
                   10722:         uploaddivid.style.display='block';
                   10723:     } else {
                   10724:         uploaddivid.style.display='none';
                   10725:         fileid.value = '';
                   10726:     }
                   10727: }
                   10728: // ]]>
                   10729: </script>
                   10730: 
                   10731: END
                   10732: }
                   10733: 
1.661     raeburn  10734: sub upload_embedded {
                   10735:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  10736:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   10737:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  10738:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   10739:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   10740:         my $orig_uploaded_filename =
                   10741:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  10742:         foreach my $type ('orig','ref','attrib','codebase') {
                   10743:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   10744:                 $env{'form.embedded_'.$type.'_'.$i} =
                   10745:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   10746:             }
                   10747:         }
1.661     raeburn  10748:         my ($path,$fname) =
                   10749:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   10750:         # no path, whole string is fname
                   10751:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   10752:         $fname = &Apache::lonnet::clean_filename($fname);
                   10753:         # See if there is anything left
                   10754:         next if ($fname eq '');
                   10755: 
                   10756:         # Check if file already exists as a file or directory.
                   10757:         my ($state,$msg);
                   10758:         if ($context eq 'portfolio') {
                   10759:             my $port_path = $dirpath;
                   10760:             if ($group ne '') {
                   10761:                 $port_path = "groups/$group/$port_path";
                   10762:             }
1.987     raeburn  10763:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   10764:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  10765:                                               $dir_root,$port_path,$disk_quota,
                   10766:                                               $current_disk_usage,$uname,$udom);
                   10767:             if ($state eq 'will_exceed_quota'
1.984     raeburn  10768:                 || $state eq 'file_locked') {
1.661     raeburn  10769:                 $output .= $msg;
                   10770:                 next;
                   10771:             }
                   10772:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   10773:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   10774:             if ($state eq 'exists') {
                   10775:                 $output .= $msg;
                   10776:                 next;
                   10777:             }
                   10778:         }
                   10779:         # Check if extension is valid
                   10780:         if (($fname =~ /\.(\w+)$/) &&
                   10781:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  10782:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   10783:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  10784:             next;
                   10785:         } elsif (($fname =~ /\.(\w+)$/) &&
                   10786:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  10787:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  10788:             next;
                   10789:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  10790:             $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  10791:             next;
                   10792:         }
                   10793:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  10794:         my $subdir = $path;
                   10795:         $subdir =~ s{/+$}{};
1.661     raeburn  10796:         if ($context eq 'portfolio') {
1.984     raeburn  10797:             my $result;
                   10798:             if ($state eq 'existingfile') {
                   10799:                 $result=
                   10800:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  10801:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  10802:             } else {
1.984     raeburn  10803:                 $result=
                   10804:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  10805:                                                     $dirpath.
1.1075.2.35  raeburn  10806:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  10807:                 if ($result !~ m|^/uploaded/|) {
                   10808:                     $output .= '<span class="LC_error">'
                   10809:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10810:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10811:                                .'</span><br />';
                   10812:                     next;
                   10813:                 } else {
1.987     raeburn  10814:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10815:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  10816:                 }
1.661     raeburn  10817:             }
1.1075.2.35  raeburn  10818:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   10819:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   10820:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  10821:             my $result =
1.1075.2.35  raeburn  10822:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  10823:             if ($result !~ m|^/uploaded/|) {
                   10824:                 $output .= '<span class="LC_error">'
                   10825:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   10826:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   10827:                            .'</span><br />';
                   10828:                     next;
                   10829:             } else {
                   10830:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10831:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  10832:                 if ($context eq 'syllabus') {
                   10833:                     &Apache::lonnet::make_public_indefinitely($result);
                   10834:                 }
1.987     raeburn  10835:             }
1.661     raeburn  10836:         } else {
                   10837: # Save the file
                   10838:             my $target = $env{'form.embedded_item_'.$i};
                   10839:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   10840:             my $dest = $fullpath.$fname;
                   10841:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  10842:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  10843:             my $count;
                   10844:             my $filepath = $dir_root;
1.1027    raeburn  10845:             foreach my $subdir (@parts) {
                   10846:                 $filepath .= "/$subdir";
                   10847:                 if (!-e $filepath) {
1.661     raeburn  10848:                     mkdir($filepath,0770);
                   10849:                 }
                   10850:             }
                   10851:             my $fh;
                   10852:             if (!open($fh,'>'.$dest)) {
                   10853:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   10854:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  10855:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   10856:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10857:                            '</span><br />';
                   10858:             } else {
                   10859:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   10860:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   10861:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  10862:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   10863:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  10864:                               '</span><br />';
                   10865:                 } else {
1.987     raeburn  10866:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   10867:                                $url.'</span>').'<br />';
                   10868:                     unless ($context eq 'testbank') {
                   10869:                         $footer .= &mt('View embedded file: [_1]',
                   10870:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   10871:                     }
                   10872:                 }
                   10873:                 close($fh);
                   10874:             }
                   10875:         }
                   10876:         if ($env{'form.embedded_ref_'.$i}) {
                   10877:             $pathchange{$i} = 1;
                   10878:         }
                   10879:     }
                   10880:     if ($output) {
                   10881:         $output = '<p>'.$output.'</p>';
                   10882:     }
                   10883:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   10884:     $returnflag = 'ok';
1.1071    raeburn  10885:     my $numpathchgs = scalar(keys(%pathchange));
                   10886:     if ($numpathchgs > 0) {
1.987     raeburn  10887:         if ($context eq 'portfolio') {
                   10888:             $output .= '<p>'.&mt('or').'</p>';
                   10889:         } elsif ($context eq 'testbank') {
1.1071    raeburn  10890:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   10891:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  10892:             $returnflag = 'modify_orightml';
                   10893:         }
                   10894:     }
1.1071    raeburn  10895:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  10896: }
                   10897: 
                   10898: sub modify_html_form {
                   10899:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   10900:     my $end = 0;
                   10901:     my $modifyform;
                   10902:     if ($context eq 'upload_embedded') {
                   10903:         return unless (ref($pathchange) eq 'HASH');
                   10904:         if ($env{'form.number_embedded_items'}) {
                   10905:             $end += $env{'form.number_embedded_items'};
                   10906:         }
                   10907:         if ($env{'form.number_pathchange_items'}) {
                   10908:             $end += $env{'form.number_pathchange_items'};
                   10909:         }
                   10910:         if ($end) {
                   10911:             for (my $i=0; $i<$end; $i++) {
                   10912:                 if ($i < $env{'form.number_embedded_items'}) {
                   10913:                     next unless($pathchange->{$i});
                   10914:                 }
                   10915:                 $modifyform .=
                   10916:                     &start_data_table_row().
                   10917:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   10918:                     'checked="checked" /></td>'.
                   10919:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   10920:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   10921:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   10922:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   10923:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   10924:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   10925:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   10926:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   10927:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   10928:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   10929:                     &end_data_table_row();
1.1071    raeburn  10930:             }
1.987     raeburn  10931:         }
                   10932:     } else {
                   10933:         $modifyform = $pathchgtable;
                   10934:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   10935:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   10936:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   10937:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   10938:         }
                   10939:     }
                   10940:     if ($modifyform) {
1.1071    raeburn  10941:         if ($actionurl eq '/adm/dependencies') {
                   10942:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   10943:         }
1.987     raeburn  10944:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   10945:                '<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".
                   10946:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   10947:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   10948:                '</ol></p>'."\n".'<p>'.
                   10949:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   10950:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   10951:                &start_data_table()."\n".
                   10952:                &start_data_table_header_row().
                   10953:                '<th>'.&mt('Change?').'</th>'.
                   10954:                '<th>'.&mt('Current reference').'</th>'.
                   10955:                '<th>'.&mt('Required reference').'</th>'.
                   10956:                &end_data_table_header_row()."\n".
                   10957:                $modifyform.
                   10958:                &end_data_table().'<br />'."\n".$hiddenstate.
                   10959:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   10960:                '</form>'."\n";
                   10961:     }
                   10962:     return;
                   10963: }
                   10964: 
                   10965: sub modify_html_refs {
1.1075.2.35  raeburn  10966:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  10967:     my $container;
                   10968:     if ($context eq 'portfolio') {
                   10969:         $container = $env{'form.container'};
                   10970:     } elsif ($context eq 'coursedoc') {
                   10971:         $container = $env{'form.primaryurl'};
1.1071    raeburn  10972:     } elsif ($context eq 'manage_dependencies') {
                   10973:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   10974:         $container = "/$container";
1.1075.2.35  raeburn  10975:     } elsif ($context eq 'syllabus') {
                   10976:         $container = $url;
1.987     raeburn  10977:     } else {
1.1027    raeburn  10978:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  10979:     }
                   10980:     my (%allfiles,%codebase,$output,$content);
                   10981:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  10982:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  10983:         if (wantarray) {
                   10984:             return ('',0,0); 
                   10985:         } else {
                   10986:             return;
                   10987:         }
                   10988:     }
                   10989:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  10990:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  10991:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   10992:             if (wantarray) {
                   10993:                 return ('',0,0);
                   10994:             } else {
                   10995:                 return;
                   10996:             }
                   10997:         } 
1.987     raeburn  10998:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  10999:         if ($content eq '-1') {
                   11000:             if (wantarray) {
                   11001:                 return ('',0,0);
                   11002:             } else {
                   11003:                 return;
                   11004:             }
                   11005:         }
1.987     raeburn  11006:     } else {
1.1071    raeburn  11007:         unless ($container =~ /^\Q$dir_root\E/) {
                   11008:             if (wantarray) {
                   11009:                 return ('',0,0);
                   11010:             } else {
                   11011:                 return;
                   11012:             }
                   11013:         } 
1.987     raeburn  11014:         if (open(my $fh,"<$container")) {
                   11015:             $content = join('', <$fh>);
                   11016:             close($fh);
                   11017:         } else {
1.1071    raeburn  11018:             if (wantarray) {
                   11019:                 return ('',0,0);
                   11020:             } else {
                   11021:                 return;
                   11022:             }
1.987     raeburn  11023:         }
                   11024:     }
                   11025:     my ($count,$codebasecount) = (0,0);
                   11026:     my $mm = new File::MMagic;
                   11027:     my $mime_type = $mm->checktype_contents($content);
                   11028:     if ($mime_type eq 'text/html') {
                   11029:         my $parse_result = 
                   11030:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11031:                                                     \%codebase,\$content);
                   11032:         if ($parse_result eq 'ok') {
                   11033:             foreach my $i (@changes) {
                   11034:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11035:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11036:                 if ($allfiles{$ref}) {
                   11037:                     my $newname =  $orig;
                   11038:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11039:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11040:                     if ($attrib_regexp =~ /:/) {
                   11041:                         $attrib_regexp =~ s/\:/|/g;
                   11042:                     }
                   11043:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11044:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11045:                         $count += $numchg;
1.1075.2.35  raeburn  11046:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11047:                         delete($allfiles{$ref});
1.987     raeburn  11048:                     }
                   11049:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11050:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11051:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11052:                         $codebasecount ++;
                   11053:                     }
                   11054:                 }
                   11055:             }
1.1075.2.35  raeburn  11056:             my $skiprewrites;
1.987     raeburn  11057:             if ($count || $codebasecount) {
                   11058:                 my $saveresult;
1.1071    raeburn  11059:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11060:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11061:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11062:                     if ($url eq $container) {
                   11063:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11064:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11065:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11066:                                             $fname.'</span>').'</p>';
1.987     raeburn  11067:                     } else {
                   11068:                          $output = '<p class="LC_error">'.
                   11069:                                    &mt('Error: update failed for: [_1].',
                   11070:                                    '<span class="LC_filename">'.
                   11071:                                    $container.'</span>').'</p>';
                   11072:                     }
1.1075.2.35  raeburn  11073:                     if ($context eq 'syllabus') {
                   11074:                         unless ($saveresult eq 'ok') {
                   11075:                             $skiprewrites = 1;
                   11076:                         }
                   11077:                     }
1.987     raeburn  11078:                 } else {
                   11079:                     if (open(my $fh,">$container")) {
                   11080:                         print $fh $content;
                   11081:                         close($fh);
                   11082:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11083:                                   $count,'<span class="LC_filename">'.
                   11084:                                   $container.'</span>').'</p>';
1.661     raeburn  11085:                     } else {
1.987     raeburn  11086:                          $output = '<p class="LC_error">'.
                   11087:                                    &mt('Error: could not update [_1].',
                   11088:                                    '<span class="LC_filename">'.
                   11089:                                    $container.'</span>').'</p>';
1.661     raeburn  11090:                     }
                   11091:                 }
                   11092:             }
1.1075.2.35  raeburn  11093:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11094:                 my ($actionurl,$state);
                   11095:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11096:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11097:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11098:                                               \%codebase,
                   11099:                                               {'context' => 'rewrites',
                   11100:                                                'ignore_remote_references' => 1,});
                   11101:                 if (ref($mapping) eq 'HASH') {
                   11102:                     my $rewrites = 0;
                   11103:                     foreach my $key (keys(%{$mapping})) {
                   11104:                         next if ($key =~ m{^https?://});
                   11105:                         my $ref = $mapping->{$key};
                   11106:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11107:                         my $attrib;
                   11108:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11109:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11110:                         }
                   11111:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11112:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11113:                             $rewrites += $numchg;
                   11114:                         }
                   11115:                     }
                   11116:                     if ($rewrites) {
                   11117:                         my $saveresult;
                   11118:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11119:                         if ($url eq $container) {
                   11120:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11121:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11122:                                             $count,'<span class="LC_filename">'.
                   11123:                                             $fname.'</span>').'</p>';
                   11124:                         } else {
                   11125:                             $output .= '<p class="LC_error">'.
                   11126:                                        &mt('Error: could not update links in [_1].',
                   11127:                                        '<span class="LC_filename">'.
                   11128:                                        $container.'</span>').'</p>';
                   11129: 
                   11130:                         }
                   11131:                     }
                   11132:                 }
                   11133:             }
1.987     raeburn  11134:         } else {
                   11135:             &logthis('Failed to parse '.$container.
                   11136:                      ' to modify references: '.$parse_result);
1.661     raeburn  11137:         }
                   11138:     }
1.1071    raeburn  11139:     if (wantarray) {
                   11140:         return ($output,$count,$codebasecount);
                   11141:     } else {
                   11142:         return $output;
                   11143:     }
1.661     raeburn  11144: }
                   11145: 
                   11146: sub check_for_existing {
                   11147:     my ($path,$fname,$element) = @_;
                   11148:     my ($state,$msg);
                   11149:     if (-d $path.'/'.$fname) {
                   11150:         $state = 'exists';
                   11151:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11152:     } elsif (-e $path.'/'.$fname) {
                   11153:         $state = 'exists';
                   11154:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11155:     }
                   11156:     if ($state eq 'exists') {
                   11157:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11158:     }
                   11159:     return ($state,$msg);
                   11160: }
                   11161: 
                   11162: sub check_for_upload {
                   11163:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11164:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11165:     my $filesize = length($env{'form.'.$element});
                   11166:     if (!$filesize) {
                   11167:         my $msg = '<span class="LC_error">'.
                   11168:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11169:                       '<span class="LC_filename">'.$fname.'</span>',
                   11170:                       $filesize).'<br />'.
1.1007    raeburn  11171:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11172:                   '</span>';
                   11173:         return ('zero_bytes',$msg);
                   11174:     }
                   11175:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11176:     my $getpropath = 1;
1.1021    raeburn  11177:     my ($dirlistref,$listerror) =
                   11178:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11179:     my $found_file = 0;
                   11180:     my $locked_file = 0;
1.991     raeburn  11181:     my @lockers;
                   11182:     my $navmap;
                   11183:     if ($env{'request.course.id'}) {
                   11184:         $navmap = Apache::lonnavmaps::navmap->new();
                   11185:     }
1.1021    raeburn  11186:     if (ref($dirlistref) eq 'ARRAY') {
                   11187:         foreach my $line (@{$dirlistref}) {
                   11188:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11189:             if ($file_name eq $fname){
                   11190:                 $file_name = $path.$file_name;
                   11191:                 if ($group ne '') {
                   11192:                     $file_name = $group.$file_name;
                   11193:                 }
                   11194:                 $found_file = 1;
                   11195:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11196:                     foreach my $lock (@lockers) {
                   11197:                         if (ref($lock) eq 'ARRAY') {
                   11198:                             my ($symb,$crsid) = @{$lock};
                   11199:                             if ($crsid eq $env{'request.course.id'}) {
                   11200:                                 if (ref($navmap)) {
                   11201:                                     my $res = $navmap->getBySymb($symb);
                   11202:                                     foreach my $part (@{$res->parts()}) { 
                   11203:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11204:                                         unless (($slot_status == $res->RESERVED) ||
                   11205:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11206:                                             $locked_file = 1;
                   11207:                                         }
1.991     raeburn  11208:                                     }
1.1021    raeburn  11209:                                 } else {
                   11210:                                     $locked_file = 1;
1.991     raeburn  11211:                                 }
                   11212:                             } else {
                   11213:                                 $locked_file = 1;
                   11214:                             }
                   11215:                         }
1.1021    raeburn  11216:                    }
                   11217:                 } else {
                   11218:                     my @info = split(/\&/,$rest);
                   11219:                     my $currsize = $info[6]/1000;
                   11220:                     if ($currsize < $filesize) {
                   11221:                         my $extra = $filesize - $currsize;
                   11222:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11223:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11224:                                       &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.1075.2.69  raeburn  11225:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11226:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11227:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11228:                             return ('will_exceed_quota',$msg);
                   11229:                         }
1.984     raeburn  11230:                     }
                   11231:                 }
1.661     raeburn  11232:             }
                   11233:         }
                   11234:     }
                   11235:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11236:         my $msg = '<p class="LC_warning">'.
                   11237:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11238:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11239:         return ('will_exceed_quota',$msg);
                   11240:     } elsif ($found_file) {
                   11241:         if ($locked_file) {
1.1075.2.69  raeburn  11242:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11243:             $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.1075.2.69  raeburn  11244:             $msg .= '</p>';
1.661     raeburn  11245:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11246:             return ('file_locked',$msg);
                   11247:         } else {
1.1075.2.69  raeburn  11248:             my $msg = '<p class="LC_error">';
1.984     raeburn  11249:             $msg .= &mt(' A file by that name: [_1] was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$port_path.$env{'form.currentpath'});
1.1075.2.69  raeburn  11250:             $msg .= '</p>';
1.984     raeburn  11251:             return ('existingfile',$msg);
1.661     raeburn  11252:         }
                   11253:     }
                   11254: }
                   11255: 
1.987     raeburn  11256: sub check_for_traversal {
                   11257:     my ($path,$url,$toplevel) = @_;
                   11258:     my @parts=split(/\//,$path);
                   11259:     my $cleanpath;
                   11260:     my $fullpath = $url;
                   11261:     for (my $i=0;$i<@parts;$i++) {
                   11262:         next if ($parts[$i] eq '.');
                   11263:         if ($parts[$i] eq '..') {
                   11264:             $fullpath =~ s{([^/]+/)$}{};
                   11265:         } else {
                   11266:             $fullpath .= $parts[$i].'/';
                   11267:         }
                   11268:     }
                   11269:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11270:         $cleanpath = $1;
                   11271:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11272:         my $curr_toprel = $1;
                   11273:         my @parts = split(/\//,$curr_toprel);
                   11274:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11275:         my @urlparts = split(/\//,$url_toprel);
                   11276:         my $doubledots;
                   11277:         my $startdiff = -1;
                   11278:         for (my $i=0; $i<@urlparts; $i++) {
                   11279:             if ($startdiff == -1) {
                   11280:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11281:                     $startdiff = $i;
                   11282:                     $doubledots .= '../';
                   11283:                 }
                   11284:             } else {
                   11285:                 $doubledots .= '../';
                   11286:             }
                   11287:         }
                   11288:         if ($startdiff > -1) {
                   11289:             $cleanpath = $doubledots;
                   11290:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11291:                 $cleanpath .= $parts[$i].'/';
                   11292:             }
                   11293:         }
                   11294:     }
                   11295:     $cleanpath =~ s{(/)$}{};
                   11296:     return $cleanpath;
                   11297: }
1.31      albertel 11298: 
1.1053    raeburn  11299: sub is_archive_file {
                   11300:     my ($mimetype) = @_;
                   11301:     if (($mimetype eq 'application/octet-stream') ||
                   11302:         ($mimetype eq 'application/x-stuffit') ||
                   11303:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11304:         return 1;
                   11305:     }
                   11306:     return;
                   11307: }
                   11308: 
                   11309: sub decompress_form {
1.1065    raeburn  11310:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11311:     my %lt = &Apache::lonlocal::texthash (
                   11312:         this => 'This file is an archive file.',
1.1067    raeburn  11313:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11314:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11315:         youm => 'You may wish to extract its contents.',
                   11316:         extr => 'Extract contents',
1.1067    raeburn  11317:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11318:         proa => 'Process automatically?',
1.1053    raeburn  11319:         yes  => 'Yes',
                   11320:         no   => 'No',
1.1067    raeburn  11321:         fold => 'Title for folder containing movie',
                   11322:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11323:     );
1.1065    raeburn  11324:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11325:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11326:     my $info = &list_archive_contents($fileloc,\@paths);
                   11327:     if (@paths) {
                   11328:         foreach my $path (@paths) {
                   11329:             $path =~ s{^/}{};
1.1067    raeburn  11330:             if ($path =~ m{^([^/]+)/$}) {
                   11331:                 $topdir = $1;
                   11332:             }
1.1065    raeburn  11333:             if ($path =~ m{^([^/]+)/}) {
                   11334:                 $toplevel{$1} = $path;
                   11335:             } else {
                   11336:                 $toplevel{$path} = $path;
                   11337:             }
                   11338:         }
                   11339:     }
1.1067    raeburn  11340:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11341:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11342:                         "$topdir/media/",
                   11343:                         "$topdir/media/$topdir.mp4",
                   11344:                         "$topdir/media/FirstFrame.png",
                   11345:                         "$topdir/media/player.swf",
                   11346:                         "$topdir/media/swfobject.js",
                   11347:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11348:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11349:                          "$topdir/$topdir.mp4",
                   11350:                          "$topdir/$topdir\_config.xml",
                   11351:                          "$topdir/$topdir\_controller.swf",
                   11352:                          "$topdir/$topdir\_embed.css",
                   11353:                          "$topdir/$topdir\_First_Frame.png",
                   11354:                          "$topdir/$topdir\_player.html",
                   11355:                          "$topdir/$topdir\_Thumbnails.png",
                   11356:                          "$topdir/playerProductInstall.swf",
                   11357:                          "$topdir/scripts/",
                   11358:                          "$topdir/scripts/config_xml.js",
                   11359:                          "$topdir/scripts/handlebars.js",
                   11360:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11361:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11362:                          "$topdir/scripts/modernizr.js",
                   11363:                          "$topdir/scripts/player-min.js",
                   11364:                          "$topdir/scripts/swfobject.js",
                   11365:                          "$topdir/skins/",
                   11366:                          "$topdir/skins/configuration_express.xml",
                   11367:                          "$topdir/skins/express_show/",
                   11368:                          "$topdir/skins/express_show/player-min.css",
                   11369:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11370:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11371:                          "$topdir/$topdir.mp4",
                   11372:                          "$topdir/$topdir\_config.xml",
                   11373:                          "$topdir/$topdir\_controller.swf",
                   11374:                          "$topdir/$topdir\_embed.css",
                   11375:                          "$topdir/$topdir\_First_Frame.png",
                   11376:                          "$topdir/$topdir\_player.html",
                   11377:                          "$topdir/$topdir\_Thumbnails.png",
                   11378:                          "$topdir/playerProductInstall.swf",
                   11379:                          "$topdir/scripts/",
                   11380:                          "$topdir/scripts/config_xml.js",
                   11381:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11382:                          "$topdir/skins/",
                   11383:                          "$topdir/skins/configuration_express.xml",
                   11384:                          "$topdir/skins/express_show/",
                   11385:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11386:                          "$topdir/skins/express_show/spritesheet.png",
                   11387:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11388:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11389:         if (@diffs == 0) {
1.1075.2.59  raeburn  11390:             $is_camtasia = 6;
                   11391:         } else {
1.1075.2.81  raeburn  11392:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11393:             if (@diffs == 0) {
                   11394:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11395:             } else {
                   11396:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11397:                 if (@diffs == 0) {
                   11398:                     $is_camtasia = 8;
                   11399:                 }
1.1075.2.59  raeburn  11400:             }
1.1067    raeburn  11401:         }
                   11402:     }
                   11403:     my $output;
                   11404:     if ($is_camtasia) {
                   11405:         $output = <<"ENDCAM";
                   11406: <script type="text/javascript" language="Javascript">
                   11407: // <![CDATA[
                   11408: 
                   11409: function camtasiaToggle() {
                   11410:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11411:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11412:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11413:                 document.getElementById('camtasia_titles').style.display='block';
                   11414:             } else {
                   11415:                 document.getElementById('camtasia_titles').style.display='none';
                   11416:             }
                   11417:         }
                   11418:     }
                   11419:     return;
                   11420: }
                   11421: 
                   11422: // ]]>
                   11423: </script>
                   11424: <p>$lt{'camt'}</p>
                   11425: ENDCAM
1.1065    raeburn  11426:     } else {
1.1067    raeburn  11427:         $output = '<p>'.$lt{'this'};
                   11428:         if ($info eq '') {
                   11429:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11430:         } else {
                   11431:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11432:                        '<div><pre>'.$info.'</pre></div>';
                   11433:         }
1.1065    raeburn  11434:     }
1.1067    raeburn  11435:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11436:     my $duplicates;
                   11437:     my $num = 0;
                   11438:     if (ref($dirlist) eq 'ARRAY') {
                   11439:         foreach my $item (@{$dirlist}) {
                   11440:             if (ref($item) eq 'ARRAY') {
                   11441:                 if (exists($toplevel{$item->[0]})) {
                   11442:                     $duplicates .= 
                   11443:                         &start_data_table_row().
                   11444:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11445:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11446:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11447:                         'value="1" />'.&mt('Yes').'</label>'.
                   11448:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11449:                         '<td>'.$item->[0].'</td>';
                   11450:                     if ($item->[2]) {
                   11451:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11452:                     } else {
                   11453:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11454:                     }
                   11455:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11456:                                    '<td>'.
                   11457:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11458:                                    '</td>'.
                   11459:                                    &end_data_table_row();
                   11460:                     $num ++;
                   11461:                 }
                   11462:             }
                   11463:         }
                   11464:     }
                   11465:     my $itemcount;
                   11466:     if (@paths > 0) {
                   11467:         $itemcount = scalar(@paths);
                   11468:     } else {
                   11469:         $itemcount = 1;
                   11470:     }
1.1067    raeburn  11471:     if ($is_camtasia) {
                   11472:         $output .= $lt{'auto'}.'<br />'.
                   11473:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11474:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11475:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11476:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11477:                    $lt{'no'}.'</label></span><br />'.
                   11478:                    '<div id="camtasia_titles" style="display:block">'.
                   11479:                    &Apache::lonhtmlcommon::start_pick_box().
                   11480:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11481:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11482:                    &Apache::lonhtmlcommon::row_closure().
                   11483:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11484:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11485:                    &Apache::lonhtmlcommon::row_closure(1).
                   11486:                    &Apache::lonhtmlcommon::end_pick_box().
                   11487:                    '</div>';
                   11488:     }
1.1065    raeburn  11489:     $output .= 
                   11490:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11491:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11492:         "\n";
1.1065    raeburn  11493:     if ($duplicates ne '') {
                   11494:         $output .= '<p><span class="LC_warning">'.
                   11495:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11496:                    &start_data_table().
                   11497:                    &start_data_table_header_row().
                   11498:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11499:                    '<th>'.&mt('Name').'</th>'.
                   11500:                    '<th>'.&mt('Type').'</th>'.
                   11501:                    '<th>'.&mt('Size').'</th>'.
                   11502:                    '<th>'.&mt('Last modified').'</th>'.
                   11503:                    &end_data_table_header_row().
                   11504:                    $duplicates.
                   11505:                    &end_data_table().
                   11506:                    '</p>';
                   11507:     }
1.1067    raeburn  11508:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11509:     if (ref($hiddenelements) eq 'HASH') {
                   11510:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11511:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11512:         }
                   11513:     }
                   11514:     $output .= <<"END";
1.1067    raeburn  11515: <br />
1.1053    raeburn  11516: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11517: </form>
                   11518: $noextract
                   11519: END
                   11520:     return $output;
                   11521: }
                   11522: 
1.1065    raeburn  11523: sub decompression_utility {
                   11524:     my ($program) = @_;
                   11525:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11526:     my $location;
                   11527:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11528:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11529:                          '/usr/sbin/') {
                   11530:             if (-x $dir.$program) {
                   11531:                 $location = $dir.$program;
                   11532:                 last;
                   11533:             }
                   11534:         }
                   11535:     }
                   11536:     return $location;
                   11537: }
                   11538: 
                   11539: sub list_archive_contents {
                   11540:     my ($file,$pathsref) = @_;
                   11541:     my (@cmd,$output);
                   11542:     my $needsregexp;
                   11543:     if ($file =~ /\.zip$/) {
                   11544:         @cmd = (&decompression_utility('unzip'),"-l");
                   11545:         $needsregexp = 1;
                   11546:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   11547:              ($file =~ /\.tgz$/)) {
                   11548:         @cmd = (&decompression_utility('tar'),"-ztf");
                   11549:     } elsif ($file =~ /\.tar\.bz2$/) {
                   11550:         @cmd = (&decompression_utility('tar'),"-jtf");
                   11551:     } elsif ($file =~ m|\.tar$|) {
                   11552:         @cmd = (&decompression_utility('tar'),"-tf");
                   11553:     }
                   11554:     if (@cmd) {
                   11555:         undef($!);
                   11556:         undef($@);
                   11557:         if (open(my $fh,"-|", @cmd, $file)) {
                   11558:             while (my $line = <$fh>) {
                   11559:                 $output .= $line;
                   11560:                 chomp($line);
                   11561:                 my $item;
                   11562:                 if ($needsregexp) {
                   11563:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   11564:                 } else {
                   11565:                     $item = $line;
                   11566:                 }
                   11567:                 if ($item ne '') {
                   11568:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   11569:                         push(@{$pathsref},$item);
                   11570:                     } 
                   11571:                 }
                   11572:             }
                   11573:             close($fh);
                   11574:         }
                   11575:     }
                   11576:     return $output;
                   11577: }
                   11578: 
1.1053    raeburn  11579: sub decompress_uploaded_file {
                   11580:     my ($file,$dir) = @_;
                   11581:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   11582:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   11583:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   11584:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   11585:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   11586:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   11587:     my $decompressed = $env{'cgi.decompressed'};
                   11588:     &Apache::lonnet::delenv('cgi.file');
                   11589:     &Apache::lonnet::delenv('cgi.dir');
                   11590:     &Apache::lonnet::delenv('cgi.decompressed');
                   11591:     return ($decompressed,$result);
                   11592: }
                   11593: 
1.1055    raeburn  11594: sub process_decompression {
                   11595:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
                   11596:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  11597:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  11598:         $error = &mt('Filename not a supported archive file type.').
                   11599:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  11600:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   11601:     } else {
                   11602:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   11603:         if ($docuhome eq 'no_host') {
                   11604:             $error = &mt('Could not determine home server for course.');
                   11605:         } else {
                   11606:             my @ids=&Apache::lonnet::current_machine_ids();
                   11607:             my $currdir = "$dir_root/$destination";
                   11608:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   11609:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   11610:                        "$dir_root/$destination";
                   11611:             } else {
                   11612:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   11613:                        "$dir_root/$docudom/$docuname/$destination";
                   11614:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   11615:                     $error = &mt('Archive file not found.');
                   11616:                 }
                   11617:             }
1.1065    raeburn  11618:             my (@to_overwrite,@to_skip);
                   11619:             if ($env{'form.archive_overwrite_total'} > 0) {
                   11620:                 my $total = $env{'form.archive_overwrite_total'};
                   11621:                 for (my $i=0; $i<$total; $i++) {
                   11622:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   11623:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   11624:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   11625:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   11626:                     }
                   11627:                 }
                   11628:             }
                   11629:             my $numskip = scalar(@to_skip);
                   11630:             if (($numskip > 0) && 
                   11631:                 ($numskip == $env{'form.archive_itemcount'})) {
                   11632:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   11633:             } elsif ($dir eq '') {
1.1055    raeburn  11634:                 $error = &mt('Directory containing archive file unavailable.');
                   11635:             } elsif (!$error) {
1.1065    raeburn  11636:                 my ($decompressed,$display);
                   11637:                 if ($numskip > 0) {
                   11638:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   11639:                     mkdir("$dir/$tempdir",0755);
                   11640:                     system("mv $dir/$file $dir/$tempdir/$file");
                   11641:                     ($decompressed,$display) = 
                   11642:                         &decompress_uploaded_file($file,"$dir/$tempdir");
                   11643:                     foreach my $item (@to_skip) {
                   11644:                         if (($item ne '') && ($item !~ /\.\./)) {
                   11645:                             if (-f "$dir/$tempdir/$item") { 
                   11646:                                 unlink("$dir/$tempdir/$item");
                   11647:                             } elsif (-d "$dir/$tempdir/$item") {
                   11648:                                 system("rm -rf $dir/$tempdir/$item");
                   11649:                             }
                   11650:                         }
                   11651:                     }
                   11652:                     system("mv $dir/$tempdir/* $dir");
                   11653:                     rmdir("$dir/$tempdir");   
                   11654:                 } else {
                   11655:                     ($decompressed,$display) = 
                   11656:                         &decompress_uploaded_file($file,$dir);
                   11657:                 }
1.1055    raeburn  11658:                 if ($decompressed eq 'ok') {
1.1065    raeburn  11659:                     $output = '<p class="LC_info">'.
                   11660:                               &mt('Files extracted successfully from archive.').
                   11661:                               '</p>'."\n";
1.1055    raeburn  11662:                     my ($warning,$result,@contents);
                   11663:                     my ($newdirlistref,$newlisterror) =
                   11664:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   11665:                                                  $docuname,1);
                   11666:                     my (%is_dir,%changes,@newitems);
                   11667:                     my $dirptr = 16384;
1.1065    raeburn  11668:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  11669:                         foreach my $dir_line (@{$newdirlistref}) {
                   11670:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1065    raeburn  11671:                             unless (($item =~ /^\.+$/) || ($item eq $file) || 
                   11672:                                     ((@to_skip > 0) && (grep(/^\Q$item\E$/,@to_skip)))) {
1.1055    raeburn  11673:                                 push(@newitems,$item);
                   11674:                                 if ($dirptr&$testdir) {
                   11675:                                     $is_dir{$item} = 1;
                   11676:                                 }
                   11677:                                 $changes{$item} = 1;
                   11678:                             }
                   11679:                         }
                   11680:                     }
                   11681:                     if (keys(%changes) > 0) {
                   11682:                         foreach my $item (sort(@newitems)) {
                   11683:                             if ($changes{$item}) {
                   11684:                                 push(@contents,$item);
                   11685:                             }
                   11686:                         }
                   11687:                     }
                   11688:                     if (@contents > 0) {
1.1067    raeburn  11689:                         my $wantform;
                   11690:                         unless ($env{'form.autoextract_camtasia'}) {
                   11691:                             $wantform = 1;
                   11692:                         }
1.1056    raeburn  11693:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  11694:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   11695:                                                                 $currdir,\%is_dir,
                   11696:                                                                 \%children,\%parent,
1.1056    raeburn  11697:                                                                 \@contents,\%dirorder,
                   11698:                                                                 \%titles,$wantform);
1.1055    raeburn  11699:                         if ($datatable ne '') {
                   11700:                             $output .= &archive_options_form('decompressed',$datatable,
                   11701:                                                              $count,$hiddenelem);
1.1065    raeburn  11702:                             my $startcount = 6;
1.1055    raeburn  11703:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  11704:                                                            \%titles,\%children);
1.1055    raeburn  11705:                         }
1.1067    raeburn  11706:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  11707:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  11708:                             my %displayed;
                   11709:                             my $total = 1;
                   11710:                             $env{'form.archive_directory'} = [];
                   11711:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   11712:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   11713:                                 $path =~ s{/$}{};
                   11714:                                 my $item;
                   11715:                                 if ($path ne '') {
                   11716:                                     $item = "$path/$titles{$i}";
                   11717:                                 } else {
                   11718:                                     $item = $titles{$i};
                   11719:                                 }
                   11720:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   11721:                                 if ($item eq $contents[0]) {
                   11722:                                     push(@{$env{'form.archive_directory'}},$i);
                   11723:                                     $env{'form.archive_'.$i} = 'display';
                   11724:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   11725:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  11726:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   11727:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  11728:                                     $env{'form.archive_'.$i} = 'display';
                   11729:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   11730:                                     $displayed{'web'} = $i;
                   11731:                                 } else {
1.1075.2.59  raeburn  11732:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   11733:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   11734:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  11735:                                         push(@{$env{'form.archive_directory'}},$i);
                   11736:                                     }
                   11737:                                     $env{'form.archive_'.$i} = 'dependency';
                   11738:                                 }
                   11739:                                 $total ++;
                   11740:                             }
                   11741:                             for (my $i=1; $i<$total; $i++) {
                   11742:                                 next if ($i == $displayed{'web'});
                   11743:                                 next if ($i == $displayed{'folder'});
                   11744:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   11745:                             }
                   11746:                             $env{'form.phase'} = 'decompress_cleanup';
                   11747:                             $env{'form.archivedelete'} = 1;
                   11748:                             $env{'form.archive_count'} = $total-1;
                   11749:                             $output .=
                   11750:                                 &process_extracted_files('coursedocs',$docudom,
                   11751:                                                          $docuname,$destination,
                   11752:                                                          $dir_root,$hiddenelem);
                   11753:                         }
1.1055    raeburn  11754:                     } else {
                   11755:                         $warning = &mt('No new items extracted from archive file.');
                   11756:                     }
                   11757:                 } else {
                   11758:                     $output = $display;
                   11759:                     $error = &mt('An error occurred during extraction from the archive file.');
                   11760:                 }
                   11761:             }
                   11762:         }
                   11763:     }
                   11764:     if ($error) {
                   11765:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   11766:                    $error.'</p>'."\n";
                   11767:     }
                   11768:     if ($warning) {
                   11769:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   11770:     }
                   11771:     return $output;
                   11772: }
                   11773: 
                   11774: sub get_extracted {
1.1056    raeburn  11775:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   11776:         $titles,$wantform) = @_;
1.1055    raeburn  11777:     my $count = 0;
                   11778:     my $depth = 0;
                   11779:     my $datatable;
1.1056    raeburn  11780:     my @hierarchy;
1.1055    raeburn  11781:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  11782:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   11783:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  11784:     foreach my $item (@{$contents}) {
                   11785:         $count ++;
1.1056    raeburn  11786:         @{$dirorder->{$count}} = @hierarchy;
                   11787:         $titles->{$count} = $item;
1.1055    raeburn  11788:         &archive_hierarchy($depth,$count,$parent,$children);
                   11789:         if ($wantform) {
                   11790:             $datatable .= &archive_row($is_dir->{$item},$item,
                   11791:                                        $currdir,$depth,$count);
                   11792:         }
                   11793:         if ($is_dir->{$item}) {
                   11794:             $depth ++;
1.1056    raeburn  11795:             push(@hierarchy,$count);
                   11796:             $parent->{$depth} = $count;
1.1055    raeburn  11797:             $datatable .=
                   11798:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  11799:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   11800:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  11801:             $depth --;
1.1056    raeburn  11802:             pop(@hierarchy);
1.1055    raeburn  11803:         }
                   11804:     }
                   11805:     return ($count,$datatable);
                   11806: }
                   11807: 
                   11808: sub recurse_extracted_archive {
1.1056    raeburn  11809:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   11810:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  11811:     my $result='';
1.1056    raeburn  11812:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   11813:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   11814:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  11815:         return $result;
                   11816:     }
                   11817:     my $dirptr = 16384;
                   11818:     my ($newdirlistref,$newlisterror) =
                   11819:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   11820:     if (ref($newdirlistref) eq 'ARRAY') {
                   11821:         foreach my $dir_line (@{$newdirlistref}) {
                   11822:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   11823:             unless ($item =~ /^\.+$/) {
                   11824:                 $$count ++;
1.1056    raeburn  11825:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   11826:                 $titles->{$$count} = $item;
1.1055    raeburn  11827:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  11828: 
1.1055    raeburn  11829:                 my $is_dir;
                   11830:                 if ($dirptr&$testdir) {
                   11831:                     $is_dir = 1;
                   11832:                 }
                   11833:                 if ($wantform) {
                   11834:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   11835:                 }
                   11836:                 if ($is_dir) {
                   11837:                     $$depth ++;
1.1056    raeburn  11838:                     push(@{$hierarchy},$$count);
                   11839:                     $parent->{$$depth} = $$count;
1.1055    raeburn  11840:                     $result .=
                   11841:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   11842:                                                    $docuname,$depth,$count,
1.1056    raeburn  11843:                                                    $hierarchy,$dirorder,$children,
                   11844:                                                    $parent,$titles,$wantform);
1.1055    raeburn  11845:                     $$depth --;
1.1056    raeburn  11846:                     pop(@{$hierarchy});
1.1055    raeburn  11847:                 }
                   11848:             }
                   11849:         }
                   11850:     }
                   11851:     return $result;
                   11852: }
                   11853: 
                   11854: sub archive_hierarchy {
                   11855:     my ($depth,$count,$parent,$children) =@_;
                   11856:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   11857:         if (exists($parent->{$depth})) {
                   11858:              $children->{$parent->{$depth}} .= $count.':';
                   11859:         }
                   11860:     }
                   11861:     return;
                   11862: }
                   11863: 
                   11864: sub archive_row {
                   11865:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   11866:     my ($name) = ($item =~ m{([^/]+)$});
                   11867:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  11868:                                        'display'    => 'Add as file',
1.1055    raeburn  11869:                                        'dependency' => 'Include as dependency',
                   11870:                                        'discard'    => 'Discard',
                   11871:                                       );
                   11872:     if ($is_dir) {
1.1059    raeburn  11873:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  11874:     }
1.1056    raeburn  11875:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   11876:     my $offset = 0;
1.1055    raeburn  11877:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  11878:         $offset ++;
1.1065    raeburn  11879:         if ($action ne 'display') {
                   11880:             $offset ++;
                   11881:         }  
1.1055    raeburn  11882:         $output .= '<td><span class="LC_nobreak">'.
                   11883:                    '<label><input type="radio" name="archive_'.$count.
                   11884:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   11885:         my $text = $choices{$action};
                   11886:         if ($is_dir) {
                   11887:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   11888:             if ($action eq 'display') {
1.1059    raeburn  11889:                 $text = &mt('Add as folder');
1.1055    raeburn  11890:             }
1.1056    raeburn  11891:         } else {
                   11892:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   11893: 
                   11894:         }
                   11895:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   11896:         if ($action eq 'dependency') {
                   11897:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   11898:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   11899:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   11900:                        '<option value=""></option>'."\n".
                   11901:                        '</select>'."\n".
                   11902:                        '</div>';
1.1059    raeburn  11903:         } elsif ($action eq 'display') {
                   11904:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   11905:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   11906:                        '</div>';
1.1055    raeburn  11907:         }
1.1056    raeburn  11908:         $output .= '</td>';
1.1055    raeburn  11909:     }
                   11910:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   11911:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   11912:     for (my $i=0; $i<$depth; $i++) {
                   11913:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   11914:     }
                   11915:     if ($is_dir) {
                   11916:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   11917:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   11918:     } else {
                   11919:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   11920:     }
                   11921:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   11922:                &end_data_table_row();
                   11923:     return $output;
                   11924: }
                   11925: 
                   11926: sub archive_options_form {
1.1065    raeburn  11927:     my ($form,$display,$count,$hiddenelem) = @_;
                   11928:     my %lt = &Apache::lonlocal::texthash(
                   11929:                perm => 'Permanently remove archive file?',
                   11930:                hows => 'How should each extracted item be incorporated in the course?',
                   11931:                cont => 'Content actions for all',
                   11932:                addf => 'Add as folder/file',
                   11933:                incd => 'Include as dependency for a displayed file',
                   11934:                disc => 'Discard',
                   11935:                no   => 'No',
                   11936:                yes  => 'Yes',
                   11937:                save => 'Save',
                   11938:     );
                   11939:     my $output = <<"END";
                   11940: <form name="$form" method="post" action="">
                   11941: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   11942: <label>
                   11943:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   11944: </label>
                   11945: &nbsp;
                   11946: <label>
                   11947:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   11948: </span>
                   11949: </p>
                   11950: <input type="hidden" name="phase" value="decompress_cleanup" />
                   11951: <br />$lt{'hows'}
                   11952: <div class="LC_columnSection">
                   11953:   <fieldset>
                   11954:     <legend>$lt{'cont'}</legend>
                   11955:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   11956:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   11957:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   11958:   </fieldset>
                   11959: </div>
                   11960: END
                   11961:     return $output.
1.1055    raeburn  11962:            &start_data_table()."\n".
1.1065    raeburn  11963:            $display."\n".
1.1055    raeburn  11964:            &end_data_table()."\n".
                   11965:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   11966:            $hiddenelem.
1.1065    raeburn  11967:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  11968:            '</form>';
                   11969: }
                   11970: 
                   11971: sub archive_javascript {
1.1056    raeburn  11972:     my ($startcount,$numitems,$titles,$children) = @_;
                   11973:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  11974:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  11975:     my $scripttag = <<START;
                   11976: <script type="text/javascript">
                   11977: // <![CDATA[
                   11978: 
                   11979: function checkAll(form,prefix) {
                   11980:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   11981:     for (var i=0; i < form.elements.length; i++) {
                   11982:         var id = form.elements[i].id;
                   11983:         if ((id != '') && (id != undefined)) {
                   11984:             if (idstr.test(id)) {
                   11985:                 if (form.elements[i].type == 'radio') {
                   11986:                     form.elements[i].checked = true;
1.1056    raeburn  11987:                     var nostart = i-$startcount;
1.1059    raeburn  11988:                     var offset = nostart%7;
                   11989:                     var count = (nostart-offset)/7;    
1.1056    raeburn  11990:                     dependencyCheck(form,count,offset);
1.1055    raeburn  11991:                 }
                   11992:             }
                   11993:         }
                   11994:     }
                   11995: }
                   11996: 
                   11997: function propagateCheck(form,count) {
                   11998:     if (count > 0) {
1.1059    raeburn  11999:         var startelement = $startcount + ((count-1) * 7);
                   12000:         for (var j=1; j<6; j++) {
                   12001:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12002:                 var item = startelement + j; 
                   12003:                 if (form.elements[item].type == 'radio') {
                   12004:                     if (form.elements[item].checked) {
                   12005:                         containerCheck(form,count,j);
                   12006:                         break;
                   12007:                     }
1.1055    raeburn  12008:                 }
                   12009:             }
                   12010:         }
                   12011:     }
                   12012: }
                   12013: 
                   12014: numitems = $numitems
1.1056    raeburn  12015: var titles = new Array(numitems);
                   12016: var parents = new Array(numitems);
1.1055    raeburn  12017: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12018:     parents[i] = new Array;
1.1055    raeburn  12019: }
1.1059    raeburn  12020: var maintitle = '$maintitle';
1.1055    raeburn  12021: 
                   12022: START
                   12023: 
1.1056    raeburn  12024:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12025:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12026:         for (my $i=0; $i<@contents; $i ++) {
                   12027:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12028:         }
                   12029:     }
                   12030: 
1.1056    raeburn  12031:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12032:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12033:     }
                   12034: 
1.1055    raeburn  12035:     $scripttag .= <<END;
                   12036: 
                   12037: function containerCheck(form,count,offset) {
                   12038:     if (count > 0) {
1.1056    raeburn  12039:         dependencyCheck(form,count,offset);
1.1059    raeburn  12040:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12041:         form.elements[item].checked = true;
                   12042:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12043:             if (parents[count].length > 0) {
                   12044:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12045:                     containerCheck(form,parents[count][j],offset);
                   12046:                 }
                   12047:             }
                   12048:         }
                   12049:     }
                   12050: }
                   12051: 
                   12052: function dependencyCheck(form,count,offset) {
                   12053:     if (count > 0) {
1.1059    raeburn  12054:         var chosen = (offset+$startcount)+7*(count-1);
                   12055:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12056:         var currtype = form.elements[depitem].type;
                   12057:         if (form.elements[chosen].value == 'dependency') {
                   12058:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12059:             form.elements[depitem].options.length = 0;
                   12060:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12061:             for (var i=1; i<=numitems; i++) {
                   12062:                 if (i == count) {
                   12063:                     continue;
                   12064:                 }
1.1059    raeburn  12065:                 var startelement = $startcount + (i-1) * 7;
                   12066:                 for (var j=1; j<6; j++) {
                   12067:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12068:                         var item = startelement + j;
                   12069:                         if (form.elements[item].type == 'radio') {
                   12070:                             if (form.elements[item].checked) {
                   12071:                                 if (form.elements[item].value == 'display') {
                   12072:                                     var n = form.elements[depitem].options.length;
                   12073:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12074:                                 }
                   12075:                             }
                   12076:                         }
                   12077:                     }
                   12078:                 }
                   12079:             }
                   12080:         } else {
                   12081:             document.getElementById('arc_depon_'+count).style.display='none';
                   12082:             form.elements[depitem].options.length = 0;
                   12083:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12084:         }
1.1059    raeburn  12085:         titleCheck(form,count,offset);
1.1056    raeburn  12086:     }
                   12087: }
                   12088: 
                   12089: function propagateSelect(form,count,offset) {
                   12090:     if (count > 0) {
1.1065    raeburn  12091:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12092:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12093:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12094:             if (parents[count].length > 0) {
                   12095:                 for (var j=0; j<parents[count].length; j++) {
                   12096:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12097:                 }
                   12098:             }
                   12099:         }
                   12100:     }
                   12101: }
1.1056    raeburn  12102: 
                   12103: function containerSelect(form,count,offset,picked) {
                   12104:     if (count > 0) {
1.1065    raeburn  12105:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12106:         if (form.elements[item].type == 'radio') {
                   12107:             if (form.elements[item].value == 'dependency') {
                   12108:                 if (form.elements[item+1].type == 'select-one') {
                   12109:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12110:                         if (form.elements[item+1].options[i].value == picked) {
                   12111:                             form.elements[item+1].selectedIndex = i;
                   12112:                             break;
                   12113:                         }
                   12114:                     }
                   12115:                 }
                   12116:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12117:                     if (parents[count].length > 0) {
                   12118:                         for (var j=0; j<parents[count].length; j++) {
                   12119:                             containerSelect(form,parents[count][j],offset,picked);
                   12120:                         }
                   12121:                     }
                   12122:                 }
                   12123:             }
                   12124:         }
                   12125:     }
                   12126: }
                   12127: 
1.1059    raeburn  12128: function titleCheck(form,count,offset) {
                   12129:     if (count > 0) {
                   12130:         var chosen = (offset+$startcount)+7*(count-1);
                   12131:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12132:         var currtype = form.elements[depitem].type;
                   12133:         if (form.elements[chosen].value == 'display') {
                   12134:             document.getElementById('arc_title_'+count).style.display='block';
                   12135:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12136:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12137:             }
                   12138:         } else {
                   12139:             document.getElementById('arc_title_'+count).style.display='none';
                   12140:             if (currtype == 'text') { 
                   12141:                 document.getElementById('archive_title_'+count).value='';
                   12142:             }
                   12143:         }
                   12144:     }
                   12145:     return;
                   12146: }
                   12147: 
1.1055    raeburn  12148: // ]]>
                   12149: </script>
                   12150: END
                   12151:     return $scripttag;
                   12152: }
                   12153: 
                   12154: sub process_extracted_files {
1.1067    raeburn  12155:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12156:     my $numitems = $env{'form.archive_count'};
                   12157:     return unless ($numitems);
                   12158:     my @ids=&Apache::lonnet::current_machine_ids();
                   12159:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12160:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12161:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12162:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12163:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12164:         $pathtocheck = "$dir_root/$destination";
                   12165:         $dir = $dir_root;
                   12166:         $ishome = 1;
                   12167:     } else {
                   12168:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12169:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
                   12170:         $dir = "$dir_root/$docudom/$docuname";    
                   12171:     }
                   12172:     my $currdir = "$dir_root/$destination";
                   12173:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12174:     if ($env{'form.folderpath'}) {
                   12175:         my @items = split('&',$env{'form.folderpath'});
                   12176:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12177:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12178:             $containers{'0'}='page';
                   12179:         } else {
                   12180:             $containers{'0'}='sequence';
                   12181:         }
1.1055    raeburn  12182:     }
                   12183:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12184:     if ($numitems) {
                   12185:         for (my $i=1; $i<=$numitems; $i++) {
                   12186:             my $path = $env{'form.archive_content_'.$i};
                   12187:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12188:                 my $item = $1;
                   12189:                 $toplevelitems{$item} = $i;
                   12190:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12191:                     $is_dir{$item} = 1;
                   12192:                 }
                   12193:             }
                   12194:         }
                   12195:     }
1.1067    raeburn  12196:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12197:     if (keys(%toplevelitems) > 0) {
                   12198:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12199:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12200:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12201:     }
1.1066    raeburn  12202:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12203:     if ($numitems) {
                   12204:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12205:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12206:             my $path = $env{'form.archive_content_'.$i};
                   12207:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12208:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12209:                     if ($prefix ne '' && $path ne '') {
                   12210:                         if (-e $prefix.$path) {
1.1066    raeburn  12211:                             if ((@archdirs > 0) && 
                   12212:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12213:                                 $todeletedir{$prefix.$path} = 1;
                   12214:                             } else {
                   12215:                                 $todelete{$prefix.$path} = 1;
                   12216:                             }
1.1055    raeburn  12217:                         }
                   12218:                     }
                   12219:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12220:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12221:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12222:                     $docstitle = $env{'form.archive_title_'.$i};
                   12223:                     if ($docstitle eq '') {
                   12224:                         $docstitle = $title;
                   12225:                     }
1.1055    raeburn  12226:                     $outer = 0;
1.1056    raeburn  12227:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12228:                         if (@{$dirorder{$i}} > 0) {
                   12229:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12230:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12231:                                     $outer = $item;
                   12232:                                     last;
                   12233:                                 }
                   12234:                             }
                   12235:                         }
                   12236:                     }
                   12237:                     my ($errtext,$fatal) = 
                   12238:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12239:                                                '/'.$folders{$outer}.'.'.
                   12240:                                                $containers{$outer});
                   12241:                     next if ($fatal);
                   12242:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12243:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12244:                             $mapinner{$i} = time;
1.1055    raeburn  12245:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12246:                             $containers{$i} = 'sequence';
                   12247:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12248:                                       $folders{$i}.'.'.$containers{$i};
                   12249:                             my $newidx = &LONCAPA::map::getresidx();
                   12250:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12251:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12252:                             push(@LONCAPA::map::order,$newidx);
                   12253:                             my ($outtext,$errtext) =
                   12254:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12255:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12256:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12257:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12258:                             unless ($errtext) {
                   12259:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',$docstitle).'</li>'."\n";
                   12260:                             }
1.1055    raeburn  12261:                         }
                   12262:                     } else {
                   12263:                         if ($context eq 'coursedocs') {
                   12264:                             my $newidx=&LONCAPA::map::getresidx();
                   12265:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12266:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12267:                                       $title;
                   12268:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12269:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
                   12270:                             }
                   12271:                             if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12272:                                 mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12273:                             }
                   12274:                             if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12275:                                 system("mv $prefix$path $prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title");
1.1056    raeburn  12276:                                 $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
1.1067    raeburn  12277:                                 unless ($ishome) {
                   12278:                                     my $fetch = "$newdest{$i}/$title";
                   12279:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12280:                                     $prompttofetch{$fetch} = 1;
                   12281:                                 }
1.1055    raeburn  12282:                             }
                   12283:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12284:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12285:                             push(@LONCAPA::map::order, $newidx);
                   12286:                             my ($outtext,$errtext)=
                   12287:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12288:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12289:                                                         '.'.$containers{$outer},1,1);
1.1067    raeburn  12290:                             unless ($errtext) {
                   12291:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12292:                                     $result .= '<li>'.&mt('File: [_1] added to course',$docstitle).'</li>'."\n";
                   12293:                                 }
                   12294:                             }
1.1055    raeburn  12295:                         }
                   12296:                     }
1.1075.2.11  raeburn  12297:                 }
                   12298:             } else {
                   12299:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
                   12300:             }
                   12301:         }
                   12302:         for (my $i=1; $i<=$numitems; $i++) {
                   12303:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12304:             my $path = $env{'form.archive_content_'.$i};
                   12305:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12306:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12307:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12308:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12309:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12310:                         my ($itemidx,$fullpath,$relpath);
                   12311:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12312:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12313:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12314:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12315:                                     $itemidx = $j;
1.1056    raeburn  12316:                                 }
                   12317:                             }
1.1075.2.11  raeburn  12318:                         }
                   12319:                         if ($itemidx eq '') {
                   12320:                             $itemidx =  0;
                   12321:                         }
                   12322:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12323:                             if ($mapinner{$referrer{$i}}) {
                   12324:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12325:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12326:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12327:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12328:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12329:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12330:                                             if (!-e $fullpath) {
                   12331:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12332:                                             }
                   12333:                                         }
1.1075.2.11  raeburn  12334:                                     } else {
                   12335:                                         last;
1.1056    raeburn  12336:                                     }
1.1075.2.11  raeburn  12337:                                 }
                   12338:                             }
                   12339:                         } elsif ($newdest{$referrer{$i}}) {
                   12340:                             $fullpath = $newdest{$referrer{$i}};
                   12341:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12342:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12343:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12344:                                     last;
                   12345:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12346:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12347:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12348:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12349:                                         if (!-e $fullpath) {
                   12350:                                             mkdir($fullpath,0755);
1.1056    raeburn  12351:                                         }
                   12352:                                     }
1.1075.2.11  raeburn  12353:                                 } else {
                   12354:                                     last;
1.1056    raeburn  12355:                                 }
1.1075.2.11  raeburn  12356:                             }
                   12357:                         }
                   12358:                         if ($fullpath ne '') {
                   12359:                             if (-e "$prefix$path") {
                   12360:                                 system("mv $prefix$path $fullpath/$title");
                   12361:                             }
                   12362:                             if (-e "$fullpath/$title") {
                   12363:                                 my $showpath;
                   12364:                                 if ($relpath ne '') {
                   12365:                                     $showpath = "$relpath/$title";
                   12366:                                 } else {
                   12367:                                     $showpath = "/$title";
1.1056    raeburn  12368:                                 }
1.1075.2.11  raeburn  12369:                                 $result .= '<li>'.&mt('[_1] included as a dependency',$showpath).'</li>'."\n";
                   12370:                             }
                   12371:                             unless ($ishome) {
                   12372:                                 my $fetch = "$fullpath/$title";
                   12373:                                 $fetch =~ s/^\Q$prefix$dir\E//;
                   12374:                                 $prompttofetch{$fetch} = 1;
1.1055    raeburn  12375:                             }
                   12376:                         }
                   12377:                     }
1.1075.2.11  raeburn  12378:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12379:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
                   12380:                                     $path,$env{'form.archive_content_'.$referrer{$i}}).'<br />';
1.1055    raeburn  12381:                 }
                   12382:             } else {
1.1075.2.11  raeburn  12383:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',$path).'<br />';
1.1055    raeburn  12384:             }
                   12385:         }
                   12386:         if (keys(%todelete)) {
                   12387:             foreach my $key (keys(%todelete)) {
                   12388:                 unlink($key);
1.1066    raeburn  12389:             }
                   12390:         }
                   12391:         if (keys(%todeletedir)) {
                   12392:             foreach my $key (keys(%todeletedir)) {
                   12393:                 rmdir($key);
                   12394:             }
                   12395:         }
                   12396:         foreach my $dir (sort(keys(%is_dir))) {
                   12397:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12398:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12399:             }
                   12400:         }
1.1067    raeburn  12401:         if ($result ne '') {
                   12402:             $output .= '<ul>'."\n".
                   12403:                        $result."\n".
                   12404:                        '</ul>';
                   12405:         }
                   12406:         unless ($ishome) {
                   12407:             my $replicationfail;
                   12408:             foreach my $item (keys(%prompttofetch)) {
                   12409:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12410:                 unless ($fetchresult eq 'ok') {
                   12411:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12412:                 }
                   12413:             }
                   12414:             if ($replicationfail) {
                   12415:                 $output .= '<p class="LC_error">'.
                   12416:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12417:                            $replicationfail.
                   12418:                            '</ul></p>';
                   12419:             }
                   12420:         }
1.1055    raeburn  12421:     } else {
                   12422:         $warning = &mt('No items found in archive.');
                   12423:     }
                   12424:     if ($error) {
                   12425:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12426:                    $error.'</p>'."\n";
                   12427:     }
                   12428:     if ($warning) {
                   12429:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12430:     }
                   12431:     return $output;
                   12432: }
                   12433: 
1.1066    raeburn  12434: sub cleanup_empty_dirs {
                   12435:     my ($path) = @_;
                   12436:     if (($path ne '') && (-d $path)) {
                   12437:         if (opendir(my $dirh,$path)) {
                   12438:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12439:             my $numitems = 0;
                   12440:             foreach my $item (@dircontents) {
                   12441:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12442:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12443:                     if (-e "$path/$item") {
                   12444:                         $numitems ++;
                   12445:                     }
                   12446:                 } else {
                   12447:                     $numitems ++;
                   12448:                 }
                   12449:             }
                   12450:             if ($numitems == 0) {
                   12451:                 rmdir($path);
                   12452:             }
                   12453:             closedir($dirh);
                   12454:         }
                   12455:     }
                   12456:     return;
                   12457: }
                   12458: 
1.41      ng       12459: =pod
1.45      matthew  12460: 
1.1075.2.56  raeburn  12461: =item * &get_folder_hierarchy()
1.1068    raeburn  12462: 
                   12463: Provides hierarchy of names of folders/sub-folders containing the current
                   12464: item,
                   12465: 
                   12466: Inputs: 3
                   12467:      - $navmap - navmaps object
                   12468: 
                   12469:      - $map - url for map (either the trigger itself, or map containing
                   12470:                            the resource, which is the trigger).
                   12471: 
                   12472:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12473: 
                   12474: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12475: 
                   12476: =cut
                   12477: 
                   12478: sub get_folder_hierarchy {
                   12479:     my ($navmap,$map,$showitem) = @_;
                   12480:     my @pathitems;
                   12481:     if (ref($navmap)) {
                   12482:         my $mapres = $navmap->getResourceByUrl($map);
                   12483:         if (ref($mapres)) {
                   12484:             my $pcslist = $mapres->map_hierarchy();
                   12485:             if ($pcslist ne '') {
                   12486:                 my @pcs = split(/,/,$pcslist);
                   12487:                 foreach my $pc (@pcs) {
                   12488:                     if ($pc == 1) {
1.1075.2.38  raeburn  12489:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12490:                     } else {
                   12491:                         my $res = $navmap->getByMapPc($pc);
                   12492:                         if (ref($res)) {
                   12493:                             my $title = $res->compTitle();
                   12494:                             $title =~ s/\W+/_/g;
                   12495:                             if ($title ne '') {
                   12496:                                 push(@pathitems,$title);
                   12497:                             }
                   12498:                         }
                   12499:                     }
                   12500:                 }
                   12501:             }
1.1071    raeburn  12502:             if ($showitem) {
                   12503:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  12504:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  12505:                 } else {
                   12506:                     my $maptitle = $mapres->compTitle();
                   12507:                     $maptitle =~ s/\W+/_/g;
                   12508:                     if ($maptitle ne '') {
                   12509:                         push(@pathitems,$maptitle);
                   12510:                     }
1.1068    raeburn  12511:                 }
                   12512:             }
                   12513:         }
                   12514:     }
                   12515:     return @pathitems;
                   12516: }
                   12517: 
                   12518: =pod
                   12519: 
1.1015    raeburn  12520: =item * &get_turnedin_filepath()
                   12521: 
                   12522: Determines path in a user's portfolio file for storage of files uploaded
                   12523: to a specific essayresponse or dropbox item.
                   12524: 
                   12525: Inputs: 3 required + 1 optional.
                   12526: $symb is symb for resource, $uname and $udom are for current user (required).
                   12527: $caller is optional (can be "submission", if routine is called when storing
                   12528: an upoaded file when "Submit Answer" button was pressed).
                   12529: 
                   12530: Returns array containing $path and $multiresp. 
                   12531: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   12532: than one file upload item.  Callers of routine should append partid as a 
                   12533: subdirectory to $path in cases where $multiresp is 1.
                   12534: 
                   12535: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   12536: 
                   12537: =cut
                   12538: 
                   12539: sub get_turnedin_filepath {
                   12540:     my ($symb,$uname,$udom,$caller) = @_;
                   12541:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   12542:     my $turnindir;
                   12543:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   12544:     $turnindir = $userhash{'turnindir'};
                   12545:     my ($path,$multiresp);
                   12546:     if ($turnindir eq '') {
                   12547:         if ($caller eq 'submission') {
                   12548:             $turnindir = &mt('turned in');
                   12549:             $turnindir =~ s/\W+/_/g;
                   12550:             my %newhash = (
                   12551:                             'turnindir' => $turnindir,
                   12552:                           );
                   12553:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   12554:         }
                   12555:     }
                   12556:     if ($turnindir ne '') {
                   12557:         $path = '/'.$turnindir.'/';
                   12558:         my ($multipart,$turnin,@pathitems);
                   12559:         my $navmap = Apache::lonnavmaps::navmap->new();
                   12560:         if (defined($navmap)) {
                   12561:             my $mapres = $navmap->getResourceByUrl($map);
                   12562:             if (ref($mapres)) {
                   12563:                 my $pcslist = $mapres->map_hierarchy();
                   12564:                 if ($pcslist ne '') {
                   12565:                     foreach my $pc (split(/,/,$pcslist)) {
                   12566:                         my $res = $navmap->getByMapPc($pc);
                   12567:                         if (ref($res)) {
                   12568:                             my $title = $res->compTitle();
                   12569:                             $title =~ s/\W+/_/g;
                   12570:                             if ($title ne '') {
1.1075.2.48  raeburn  12571:                                 if (($pc > 1) && (length($title) > 12)) {
                   12572:                                     $title = substr($title,0,12);
                   12573:                                 }
1.1015    raeburn  12574:                                 push(@pathitems,$title);
                   12575:                             }
                   12576:                         }
                   12577:                     }
                   12578:                 }
                   12579:                 my $maptitle = $mapres->compTitle();
                   12580:                 $maptitle =~ s/\W+/_/g;
                   12581:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  12582:                     if (length($maptitle) > 12) {
                   12583:                         $maptitle = substr($maptitle,0,12);
                   12584:                     }
1.1015    raeburn  12585:                     push(@pathitems,$maptitle);
                   12586:                 }
                   12587:                 unless ($env{'request.state'} eq 'construct') {
                   12588:                     my $res = $navmap->getBySymb($symb);
                   12589:                     if (ref($res)) {
                   12590:                         my $partlist = $res->parts();
                   12591:                         my $totaluploads = 0;
                   12592:                         if (ref($partlist) eq 'ARRAY') {
                   12593:                             foreach my $part (@{$partlist}) {
                   12594:                                 my @types = $res->responseType($part);
                   12595:                                 my @ids = $res->responseIds($part);
                   12596:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   12597:                                     if ($types[$i] eq 'essay') {
                   12598:                                         my $partid = $part.'_'.$ids[$i];
                   12599:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   12600:                                             $totaluploads ++;
                   12601:                                         }
                   12602:                                     }
                   12603:                                 }
                   12604:                             }
                   12605:                             if ($totaluploads > 1) {
                   12606:                                 $multiresp = 1;
                   12607:                             }
                   12608:                         }
                   12609:                     }
                   12610:                 }
                   12611:             } else {
                   12612:                 return;
                   12613:             }
                   12614:         } else {
                   12615:             return;
                   12616:         }
                   12617:         my $restitle=&Apache::lonnet::gettitle($symb);
                   12618:         $restitle =~ s/\W+/_/g;
                   12619:         if ($restitle eq '') {
                   12620:             $restitle = ($resurl =~ m{/[^/]+$});
                   12621:             if ($restitle eq '') {
                   12622:                 $restitle = time;
                   12623:             }
                   12624:         }
1.1075.2.48  raeburn  12625:         if (length($restitle) > 12) {
                   12626:             $restitle = substr($restitle,0,12);
                   12627:         }
1.1015    raeburn  12628:         push(@pathitems,$restitle);
                   12629:         $path .= join('/',@pathitems);
                   12630:     }
                   12631:     return ($path,$multiresp);
                   12632: }
                   12633: 
                   12634: =pod
                   12635: 
1.464     albertel 12636: =back
1.41      ng       12637: 
1.112     bowersj2 12638: =head1 CSV Upload/Handling functions
1.38      albertel 12639: 
1.41      ng       12640: =over 4
                   12641: 
1.648     raeburn  12642: =item * &upfile_store($r)
1.41      ng       12643: 
                   12644: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 12645: needs $env{'form.upfile'}
1.41      ng       12646: returns $datatoken to be put into hidden field
                   12647: 
                   12648: =cut
1.31      albertel 12649: 
                   12650: sub upfile_store {
                   12651:     my $r=shift;
1.258     albertel 12652:     $env{'form.upfile'}=~s/\r/\n/gs;
                   12653:     $env{'form.upfile'}=~s/\f/\n/gs;
                   12654:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   12655:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 12656: 
1.258     albertel 12657:     my $datatoken=$env{'user.name'}.'_'.$env{'user.domain'}.
                   12658: 	'_enroll_'.$env{'request.course.id'}.'_'.time.'_'.$$;
1.31      albertel 12659:     {
1.158     raeburn  12660:         my $datafile = $r->dir_config('lonDaemons').
                   12661:                            '/tmp/'.$datatoken.'.tmp';
                   12662:         if ( open(my $fh,">$datafile") ) {
1.258     albertel 12663:             print $fh $env{'form.upfile'};
1.158     raeburn  12664:             close($fh);
                   12665:         }
1.31      albertel 12666:     }
                   12667:     return $datatoken;
                   12668: }
                   12669: 
1.56      matthew  12670: =pod
                   12671: 
1.648     raeburn  12672: =item * &load_tmp_file($r)
1.41      ng       12673: 
                   12674: Load uploaded file from tmp, $r should be the HTTP Request object,
1.258     albertel 12675: needs $env{'form.datatoken'},
                   12676: sets $env{'form.upfile'} to the contents of the file
1.41      ng       12677: 
                   12678: =cut
1.31      albertel 12679: 
                   12680: sub load_tmp_file {
                   12681:     my $r=shift;
                   12682:     my @studentdata=();
                   12683:     {
1.158     raeburn  12684:         my $studentfile = $r->dir_config('lonDaemons').
1.258     albertel 12685:                               '/tmp/'.$env{'form.datatoken'}.'.tmp';
1.158     raeburn  12686:         if ( open(my $fh,"<$studentfile") ) {
                   12687:             @studentdata=<$fh>;
                   12688:             close($fh);
                   12689:         }
1.31      albertel 12690:     }
1.258     albertel 12691:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 12692: }
                   12693: 
1.56      matthew  12694: =pod
                   12695: 
1.648     raeburn  12696: =item * &upfile_record_sep()
1.41      ng       12697: 
                   12698: Separate uploaded file into records
                   12699: returns array of records,
1.258     albertel 12700: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       12701: 
                   12702: =cut
1.31      albertel 12703: 
                   12704: sub upfile_record_sep {
1.258     albertel 12705:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 12706:     } else {
1.248     albertel 12707: 	my @records;
1.258     albertel 12708: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 12709: 	    if ($line=~/^\s*$/) { next; }
                   12710: 	    push(@records,$line);
                   12711: 	}
                   12712: 	return @records;
1.31      albertel 12713:     }
                   12714: }
                   12715: 
1.56      matthew  12716: =pod
                   12717: 
1.648     raeburn  12718: =item * &record_sep($record)
1.41      ng       12719: 
1.258     albertel 12720: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       12721: 
                   12722: =cut
                   12723: 
1.263     www      12724: sub takeleft {
                   12725:     my $index=shift;
                   12726:     return substr('0000'.$index,-4,4);
                   12727: }
                   12728: 
1.31      albertel 12729: sub record_sep {
                   12730:     my $record=shift;
                   12731:     my %components=();
1.258     albertel 12732:     if ($env{'form.upfiletype'} eq 'xml') {
                   12733:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 12734:         my $i=0;
1.356     albertel 12735:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 12736:             $field=~s/^(\"|\')//;
                   12737:             $field=~s/(\"|\')$//;
1.263     www      12738:             $components{&takeleft($i)}=$field;
1.31      albertel 12739:             $i++;
                   12740:         }
1.258     albertel 12741:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 12742:         my $i=0;
1.356     albertel 12743:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 12744:             $field=~s/^(\"|\')//;
                   12745:             $field=~s/(\"|\')$//;
1.263     www      12746:             $components{&takeleft($i)}=$field;
1.31      albertel 12747:             $i++;
                   12748:         }
                   12749:     } else {
1.561     www      12750:         my $separator=',';
1.480     banghart 12751:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      12752:             $separator=';';
1.480     banghart 12753:         }
1.31      albertel 12754:         my $i=0;
1.561     www      12755: # the character we are looking for to indicate the end of a quote or a record 
                   12756:         my $looking_for=$separator;
                   12757: # do not add the characters to the fields
                   12758:         my $ignore=0;
                   12759: # we just encountered a separator (or the beginning of the record)
                   12760:         my $just_found_separator=1;
                   12761: # store the field we are working on here
                   12762:         my $field='';
                   12763: # work our way through all characters in record
                   12764:         foreach my $character ($record=~/(.)/g) {
                   12765:             if ($character eq $looking_for) {
                   12766:                if ($character ne $separator) {
                   12767: # Found the end of a quote, again looking for separator
                   12768:                   $looking_for=$separator;
                   12769:                   $ignore=1;
                   12770:                } else {
                   12771: # Found a separator, store away what we got
                   12772:                   $components{&takeleft($i)}=$field;
                   12773: 	          $i++;
                   12774:                   $just_found_separator=1;
                   12775:                   $ignore=0;
                   12776:                   $field='';
                   12777:                }
                   12778:                next;
                   12779:             }
                   12780: # single or double quotation marks after a separator indicate beginning of a quote
                   12781: # we are now looking for the end of the quote and need to ignore separators
                   12782:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   12783:                $looking_for=$character;
                   12784:                next;
                   12785:             }
                   12786: # ignore would be true after we reached the end of a quote
                   12787:             if ($ignore) { next; }
                   12788:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   12789:             $field.=$character;
                   12790:             $just_found_separator=0; 
1.31      albertel 12791:         }
1.561     www      12792: # catch the very last entry, since we never encountered the separator
                   12793:         $components{&takeleft($i)}=$field;
1.31      albertel 12794:     }
                   12795:     return %components;
                   12796: }
                   12797: 
1.144     matthew  12798: ######################################################
                   12799: ######################################################
                   12800: 
1.56      matthew  12801: =pod
                   12802: 
1.648     raeburn  12803: =item * &upfile_select_html()
1.41      ng       12804: 
1.144     matthew  12805: Return HTML code to select a file from the users machine and specify 
                   12806: the file type.
1.41      ng       12807: 
                   12808: =cut
                   12809: 
1.144     matthew  12810: ######################################################
                   12811: ######################################################
1.31      albertel 12812: sub upfile_select_html {
1.144     matthew  12813:     my %Types = (
                   12814:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 12815:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  12816:                  space => &mt('Space separated'),
                   12817:                  tab   => &mt('Tabulator separated'),
                   12818: #                 xml   => &mt('HTML/XML'),
                   12819:                  );
                   12820:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  12821:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  12822:     foreach my $type (sort(keys(%Types))) {
                   12823:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   12824:     }
                   12825:     $Str .= "</select>\n";
                   12826:     return $Str;
1.31      albertel 12827: }
                   12828: 
1.301     albertel 12829: sub get_samples {
                   12830:     my ($records,$toget) = @_;
                   12831:     my @samples=({});
                   12832:     my $got=0;
                   12833:     foreach my $rec (@$records) {
                   12834: 	my %temp = &record_sep($rec);
                   12835: 	if (! grep(/\S/, values(%temp))) { next; }
                   12836: 	if (%temp) {
                   12837: 	    $samples[$got]=\%temp;
                   12838: 	    $got++;
                   12839: 	    if ($got == $toget) { last; }
                   12840: 	}
                   12841:     }
                   12842:     return \@samples;
                   12843: }
                   12844: 
1.144     matthew  12845: ######################################################
                   12846: ######################################################
                   12847: 
1.56      matthew  12848: =pod
                   12849: 
1.648     raeburn  12850: =item * &csv_print_samples($r,$records)
1.41      ng       12851: 
                   12852: Prints a table of sample values from each column uploaded $r is an
                   12853: Apache Request ref, $records is an arrayref from
                   12854: &Apache::loncommon::upfile_record_sep
                   12855: 
                   12856: =cut
                   12857: 
1.144     matthew  12858: ######################################################
                   12859: ######################################################
1.31      albertel 12860: sub csv_print_samples {
                   12861:     my ($r,$records) = @_;
1.662     bisitz   12862:     my $samples = &get_samples($records,5);
1.301     albertel 12863: 
1.594     raeburn  12864:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   12865:               &start_data_table_header_row());
1.356     albertel 12866:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   12867:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  12868:     $r->print(&end_data_table_header_row());
1.301     albertel 12869:     foreach my $hash (@$samples) {
1.594     raeburn  12870: 	$r->print(&start_data_table_row());
1.356     albertel 12871: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 12872: 	    $r->print('<td>');
1.356     albertel 12873: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 12874: 	    $r->print('</td>');
                   12875: 	}
1.594     raeburn  12876: 	$r->print(&end_data_table_row());
1.31      albertel 12877:     }
1.594     raeburn  12878:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 12879: }
                   12880: 
1.144     matthew  12881: ######################################################
                   12882: ######################################################
                   12883: 
1.56      matthew  12884: =pod
                   12885: 
1.648     raeburn  12886: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       12887: 
                   12888: Prints a table to create associations between values and table columns.
1.144     matthew  12889: 
1.41      ng       12890: $r is an Apache Request ref,
                   12891: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  12892: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       12893: 
                   12894: =cut
                   12895: 
1.144     matthew  12896: ######################################################
                   12897: ######################################################
1.31      albertel 12898: sub csv_print_select_table {
                   12899:     my ($r,$records,$d) = @_;
1.301     albertel 12900:     my $i=0;
                   12901:     my $samples = &get_samples($records,1);
1.144     matthew  12902:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  12903: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  12904:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  12905:               '<th>'.&mt('Column').'</th>'.
                   12906:               &end_data_table_header_row()."\n");
1.356     albertel 12907:     foreach my $array_ref (@$d) {
                   12908: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  12909: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 12910: 
1.875     bisitz   12911: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  12912: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 12913: 	$r->print('<option value="none"></option>');
1.356     albertel 12914: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   12915: 	    $r->print('<option value="'.$sample.'"'.
                   12916:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   12917:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 12918: 	}
1.594     raeburn  12919: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 12920: 	$i++;
                   12921:     }
1.594     raeburn  12922:     $r->print(&end_data_table());
1.31      albertel 12923:     $i--;
                   12924:     return $i;
                   12925: }
1.56      matthew  12926: 
1.144     matthew  12927: ######################################################
                   12928: ######################################################
                   12929: 
1.56      matthew  12930: =pod
1.31      albertel 12931: 
1.648     raeburn  12932: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       12933: 
                   12934: Prints a table of sample values from the upload and can make associate samples to internal names.
                   12935: 
                   12936: $r is an Apache Request ref,
                   12937: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   12938: $d is an array of 2 element arrays (internal name, displayed name)
                   12939: 
                   12940: =cut
                   12941: 
1.144     matthew  12942: ######################################################
                   12943: ######################################################
1.31      albertel 12944: sub csv_samples_select_table {
                   12945:     my ($r,$records,$d) = @_;
                   12946:     my $i=0;
1.144     matthew  12947:     #
1.662     bisitz   12948:     my $max_samples = 5;
                   12949:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  12950:     $r->print(&start_data_table().
                   12951:               &start_data_table_header_row().'<th>'.
                   12952:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   12953:               &end_data_table_header_row());
1.301     albertel 12954: 
                   12955:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  12956: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  12957: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 12958: 	foreach my $option (@$d) {
                   12959: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  12960: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 12961:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  12962:                       $display.'</option>');
1.31      albertel 12963: 	}
                   12964: 	$r->print('</select></td><td>');
1.662     bisitz   12965: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 12966: 	    if (defined($samples->[$line]{$key})) { 
                   12967: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   12968: 	    }
                   12969: 	}
1.594     raeburn  12970: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 12971: 	$i++;
                   12972:     }
1.594     raeburn  12973:     $r->print(&end_data_table());
1.31      albertel 12974:     $i--;
                   12975:     return($i);
1.115     matthew  12976: }
                   12977: 
1.144     matthew  12978: ######################################################
                   12979: ######################################################
                   12980: 
1.115     matthew  12981: =pod
                   12982: 
1.648     raeburn  12983: =item * &clean_excel_name($name)
1.115     matthew  12984: 
                   12985: Returns a replacement for $name which does not contain any illegal characters.
                   12986: 
                   12987: =cut
                   12988: 
1.144     matthew  12989: ######################################################
                   12990: ######################################################
1.115     matthew  12991: sub clean_excel_name {
                   12992:     my ($name) = @_;
                   12993:     $name =~ s/[:\*\?\/\\]//g;
                   12994:     if (length($name) > 31) {
                   12995:         $name = substr($name,0,31);
                   12996:     }
                   12997:     return $name;
1.25      albertel 12998: }
1.84      albertel 12999: 
1.85      albertel 13000: =pod
                   13001: 
1.648     raeburn  13002: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13003: 
                   13004: Returns either 1 or undef
                   13005: 
                   13006: 1 if the part is to be hidden, undef if it is to be shown
                   13007: 
                   13008: Arguments are:
                   13009: 
                   13010: $id the id of the part to be checked
                   13011: $symb, optional the symb of the resource to check
                   13012: $udom, optional the domain of the user to check for
                   13013: $uname, optional the username of the user to check for
                   13014: 
                   13015: =cut
1.84      albertel 13016: 
                   13017: sub check_if_partid_hidden {
                   13018:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13019:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13020: 					 $symb,$udom,$uname);
1.141     albertel 13021:     my $truth=1;
                   13022:     #if the string starts with !, then the list is the list to show not hide
                   13023:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13024:     my @hiddenlist=split(/,/,$hiddenparts);
                   13025:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13026: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13027:     }
1.141     albertel 13028:     return !$truth;
1.84      albertel 13029: }
1.127     matthew  13030: 
1.138     matthew  13031: 
                   13032: ############################################################
                   13033: ############################################################
                   13034: 
                   13035: =pod
                   13036: 
1.157     matthew  13037: =back 
                   13038: 
1.138     matthew  13039: =head1 cgi-bin script and graphing routines
                   13040: 
1.157     matthew  13041: =over 4
                   13042: 
1.648     raeburn  13043: =item * &get_cgi_id()
1.138     matthew  13044: 
                   13045: Inputs: none
                   13046: 
                   13047: Returns an id which can be used to pass environment variables
                   13048: to various cgi-bin scripts.  These environment variables will
                   13049: be removed from the users environment after a given time by
                   13050: the routine &Apache::lonnet::transfer_profile_to_env.
                   13051: 
                   13052: =cut
                   13053: 
                   13054: ############################################################
                   13055: ############################################################
1.152     albertel 13056: my $uniq=0;
1.136     matthew  13057: sub get_cgi_id {
1.154     albertel 13058:     $uniq=($uniq+1)%100000;
1.280     albertel 13059:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13060: }
                   13061: 
1.127     matthew  13062: ############################################################
                   13063: ############################################################
                   13064: 
                   13065: =pod
                   13066: 
1.648     raeburn  13067: =item * &DrawBarGraph()
1.127     matthew  13068: 
1.138     matthew  13069: Facilitates the plotting of data in a (stacked) bar graph.
                   13070: Puts plot definition data into the users environment in order for 
                   13071: graph.png to plot it.  Returns an <img> tag for the plot.
                   13072: The bars on the plot are labeled '1','2',...,'n'.
                   13073: 
                   13074: Inputs:
                   13075: 
                   13076: =over 4
                   13077: 
                   13078: =item $Title: string, the title of the plot
                   13079: 
                   13080: =item $xlabel: string, text describing the X-axis of the plot
                   13081: 
                   13082: =item $ylabel: string, text describing the Y-axis of the plot
                   13083: 
                   13084: =item $Max: scalar, the maximum Y value to use in the plot
                   13085: If $Max is < any data point, the graph will not be rendered.
                   13086: 
1.140     matthew  13087: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13088: they are plotted.  If undefined, default values will be used.
                   13089: 
1.178     matthew  13090: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13091: 
1.138     matthew  13092: =item @Values: An array of array references.  Each array reference holds data
                   13093: to be plotted in a stacked bar chart.
                   13094: 
1.239     matthew  13095: =item If the final element of @Values is a hash reference the key/value
                   13096: pairs will be added to the graph definition.
                   13097: 
1.138     matthew  13098: =back
                   13099: 
                   13100: Returns:
                   13101: 
                   13102: An <img> tag which references graph.png and the appropriate identifying
                   13103: information for the plot.
                   13104: 
1.127     matthew  13105: =cut
                   13106: 
                   13107: ############################################################
                   13108: ############################################################
1.134     matthew  13109: sub DrawBarGraph {
1.178     matthew  13110:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13111:     #
                   13112:     if (! defined($colors)) {
                   13113:         $colors = ['#33ff00', 
                   13114:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13115:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13116:                   ]; 
                   13117:     }
1.228     matthew  13118:     my $extra_settings = {};
                   13119:     if (ref($Values[-1]) eq 'HASH') {
                   13120:         $extra_settings = pop(@Values);
                   13121:     }
1.127     matthew  13122:     #
1.136     matthew  13123:     my $identifier = &get_cgi_id();
                   13124:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13125:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13126:         return '';
                   13127:     }
1.225     matthew  13128:     #
                   13129:     my @Labels;
                   13130:     if (defined($labels)) {
                   13131:         @Labels = @$labels;
                   13132:     } else {
                   13133:         for (my $i=0;$i<@{$Values[0]};$i++) {
                   13134:             push (@Labels,$i+1);
                   13135:         }
                   13136:     }
                   13137:     #
1.129     matthew  13138:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13139:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13140:     my %ValuesHash;
                   13141:     my $NumSets=1;
                   13142:     foreach my $array (@Values) {
                   13143:         next if (! ref($array));
1.136     matthew  13144:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13145:             join(',',@$array);
1.129     matthew  13146:     }
1.127     matthew  13147:     #
1.136     matthew  13148:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13149:     if ($NumBars < 3) {
                   13150:         $width = 120+$NumBars*32;
1.220     matthew  13151:         $xskip = 1;
1.225     matthew  13152:         $bar_width = 30;
                   13153:     } elsif ($NumBars < 5) {
                   13154:         $width = 120+$NumBars*20;
                   13155:         $xskip = 1;
                   13156:         $bar_width = 20;
1.220     matthew  13157:     } elsif ($NumBars < 10) {
1.136     matthew  13158:         $width = 120+$NumBars*15;
                   13159:         $xskip = 1;
                   13160:         $bar_width = 15;
                   13161:     } elsif ($NumBars <= 25) {
                   13162:         $width = 120+$NumBars*11;
                   13163:         $xskip = 5;
                   13164:         $bar_width = 8;
                   13165:     } elsif ($NumBars <= 50) {
                   13166:         $width = 120+$NumBars*8;
                   13167:         $xskip = 5;
                   13168:         $bar_width = 4;
                   13169:     } else {
                   13170:         $width = 120+$NumBars*8;
                   13171:         $xskip = 5;
                   13172:         $bar_width = 4;
                   13173:     }
                   13174:     #
1.137     matthew  13175:     $Max = 1 if ($Max < 1);
                   13176:     if ( int($Max) < $Max ) {
                   13177:         $Max++;
                   13178:         $Max = int($Max);
                   13179:     }
1.127     matthew  13180:     $Title  = '' if (! defined($Title));
                   13181:     $xlabel = '' if (! defined($xlabel));
                   13182:     $ylabel = '' if (! defined($ylabel));
1.369     www      13183:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13184:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13185:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13186:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13187:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13188:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13189:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13190:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13191:     $ValuesHash{$id.'.height'}   = $height;
                   13192:     $ValuesHash{$id.'.width'}    = $width;
                   13193:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13194:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13195:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13196:     #
1.228     matthew  13197:     # Deal with other parameters
                   13198:     while (my ($key,$value) = each(%$extra_settings)) {
                   13199:         $ValuesHash{$id.'.'.$key} = $value;
                   13200:     }
                   13201:     #
1.646     raeburn  13202:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13203:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13204: }
                   13205: 
                   13206: ############################################################
                   13207: ############################################################
                   13208: 
                   13209: =pod
                   13210: 
1.648     raeburn  13211: =item * &DrawXYGraph()
1.137     matthew  13212: 
1.138     matthew  13213: Facilitates the plotting of data in an XY graph.
                   13214: Puts plot definition data into the users environment in order for 
                   13215: graph.png to plot it.  Returns an <img> tag for the plot.
                   13216: 
                   13217: Inputs:
                   13218: 
                   13219: =over 4
                   13220: 
                   13221: =item $Title: string, the title of the plot
                   13222: 
                   13223: =item $xlabel: string, text describing the X-axis of the plot
                   13224: 
                   13225: =item $ylabel: string, text describing the Y-axis of the plot
                   13226: 
                   13227: =item $Max: scalar, the maximum Y value to use in the plot
                   13228: If $Max is < any data point, the graph will not be rendered.
                   13229: 
                   13230: =item $colors: Array ref containing the hex color codes for the data to be 
                   13231: plotted in.  If undefined, default values will be used.
                   13232: 
                   13233: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13234: 
                   13235: =item $Ydata: Array ref containing Array refs.  
1.185     www      13236: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13237: 
                   13238: =item %Values: hash indicating or overriding any default values which are 
                   13239: passed to graph.png.  
                   13240: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13241: 
                   13242: =back
                   13243: 
                   13244: Returns:
                   13245: 
                   13246: An <img> tag which references graph.png and the appropriate identifying
                   13247: information for the plot.
                   13248: 
1.137     matthew  13249: =cut
                   13250: 
                   13251: ############################################################
                   13252: ############################################################
                   13253: sub DrawXYGraph {
                   13254:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13255:     #
                   13256:     # Create the identifier for the graph
                   13257:     my $identifier = &get_cgi_id();
                   13258:     my $id = 'cgi.'.$identifier;
                   13259:     #
                   13260:     $Title  = '' if (! defined($Title));
                   13261:     $xlabel = '' if (! defined($xlabel));
                   13262:     $ylabel = '' if (! defined($ylabel));
                   13263:     my %ValuesHash = 
                   13264:         (
1.369     www      13265:          $id.'.title'  => &escape($Title),
                   13266:          $id.'.xlabel' => &escape($xlabel),
                   13267:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13268:          $id.'.y_max_value'=> $Max,
                   13269:          $id.'.labels'     => join(',',@$Xlabels),
                   13270:          $id.'.PlotType'   => 'XY',
                   13271:          );
                   13272:     #
                   13273:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13274:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13275:     }
                   13276:     #
                   13277:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13278:         return '';
                   13279:     }
                   13280:     my $NumSets=1;
1.138     matthew  13281:     foreach my $array (@{$Ydata}){
1.137     matthew  13282:         next if (! ref($array));
                   13283:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13284:     }
1.138     matthew  13285:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13286:     #
                   13287:     # Deal with other parameters
                   13288:     while (my ($key,$value) = each(%Values)) {
                   13289:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13290:     }
                   13291:     #
1.646     raeburn  13292:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13293:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13294: }
                   13295: 
                   13296: ############################################################
                   13297: ############################################################
                   13298: 
                   13299: =pod
                   13300: 
1.648     raeburn  13301: =item * &DrawXYYGraph()
1.138     matthew  13302: 
                   13303: Facilitates the plotting of data in an XY graph with two Y axes.
                   13304: Puts plot definition data into the users environment in order for 
                   13305: graph.png to plot it.  Returns an <img> tag for the plot.
                   13306: 
                   13307: Inputs:
                   13308: 
                   13309: =over 4
                   13310: 
                   13311: =item $Title: string, the title of the plot
                   13312: 
                   13313: =item $xlabel: string, text describing the X-axis of the plot
                   13314: 
                   13315: =item $ylabel: string, text describing the Y-axis of the plot
                   13316: 
                   13317: =item $colors: Array ref containing the hex color codes for the data to be 
                   13318: plotted in.  If undefined, default values will be used.
                   13319: 
                   13320: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13321: 
                   13322: =item $Ydata1: The first data set
                   13323: 
                   13324: =item $Min1: The minimum value of the left Y-axis
                   13325: 
                   13326: =item $Max1: The maximum value of the left Y-axis
                   13327: 
                   13328: =item $Ydata2: The second data set
                   13329: 
                   13330: =item $Min2: The minimum value of the right Y-axis
                   13331: 
                   13332: =item $Max2: The maximum value of the left Y-axis
                   13333: 
                   13334: =item %Values: hash indicating or overriding any default values which are 
                   13335: passed to graph.png.  
                   13336: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13337: 
                   13338: =back
                   13339: 
                   13340: Returns:
                   13341: 
                   13342: An <img> tag which references graph.png and the appropriate identifying
                   13343: information for the plot.
1.136     matthew  13344: 
                   13345: =cut
                   13346: 
                   13347: ############################################################
                   13348: ############################################################
1.137     matthew  13349: sub DrawXYYGraph {
                   13350:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13351:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13352:     #
                   13353:     # Create the identifier for the graph
                   13354:     my $identifier = &get_cgi_id();
                   13355:     my $id = 'cgi.'.$identifier;
                   13356:     #
                   13357:     $Title  = '' if (! defined($Title));
                   13358:     $xlabel = '' if (! defined($xlabel));
                   13359:     $ylabel = '' if (! defined($ylabel));
                   13360:     my %ValuesHash = 
                   13361:         (
1.369     www      13362:          $id.'.title'  => &escape($Title),
                   13363:          $id.'.xlabel' => &escape($xlabel),
                   13364:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13365:          $id.'.labels' => join(',',@$Xlabels),
                   13366:          $id.'.PlotType' => 'XY',
                   13367:          $id.'.NumSets' => 2,
1.137     matthew  13368:          $id.'.two_axes' => 1,
                   13369:          $id.'.y1_max_value' => $Max1,
                   13370:          $id.'.y1_min_value' => $Min1,
                   13371:          $id.'.y2_max_value' => $Max2,
                   13372:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13373:          );
                   13374:     #
1.137     matthew  13375:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13376:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13377:     }
                   13378:     #
                   13379:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13380:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13381:         return '';
                   13382:     }
                   13383:     my $NumSets=1;
1.137     matthew  13384:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13385:         next if (! ref($array));
                   13386:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13387:     }
                   13388:     #
                   13389:     # Deal with other parameters
                   13390:     while (my ($key,$value) = each(%Values)) {
                   13391:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13392:     }
                   13393:     #
1.646     raeburn  13394:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13395:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13396: }
                   13397: 
                   13398: ############################################################
                   13399: ############################################################
                   13400: 
                   13401: =pod
                   13402: 
1.157     matthew  13403: =back 
                   13404: 
1.139     matthew  13405: =head1 Statistics helper routines?  
                   13406: 
                   13407: Bad place for them but what the hell.
                   13408: 
1.157     matthew  13409: =over 4
                   13410: 
1.648     raeburn  13411: =item * &chartlink()
1.139     matthew  13412: 
                   13413: Returns a link to the chart for a specific student.  
                   13414: 
                   13415: Inputs:
                   13416: 
                   13417: =over 4
                   13418: 
                   13419: =item $linktext: The text of the link
                   13420: 
                   13421: =item $sname: The students username
                   13422: 
                   13423: =item $sdomain: The students domain
                   13424: 
                   13425: =back
                   13426: 
1.157     matthew  13427: =back
                   13428: 
1.139     matthew  13429: =cut
                   13430: 
                   13431: ############################################################
                   13432: ############################################################
                   13433: sub chartlink {
                   13434:     my ($linktext, $sname, $sdomain) = @_;
                   13435:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13436:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13437:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13438:        '">'.$linktext.'</a>';
1.153     matthew  13439: }
                   13440: 
                   13441: #######################################################
                   13442: #######################################################
                   13443: 
                   13444: =pod
                   13445: 
                   13446: =head1 Course Environment Routines
1.157     matthew  13447: 
                   13448: =over 4
1.153     matthew  13449: 
1.648     raeburn  13450: =item * &restore_course_settings()
1.153     matthew  13451: 
1.648     raeburn  13452: =item * &store_course_settings()
1.153     matthew  13453: 
                   13454: Restores/Store indicated form parameters from the course environment.
                   13455: Will not overwrite existing values of the form parameters.
                   13456: 
                   13457: Inputs: 
                   13458: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13459: 
                   13460: a hash ref describing the data to be stored.  For example:
                   13461:    
                   13462: %Save_Parameters = ('Status' => 'scalar',
                   13463:     'chartoutputmode' => 'scalar',
                   13464:     'chartoutputdata' => 'scalar',
                   13465:     'Section' => 'array',
1.373     raeburn  13466:     'Group' => 'array',
1.153     matthew  13467:     'StudentData' => 'array',
                   13468:     'Maps' => 'array');
                   13469: 
                   13470: Returns: both routines return nothing
                   13471: 
1.631     raeburn  13472: =back
                   13473: 
1.153     matthew  13474: =cut
                   13475: 
                   13476: #######################################################
                   13477: #######################################################
                   13478: sub store_course_settings {
1.496     albertel 13479:     return &store_settings($env{'request.course.id'},@_);
                   13480: }
                   13481: 
                   13482: sub store_settings {
1.153     matthew  13483:     # save to the environment
                   13484:     # appenv the same items, just to be safe
1.300     albertel 13485:     my $udom  = $env{'user.domain'};
                   13486:     my $uname = $env{'user.name'};
1.496     albertel 13487:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13488:     my %SaveHash;
                   13489:     my %AppHash;
                   13490:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 13491:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 13492:         my $envname = 'environment.'.$basename;
1.258     albertel 13493:         if (exists($env{'form.'.$setting})) {
1.153     matthew  13494:             # Save this value away
                   13495:             if ($type eq 'scalar' &&
1.258     albertel 13496:                 (! exists($env{$envname}) || 
                   13497:                  $env{$envname} ne $env{'form.'.$setting})) {
                   13498:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   13499:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  13500:             } elsif ($type eq 'array') {
                   13501:                 my $stored_form;
1.258     albertel 13502:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  13503:                     $stored_form = join(',',
                   13504:                                         map {
1.369     www      13505:                                             &escape($_);
1.258     albertel 13506:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  13507:                 } else {
                   13508:                     $stored_form = 
1.369     www      13509:                         &escape($env{'form.'.$setting});
1.153     matthew  13510:                 }
                   13511:                 # Determine if the array contents are the same.
1.258     albertel 13512:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  13513:                     $SaveHash{$basename} = $stored_form;
                   13514:                     $AppHash{$envname}   = $stored_form;
                   13515:                 }
                   13516:             }
                   13517:         }
                   13518:     }
                   13519:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 13520:                                           $udom,$uname);
1.153     matthew  13521:     if ($put_result !~ /^(ok|delayed)/) {
                   13522:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   13523:                                  'got error:'.$put_result);
                   13524:     }
                   13525:     # Make sure these settings stick around in this session, too
1.646     raeburn  13526:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  13527:     return;
                   13528: }
                   13529: 
                   13530: sub restore_course_settings {
1.499     albertel 13531:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 13532: }
                   13533: 
                   13534: sub restore_settings {
                   13535:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  13536:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 13537:         next if (exists($env{'form.'.$setting}));
1.496     albertel 13538:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  13539:             '.'.$setting;
1.258     albertel 13540:         if (exists($env{$envname})) {
1.153     matthew  13541:             if ($type eq 'scalar') {
1.258     albertel 13542:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  13543:             } elsif ($type eq 'array') {
1.258     albertel 13544:                 $env{'form.'.$setting} = [ 
1.153     matthew  13545:                                            map { 
1.369     www      13546:                                                &unescape($_); 
1.258     albertel 13547:                                            } split(',',$env{$envname})
1.153     matthew  13548:                                            ];
                   13549:             }
                   13550:         }
                   13551:     }
1.127     matthew  13552: }
                   13553: 
1.618     raeburn  13554: #######################################################
                   13555: #######################################################
                   13556: 
                   13557: =pod
                   13558: 
                   13559: =head1 Domain E-mail Routines  
                   13560: 
                   13561: =over 4
                   13562: 
1.648     raeburn  13563: =item * &build_recipient_list()
1.618     raeburn  13564: 
1.1075.2.44  raeburn  13565: Build recipient lists for following types of e-mail:
1.766     raeburn  13566: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  13567: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   13568: module change checking, student/employee ID conflict checks, as
                   13569: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   13570: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  13571: 
                   13572: Inputs:
1.1075.2.44  raeburn  13573: defmail (scalar - email address of default recipient),
                   13574: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   13575: requestsmail, updatesmail, or idconflictsmail).
                   13576: 
1.619     raeburn  13577: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  13578: 
                   13579: origmail (scalar - email address of recipient from loncapa.conf,
                   13580: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  13581: 
1.655     raeburn  13582: Returns: comma separated list of addresses to which to send e-mail.
                   13583: 
                   13584: =back
1.618     raeburn  13585: 
                   13586: =cut
                   13587: 
                   13588: ############################################################
                   13589: ############################################################
                   13590: sub build_recipient_list {
1.619     raeburn  13591:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  13592:     my @recipients;
                   13593:     my $otheremails;
                   13594:     my %domconfig =
                   13595:          &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
                   13596:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  13597:         if (exists($domconfig{'contacts'}{$mailing})) {
                   13598:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   13599:                 my @contacts = ('adminemail','supportemail');
                   13600:                 foreach my $item (@contacts) {
                   13601:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   13602:                         my $addr = $domconfig{'contacts'}{$item}; 
                   13603:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13604:                             push(@recipients,$addr);
                   13605:                         }
1.619     raeburn  13606:                     }
1.766     raeburn  13607:                     $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
1.618     raeburn  13608:                 }
                   13609:             }
1.766     raeburn  13610:         } elsif ($origmail ne '') {
                   13611:             push(@recipients,$origmail);
1.618     raeburn  13612:         }
1.619     raeburn  13613:     } elsif ($origmail ne '') {
                   13614:         push(@recipients,$origmail);
1.618     raeburn  13615:     }
1.688     raeburn  13616:     if (defined($defmail)) {
                   13617:         if ($defmail ne '') {
                   13618:             push(@recipients,$defmail);
                   13619:         }
1.618     raeburn  13620:     }
                   13621:     if ($otheremails) {
1.619     raeburn  13622:         my @others;
                   13623:         if ($otheremails =~ /,/) {
                   13624:             @others = split(/,/,$otheremails);
1.618     raeburn  13625:         } else {
1.619     raeburn  13626:             push(@others,$otheremails);
                   13627:         }
                   13628:         foreach my $addr (@others) {
                   13629:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   13630:                 push(@recipients,$addr);
                   13631:             }
1.618     raeburn  13632:         }
                   13633:     }
1.619     raeburn  13634:     my $recipientlist = join(',',@recipients); 
1.618     raeburn  13635:     return $recipientlist;
                   13636: }
                   13637: 
1.127     matthew  13638: ############################################################
                   13639: ############################################################
1.154     albertel 13640: 
1.655     raeburn  13641: =pod
                   13642: 
                   13643: =head1 Course Catalog Routines
                   13644: 
                   13645: =over 4
                   13646: 
                   13647: =item * &gather_categories()
                   13648: 
                   13649: Converts category definitions - keys of categories hash stored in  
                   13650: coursecategories in configuration.db on the primary library server in a 
                   13651: domain - to an array.  Also generates javascript and idx hash used to 
                   13652: generate Domain Coordinator interface for editing Course Categories.
                   13653: 
                   13654: Inputs:
1.663     raeburn  13655: 
1.655     raeburn  13656: categories (reference to hash of category definitions).
1.663     raeburn  13657: 
1.655     raeburn  13658: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13659:       categories and subcategories).
1.663     raeburn  13660: 
1.655     raeburn  13661: idx (reference to hash of counters used in Domain Coordinator interface for 
                   13662:       editing Course Categories).
1.663     raeburn  13663: 
1.655     raeburn  13664: jsarray (reference to array of categories used to create Javascript arrays for
                   13665:          Domain Coordinator interface for editing Course Categories).
                   13666: 
                   13667: Returns: nothing
                   13668: 
                   13669: Side effects: populates cats, idx and jsarray. 
                   13670: 
                   13671: =cut
                   13672: 
                   13673: sub gather_categories {
                   13674:     my ($categories,$cats,$idx,$jsarray) = @_;
                   13675:     my %counters;
                   13676:     my $num = 0;
                   13677:     foreach my $item (keys(%{$categories})) {
                   13678:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   13679:         if ($container eq '' && $depth == 0) {
                   13680:             $cats->[$depth][$categories->{$item}] = $cat;
                   13681:         } else {
                   13682:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   13683:         }
                   13684:         my ($escitem,$tail) = split(/:/,$item,2);
                   13685:         if ($counters{$tail} eq '') {
                   13686:             $counters{$tail} = $num;
                   13687:             $num ++;
                   13688:         }
                   13689:         if (ref($idx) eq 'HASH') {
                   13690:             $idx->{$item} = $counters{$tail};
                   13691:         }
                   13692:         if (ref($jsarray) eq 'ARRAY') {
                   13693:             push(@{$jsarray->[$counters{$tail}]},$item);
                   13694:         }
                   13695:     }
                   13696:     return;
                   13697: }
                   13698: 
                   13699: =pod
                   13700: 
                   13701: =item * &extract_categories()
                   13702: 
                   13703: Used to generate breadcrumb trails for course categories.
                   13704: 
                   13705: Inputs:
1.663     raeburn  13706: 
1.655     raeburn  13707: categories (reference to hash of category definitions).
1.663     raeburn  13708: 
1.655     raeburn  13709: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13710:       categories and subcategories).
1.663     raeburn  13711: 
1.655     raeburn  13712: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  13713: 
1.655     raeburn  13714: allitems (reference to hash - key is category key 
                   13715:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13716: 
1.655     raeburn  13717: idx (reference to hash of counters used in Domain Coordinator interface for
                   13718:       editing Course Categories).
1.663     raeburn  13719: 
1.655     raeburn  13720: jsarray (reference to array of categories used to create Javascript arrays for
                   13721:          Domain Coordinator interface for editing Course Categories).
                   13722: 
1.665     raeburn  13723: subcats (reference to hash of arrays containing all subcategories within each 
                   13724:          category, -recursive)
                   13725: 
1.655     raeburn  13726: Returns: nothing
                   13727: 
                   13728: Side effects: populates trails and allitems hash references.
                   13729: 
                   13730: =cut
                   13731: 
                   13732: sub extract_categories {
1.665     raeburn  13733:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats) = @_;
1.655     raeburn  13734:     if (ref($categories) eq 'HASH') {
                   13735:         &gather_categories($categories,$cats,$idx,$jsarray);
                   13736:         if (ref($cats->[0]) eq 'ARRAY') {
                   13737:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   13738:                 my $name = $cats->[0][$i];
                   13739:                 my $item = &escape($name).'::0';
                   13740:                 my $trailstr;
                   13741:                 if ($name eq 'instcode') {
                   13742:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  13743:                 } elsif ($name eq 'communities') {
                   13744:                     $trailstr = &mt('Communities');
1.655     raeburn  13745:                 } else {
                   13746:                     $trailstr = $name;
                   13747:                 }
                   13748:                 if ($allitems->{$item} eq '') {
                   13749:                     push(@{$trails},$trailstr);
                   13750:                     $allitems->{$item} = scalar(@{$trails})-1;
                   13751:                 }
                   13752:                 my @parents = ($name);
                   13753:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   13754:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   13755:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  13756:                         if (ref($subcats) eq 'HASH') {
                   13757:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   13758:                         }
                   13759:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats);
                   13760:                     }
                   13761:                 } else {
                   13762:                     if (ref($subcats) eq 'HASH') {
                   13763:                         $subcats->{$item} = [];
1.655     raeburn  13764:                     }
                   13765:                 }
                   13766:             }
                   13767:         }
                   13768:     }
                   13769:     return;
                   13770: }
                   13771: 
                   13772: =pod
                   13773: 
1.1075.2.56  raeburn  13774: =item * &recurse_categories()
1.655     raeburn  13775: 
                   13776: Recursively used to generate breadcrumb trails for course categories.
                   13777: 
                   13778: Inputs:
1.663     raeburn  13779: 
1.655     raeburn  13780: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   13781:       categories and subcategories).
1.663     raeburn  13782: 
1.655     raeburn  13783: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  13784: 
                   13785: category (current course category, for which breadcrumb trail is being generated).
                   13786: 
                   13787: trails (reference to array of breadcrumb trails for each category).
                   13788: 
1.655     raeburn  13789: allitems (reference to hash - key is category key
                   13790:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  13791: 
1.655     raeburn  13792: parents (array containing containers directories for current category, 
                   13793:          back to top level). 
                   13794: 
                   13795: Returns: nothing
                   13796: 
                   13797: Side effects: populates trails and allitems hash references
                   13798: 
                   13799: =cut
                   13800: 
                   13801: sub recurse_categories {
1.665     raeburn  13802:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats) = @_;
1.655     raeburn  13803:     my $shallower = $depth - 1;
                   13804:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   13805:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   13806:             my $name = $cats->[$depth]{$category}[$k];
                   13807:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13808:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13809:             if ($allitems->{$item} eq '') {
                   13810:                 push(@{$trails},$trailstr);
                   13811:                 $allitems->{$item} = scalar(@{$trails})-1;
                   13812:             }
                   13813:             my $deeper = $depth+1;
                   13814:             push(@{$parents},$category);
1.665     raeburn  13815:             if (ref($subcats) eq 'HASH') {
                   13816:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   13817:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   13818:                     my $higher;
                   13819:                     if ($j > 0) {
                   13820:                         $higher = &escape($parents->[$j]).':'.
                   13821:                                   &escape($parents->[$j-1]).':'.$j;
                   13822:                     } else {
                   13823:                         $higher = &escape($parents->[$j]).'::'.$j;
                   13824:                     }
                   13825:                     push(@{$subcats->{$higher}},$subcat);
                   13826:                 }
                   13827:             }
                   13828:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
                   13829:                                 $subcats);
1.655     raeburn  13830:             pop(@{$parents});
                   13831:         }
                   13832:     } else {
                   13833:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   13834:         my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   13835:         if ($allitems->{$item} eq '') {
                   13836:             push(@{$trails},$trailstr);
                   13837:             $allitems->{$item} = scalar(@{$trails})-1;
                   13838:         }
                   13839:     }
                   13840:     return;
                   13841: }
                   13842: 
1.663     raeburn  13843: =pod
                   13844: 
1.1075.2.56  raeburn  13845: =item * &assign_categories_table()
1.663     raeburn  13846: 
                   13847: Create a datatable for display of hierarchical categories in a domain,
                   13848: with checkboxes to allow a course to be categorized. 
                   13849: 
                   13850: Inputs:
                   13851: 
                   13852: cathash - reference to hash of categories defined for the domain (from
                   13853:           configuration.db)
                   13854: 
                   13855: currcat - scalar with an & separated list of categories assigned to a course. 
                   13856: 
1.919     raeburn  13857: type    - scalar contains course type (Course or Community).
                   13858: 
1.663     raeburn  13859: Returns: $output (markup to be displayed) 
                   13860: 
                   13861: =cut
                   13862: 
                   13863: sub assign_categories_table {
1.919     raeburn  13864:     my ($cathash,$currcat,$type) = @_;
1.663     raeburn  13865:     my $output;
                   13866:     if (ref($cathash) eq 'HASH') {
                   13867:         my (@cats,@trails,%allitems,%idx,@jsarray,@path,$maxdepth);
                   13868:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray);
                   13869:         $maxdepth = scalar(@cats);
                   13870:         if (@cats > 0) {
                   13871:             my $itemcount = 0;
                   13872:             if (ref($cats[0]) eq 'ARRAY') {
                   13873:                 my @currcategories;
                   13874:                 if ($currcat ne '') {
                   13875:                     @currcategories = split('&',$currcat);
                   13876:                 }
1.919     raeburn  13877:                 my $table;
1.663     raeburn  13878:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   13879:                     my $parent = $cats[0][$i];
1.919     raeburn  13880:                     next if ($parent eq 'instcode');
                   13881:                     if ($type eq 'Community') {
                   13882:                         next unless ($parent eq 'communities');
                   13883:                     } else {
                   13884:                         next if ($parent eq 'communities');
                   13885:                     }
1.663     raeburn  13886:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   13887:                     my $item = &escape($parent).'::0';
                   13888:                     my $checked = '';
                   13889:                     if (@currcategories > 0) {
                   13890:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   13891:                             $checked = ' checked="checked"';
1.663     raeburn  13892:                         }
                   13893:                     }
1.919     raeburn  13894:                     my $parent_title = $parent;
                   13895:                     if ($parent eq 'communities') {
                   13896:                         $parent_title = &mt('Communities');
                   13897:                     }
                   13898:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   13899:                               '<input type="checkbox" name="usecategory" value="'.
                   13900:                               $item.'"'.$checked.' />'.$parent_title.'</span>'.
                   13901:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  13902:                     my $depth = 1;
                   13903:                     push(@path,$parent);
1.919     raeburn  13904:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories);
1.663     raeburn  13905:                     pop(@path);
1.919     raeburn  13906:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  13907:                     $itemcount ++;
                   13908:                 }
1.919     raeburn  13909:                 if ($itemcount) {
                   13910:                     $output = &Apache::loncommon::start_data_table().
                   13911:                               $table.
                   13912:                               &Apache::loncommon::end_data_table();
                   13913:                 }
1.663     raeburn  13914:             }
                   13915:         }
                   13916:     }
                   13917:     return $output;
                   13918: }
                   13919: 
                   13920: =pod
                   13921: 
1.1075.2.56  raeburn  13922: =item * &assign_category_rows()
1.663     raeburn  13923: 
                   13924: Create a datatable row for display of nested categories in a domain,
                   13925: with checkboxes to allow a course to be categorized,called recursively.
                   13926: 
                   13927: Inputs:
                   13928: 
                   13929: itemcount - track row number for alternating colors
                   13930: 
                   13931: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   13932:       categories and subcategories.
                   13933: 
                   13934: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   13935: 
                   13936: parent - parent of current category item
                   13937: 
                   13938: path - Array containing all categories back up through the hierarchy from the
                   13939:        current category to the top level.
                   13940: 
                   13941: currcategories - reference to array of current categories assigned to the course
                   13942: 
                   13943: Returns: $output (markup to be displayed).
                   13944: 
                   13945: =cut
                   13946: 
                   13947: sub assign_category_rows {
                   13948:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories) = @_;
                   13949:     my ($text,$name,$item,$chgstr);
                   13950:     if (ref($cats) eq 'ARRAY') {
                   13951:         my $maxdepth = scalar(@{$cats});
                   13952:         if (ref($cats->[$depth]) eq 'HASH') {
                   13953:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   13954:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   13955:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  13956:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  13957:                 for (my $j=0; $j<$numchildren; $j++) {
                   13958:                     $name = $cats->[$depth]{$parent}[$j];
                   13959:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   13960:                     my $deeper = $depth+1;
                   13961:                     my $checked = '';
                   13962:                     if (ref($currcategories) eq 'ARRAY') {
                   13963:                         if (@{$currcategories} > 0) {
                   13964:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   13965:                                 $checked = ' checked="checked"';
1.663     raeburn  13966:                             }
                   13967:                         }
                   13968:                     }
1.664     raeburn  13969:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   13970:                              '<input type="checkbox" name="usecategory" value="'.
1.675     raeburn  13971:                              $item.'"'.$checked.' />'.$name.'</label></span>'.
                   13972:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   13973:                              '</td><td>';
1.663     raeburn  13974:                     if (ref($path) eq 'ARRAY') {
                   13975:                         push(@{$path},$name);
                   13976:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories);
                   13977:                         pop(@{$path});
                   13978:                     }
                   13979:                     $text .= '</td></tr>';
                   13980:                 }
                   13981:                 $text .= '</table></td>';
                   13982:             }
                   13983:         }
                   13984:     }
                   13985:     return $text;
                   13986: }
                   13987: 
1.1075.2.69  raeburn  13988: =pod
                   13989: 
                   13990: =back
                   13991: 
                   13992: =cut
                   13993: 
1.655     raeburn  13994: ############################################################
                   13995: ############################################################
                   13996: 
                   13997: 
1.443     albertel 13998: sub commit_customrole {
1.664     raeburn  13999:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14000:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14001:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14002:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14003:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14004:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14005:                  '</b><br />';
                   14006:     return $output;
                   14007: }
                   14008: 
                   14009: sub commit_standardrole {
1.1075.2.31  raeburn  14010:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14011:     my ($output,$logmsg,$linefeed);
                   14012:     if ($context eq 'auto') {
                   14013:         $linefeed = "\n";
                   14014:     } else {
                   14015:         $linefeed = "<br />\n";
                   14016:     }  
1.443     albertel 14017:     if ($three eq 'st') {
1.541     raeburn  14018:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14019:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14020:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14021:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14022:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14023:         } else {
1.541     raeburn  14024:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14025:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14026:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14027:             if ($context eq 'auto') {
                   14028:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14029:             } else {
                   14030:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14031:                &mt('Add to classlist').': <b>ok</b>';
                   14032:             }
                   14033:             $output .= $linefeed;
1.443     albertel 14034:         }
                   14035:     } else {
                   14036:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14037:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14038:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14039:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14040:         if ($context eq 'auto') {
                   14041:             $output .= $result.$linefeed;
                   14042:         } else {
                   14043:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14044:         }
1.443     albertel 14045:     }
                   14046:     return $output;
                   14047: }
                   14048: 
                   14049: sub commit_studentrole {
1.1075.2.31  raeburn  14050:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14051:         $credits) = @_;
1.626     raeburn  14052:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14053:     if ($context eq 'auto') {
                   14054:         $linefeed = "\n";
                   14055:     } else {
                   14056:         $linefeed = '<br />'."\n";
                   14057:     }
1.443     albertel 14058:     if (defined($one) && defined($two)) {
                   14059:         my $cid=$one.'_'.$two;
                   14060:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14061:         my $secchange = 0;
                   14062:         my $expire_role_result;
                   14063:         my $modify_section_result;
1.628     raeburn  14064:         if ($oldsec ne '-1') { 
                   14065:             if ($oldsec ne $sec) {
1.443     albertel 14066:                 $secchange = 1;
1.628     raeburn  14067:                 my $now = time;
1.443     albertel 14068:                 my $uurl='/'.$cid;
                   14069:                 $uurl=~s/\_/\//g;
                   14070:                 if ($oldsec) {
                   14071:                     $uurl.='/'.$oldsec;
                   14072:                 }
1.626     raeburn  14073:                 $oldsecurl = $uurl;
1.628     raeburn  14074:                 $expire_role_result = 
1.652     raeburn  14075:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14076:                 if ($env{'request.course.sec'} ne '') { 
                   14077:                     if ($expire_role_result eq 'refused') {
                   14078:                         my @roles = ('st');
                   14079:                         my @statuses = ('previous');
                   14080:                         my @roledoms = ($one);
                   14081:                         my $withsec = 1;
                   14082:                         my %roleshash = 
                   14083:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14084:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14085:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14086:                             my ($oldstart,$oldend) = 
                   14087:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14088:                             if ($oldend > 0 && $oldend <= $now) {
                   14089:                                 $expire_role_result = 'ok';
                   14090:                             }
                   14091:                         }
                   14092:                     }
                   14093:                 }
1.443     albertel 14094:                 $result = $expire_role_result;
                   14095:             }
                   14096:         }
                   14097:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14098:             $modify_section_result = 
                   14099:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14100:                                                            undef,undef,undef,$sec,
                   14101:                                                            $end,$start,'','',$cid,
                   14102:                                                            '',$context,$credits);
1.443     albertel 14103:             if ($modify_section_result =~ /^ok/) {
                   14104:                 if ($secchange == 1) {
1.628     raeburn  14105:                     if ($sec eq '') {
                   14106:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14107:                     } else {
                   14108:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14109:                     }
1.443     albertel 14110:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14111:                     if ($sec eq '') {
                   14112:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14113:                     } else {
                   14114:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14115:                     }
1.443     albertel 14116:                 } else {
1.628     raeburn  14117:                     if ($sec eq '') {
                   14118:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14119:                     } else {
                   14120:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14121:                     }
1.443     albertel 14122:                 }
                   14123:             } else {
1.628     raeburn  14124:                 if ($secchange) {       
                   14125:                     $$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;
                   14126:                 } else {
                   14127:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14128:                 }
1.443     albertel 14129:             }
                   14130:             $result = $modify_section_result;
                   14131:         } elsif ($secchange == 1) {
1.628     raeburn  14132:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14133:                 $$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  14134:             } else {
                   14135:                 $$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;
                   14136:             }
1.626     raeburn  14137:             if ($expire_role_result eq 'refused') {
                   14138:                 my $newsecurl = '/'.$cid;
                   14139:                 $newsecurl =~ s/\_/\//g;
                   14140:                 if ($sec ne '') {
                   14141:                     $newsecurl.='/'.$sec;
                   14142:                 }
                   14143:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14144:                     if ($sec eq '') {
                   14145:                         $$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;
                   14146:                     } else {
                   14147:                         $$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;
                   14148:                     }
                   14149:                 }
                   14150:             }
1.443     albertel 14151:         }
                   14152:     } else {
1.626     raeburn  14153:         $$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 14154:         $result = "error: incomplete course id\n";
                   14155:     }
                   14156:     return $result;
                   14157: }
                   14158: 
1.1075.2.25  raeburn  14159: sub show_role_extent {
                   14160:     my ($scope,$context,$role) = @_;
                   14161:     $scope =~ s{^/}{};
                   14162:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14163:     push(@courseroles,'co');
                   14164:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14165:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14166:         $scope =~ s{/}{_};
                   14167:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14168:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14169:         my ($audom,$auname) = split(/\//,$scope);
                   14170:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14171:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14172:     } else {
                   14173:         $scope =~ s{/$}{};
                   14174:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14175:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14176:     }
                   14177: }
                   14178: 
1.443     albertel 14179: ############################################################
                   14180: ############################################################
                   14181: 
1.566     albertel 14182: sub check_clone {
1.578     raeburn  14183:     my ($args,$linefeed) = @_;
1.566     albertel 14184:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14185:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14186:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14187:     my $clonemsg;
                   14188:     my $can_clone = 0;
1.944     raeburn  14189:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14190:     if ($lctype ne 'community') {
                   14191:         $lctype = 'course';
                   14192:     }
1.566     albertel 14193:     if ($clonehome eq 'no_host') {
1.944     raeburn  14194:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14195:             $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'});
                   14196:         } else {
                   14197:             $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'});
                   14198:         }     
1.566     albertel 14199:     } else {
                   14200: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14201:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14202:             if ($clonedesc{'type'} ne 'Community') {
                   14203:                  $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'});
                   14204:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14205:             }
                   14206:         }
1.882     raeburn  14207: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) && 
                   14208:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14209: 	    $can_clone = 1;
                   14210: 	} else {
1.1075.2.95  raeburn  14211: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14212: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14213:             if ($clonehash{'cloners'} eq '') {
                   14214:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14215:                 if ($domdefs{'canclone'}) {
                   14216:                     unless ($domdefs{'canclone'} eq 'none') {
                   14217:                         if ($domdefs{'canclone'} eq 'domain') {
                   14218:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14219:                                 $can_clone = 1;
                   14220:                             }
                   14221:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14222:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14223:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14224:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14225:                                 $can_clone = 1;
                   14226:                             }
                   14227:                         }
                   14228:                     }
1.908     raeburn  14229:                 }
1.1075.2.95  raeburn  14230:             } else {
                   14231: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14232:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14233:                     $can_clone = 1;
1.1075.2.95  raeburn  14234:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14235:                     $can_clone = 1;
1.1075.2.96  raeburn  14236:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14237:                     $can_clone = 1;
1.1075.2.95  raeburn  14238:                 }
                   14239:                 unless ($can_clone) {
1.1075.2.96  raeburn  14240:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14241:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14242:                         my (%gotdomdefaults,%gotcodedefaults);
                   14243:                         foreach my $cloner (@cloners) {
                   14244:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14245:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14246:                                 my (%codedefaults,@code_order);
                   14247:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14248:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14249:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14250:                                     }
                   14251:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14252:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14253:                                     }
                   14254:                                 } else {
                   14255:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14256:                                                                             \%codedefaults,
                   14257:                                                                             \@code_order);
                   14258:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14259:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14260:                                 }
                   14261:                                 if (@code_order > 0) {
                   14262:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14263:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14264:                                                                                 $args->{'crscode'})) {
                   14265:                                         $can_clone = 1;
                   14266:                                         last;
                   14267:                                     }
                   14268:                                 }
                   14269:                             }
                   14270:                         }
                   14271:                     }
1.1075.2.96  raeburn  14272:                 }
                   14273:             }
                   14274:             unless ($can_clone) {
                   14275:                 my $ccrole = 'cc';
                   14276:                 if ($args->{'crstype'} eq 'Community') {
                   14277:                     $ccrole = 'co';
                   14278:                 }
                   14279:                 my %roleshash =
                   14280:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14281:                                                   $args->{'ccdomain'},
                   14282:                                                   'userroles',['active'],[$ccrole],
                   14283:                                                   [$args->{'clonedomain'}]);
                   14284:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14285:                     $can_clone = 1;
                   14286:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14287:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14288:                     $can_clone = 1;
1.1075.2.95  raeburn  14289:                 }
                   14290:             }
                   14291:             unless ($can_clone) {
                   14292:                 if ($args->{'crstype'} eq 'Community') {
                   14293:                     $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'});
                   14294:                 } else {
                   14295:                     $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'});
1.578     raeburn  14296: 	        }
1.566     albertel 14297: 	    }
1.578     raeburn  14298:         }
1.566     albertel 14299:     }
                   14300:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14301: }
                   14302: 
1.444     albertel 14303: sub construct_course {
1.1075.2.59  raeburn  14304:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,$cnum,$category,$coderef) = @_;
1.444     albertel 14305:     my $outcome;
1.541     raeburn  14306:     my $linefeed =  '<br />'."\n";
                   14307:     if ($context eq 'auto') {
                   14308:         $linefeed = "\n";
                   14309:     }
1.566     albertel 14310: 
                   14311: #
                   14312: # Are we cloning?
                   14313: #
                   14314:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14315:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14316: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14317: 	if ($context ne 'auto') {
1.578     raeburn  14318:             if ($clonemsg ne '') {
                   14319: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14320:             }
1.566     albertel 14321: 	}
                   14322: 	$outcome .= $clonemsg.$linefeed;
                   14323: 
                   14324:         if (!$can_clone) {
                   14325: 	    return (0,$outcome);
                   14326: 	}
                   14327:     }
                   14328: 
1.444     albertel 14329: #
                   14330: # Open course
                   14331: #
                   14332:     my $crstype = lc($args->{'crstype'});
                   14333:     my %cenv=();
                   14334:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14335:                                              $args->{'cdescr'},
                   14336:                                              $args->{'curl'},
                   14337:                                              $args->{'course_home'},
                   14338:                                              $args->{'nonstandard'},
                   14339:                                              $args->{'crscode'},
                   14340:                                              $args->{'ccuname'}.':'.
                   14341:                                              $args->{'ccdomain'},
1.882     raeburn  14342:                                              $args->{'crstype'},
1.885     raeburn  14343:                                              $cnum,$context,$category);
1.444     albertel 14344: 
                   14345:     # Note: The testing routines depend on this being output; see 
                   14346:     # Utils::Course. This needs to at least be output as a comment
                   14347:     # if anyone ever decides to not show this, and Utils::Course::new
                   14348:     # will need to be suitably modified.
1.541     raeburn  14349:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14350:     if ($$courseid =~ /^error:/) {
                   14351:         return (0,$outcome);
                   14352:     }
                   14353: 
1.444     albertel 14354: #
                   14355: # Check if created correctly
                   14356: #
1.479     albertel 14357:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14358:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14359:     if ($crsuhome eq 'no_host') {
                   14360:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14361:         return (0,$outcome);
                   14362:     }
1.541     raeburn  14363:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14364: 
1.444     albertel 14365: #
1.566     albertel 14366: # Do the cloning
                   14367: #   
                   14368:     if ($can_clone && $cloneid) {
                   14369: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   14370: 	if ($context ne 'auto') {
                   14371: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   14372: 	}
                   14373: 	$outcome .= $clonemsg.$linefeed;
                   14374: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 14375: # Copy all files
1.637     www      14376: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 14377: # Restore URL
1.566     albertel 14378: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 14379: # Restore title
1.566     albertel 14380: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  14381: # Restore creation date, creator and creation context.
                   14382:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   14383:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   14384:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 14385: # Mark as cloned
1.566     albertel 14386: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      14387: # Need to clone grading mode
                   14388:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   14389:         $cenv{'grading'}=$newenv{'grading'};
                   14390: # Do not clone these environment entries
                   14391:         &Apache::lonnet::del('environment',
                   14392:                   ['default_enrollment_start_date',
                   14393:                    'default_enrollment_end_date',
                   14394:                    'question.email',
                   14395:                    'policy.email',
                   14396:                    'comment.email',
                   14397:                    'pch.users.denied',
1.725     raeburn  14398:                    'plc.users.denied',
                   14399:                    'hidefromcat',
1.1075.2.36  raeburn  14400:                    'checkforpriv',
1.1075.2.59  raeburn  14401:                    'categories',
                   14402:                    'internal.uniquecode'],
1.638     www      14403:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  14404:         if ($args->{'textbook'}) {
                   14405:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   14406:         }
1.444     albertel 14407:     }
1.566     albertel 14408: 
1.444     albertel 14409: #
                   14410: # Set environment (will override cloned, if existing)
                   14411: #
                   14412:     my @sections = ();
                   14413:     my @xlists = ();
                   14414:     if ($args->{'crstype'}) {
                   14415:         $cenv{'type'}=$args->{'crstype'};
                   14416:     }
                   14417:     if ($args->{'crsid'}) {
                   14418:         $cenv{'courseid'}=$args->{'crsid'};
                   14419:     }
                   14420:     if ($args->{'crscode'}) {
                   14421:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   14422:     }
                   14423:     if ($args->{'crsquota'} ne '') {
                   14424:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   14425:     } else {
                   14426:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   14427:     }
                   14428:     if ($args->{'ccuname'}) {
                   14429:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   14430:                                         ':'.$args->{'ccdomain'};
                   14431:     } else {
                   14432:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   14433:     }
1.1075.2.31  raeburn  14434:     if ($args->{'defaultcredits'}) {
                   14435:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   14436:     }
1.444     albertel 14437:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   14438:     if ($args->{'crssections'}) {
                   14439:         $cenv{'internal.sectionnums'} = '';
                   14440:         if ($args->{'crssections'} =~ m/,/) {
                   14441:             @sections = split/,/,$args->{'crssections'};
                   14442:         } else {
                   14443:             $sections[0] = $args->{'crssections'};
                   14444:         }
                   14445:         if (@sections > 0) {
                   14446:             foreach my $item (@sections) {
                   14447:                 my ($sec,$gp) = split/:/,$item;
                   14448:                 my $class = $args->{'crscode'}.$sec;
                   14449:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   14450:                 $cenv{'internal.sectionnums'} .= $item.',';
                   14451:                 unless ($addcheck eq 'ok') {
                   14452:                     push @badclasses, $class;
                   14453:                 }
                   14454:             }
                   14455:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   14456:         }
                   14457:     }
                   14458: # do not hide course coordinator from staff listing, 
                   14459: # even if privileged
                   14460:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  14461: # add course coordinator's domain to domains to check for privileged users
                   14462: # if different to course domain
                   14463:     if ($$crsudom ne $args->{'ccdomain'}) {
                   14464:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   14465:     }
1.444     albertel 14466: # add crosslistings
                   14467:     if ($args->{'crsxlist'}) {
                   14468:         $cenv{'internal.crosslistings'}='';
                   14469:         if ($args->{'crsxlist'} =~ m/,/) {
                   14470:             @xlists = split/,/,$args->{'crsxlist'};
                   14471:         } else {
                   14472:             $xlists[0] = $args->{'crsxlist'};
                   14473:         }
                   14474:         if (@xlists > 0) {
                   14475:             foreach my $item (@xlists) {
                   14476:                 my ($xl,$gp) = split/:/,$item;
                   14477:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   14478:                 $cenv{'internal.crosslistings'} .= $item.',';
                   14479:                 unless ($addcheck eq 'ok') {
                   14480:                     push @badclasses, $xl;
                   14481:                 }
                   14482:             }
                   14483:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   14484:         }
                   14485:     }
                   14486:     if ($args->{'autoadds'}) {
                   14487:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   14488:     }
                   14489:     if ($args->{'autodrops'}) {
                   14490:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   14491:     }
                   14492: # check for notification of enrollment changes
                   14493:     my @notified = ();
                   14494:     if ($args->{'notify_owner'}) {
                   14495:         if ($args->{'ccuname'} ne '') {
                   14496:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   14497:         }
                   14498:     }
                   14499:     if ($args->{'notify_dc'}) {
                   14500:         if ($uname ne '') { 
1.630     raeburn  14501:             push(@notified,$uname.':'.$udom);
1.444     albertel 14502:         }
                   14503:     }
                   14504:     if (@notified > 0) {
                   14505:         my $notifylist;
                   14506:         if (@notified > 1) {
                   14507:             $notifylist = join(',',@notified);
                   14508:         } else {
                   14509:             $notifylist = $notified[0];
                   14510:         }
                   14511:         $cenv{'internal.notifylist'} = $notifylist;
                   14512:     }
                   14513:     if (@badclasses > 0) {
                   14514:         my %lt=&Apache::lonlocal::texthash(
                   14515:                 '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',
                   14516:                 'dnhr' => 'does not have rights to access enrollment in these classes',
                   14517:                 'adby' => 'as determined by the policies of your institution on access to official classlists'
                   14518:         );
1.541     raeburn  14519:         my $badclass_msg = $cenv{'internal.courseowner'}.') - '.$lt{'dnhr'}.
                   14520:                            ' ('.$lt{'adby'}.')';
                   14521:         if ($context eq 'auto') {
                   14522:             $outcome .= $badclass_msg.$linefeed;
1.566     albertel 14523:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.541     raeburn  14524:             foreach my $item (@badclasses) {
                   14525:                 if ($context eq 'auto') {
                   14526:                     $outcome .= " - $item\n";
                   14527:                 } else {
                   14528:                     $outcome .= "<li>$item</li>\n";
                   14529:                 }
                   14530:             }
                   14531:             if ($context eq 'auto') {
                   14532:                 $outcome .= $linefeed;
                   14533:             } else {
1.566     albertel 14534:                 $outcome .= "</ul><br /><br /></div>\n";
1.541     raeburn  14535:             }
                   14536:         } 
1.444     albertel 14537:     }
                   14538:     if ($args->{'no_end_date'}) {
                   14539:         $args->{'endaccess'} = 0;
                   14540:     }
                   14541:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   14542:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   14543:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   14544:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   14545:     if ($args->{'showphotos'}) {
                   14546:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   14547:     }
                   14548:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   14549:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   14550:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   14551:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  14552:             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'); 
                   14553:             if ($context eq 'auto') {
                   14554:                 $outcome .= $krb_msg;
                   14555:             } else {
1.566     albertel 14556:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  14557:             }
                   14558:             $outcome .= $linefeed;
1.444     albertel 14559:         }
                   14560:     }
                   14561:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   14562:        if ($args->{'setpolicy'}) {
                   14563:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14564:        }
                   14565:        if ($args->{'setcontent'}) {
                   14566:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   14567:        }
                   14568:     }
                   14569:     if ($args->{'reshome'}) {
                   14570: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   14571: 	$cenv{'reshome'}=~s/\/+$/\//;
                   14572:     }
                   14573: #
                   14574: # course has keyed access
                   14575: #
                   14576:     if ($args->{'setkeys'}) {
                   14577:        $cenv{'keyaccess'}='yes';
                   14578:     }
                   14579: # if specified, key authority is not course, but user
                   14580: # only active if keyaccess is yes
                   14581:     if ($args->{'keyauth'}) {
1.487     albertel 14582: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   14583: 	$user = &LONCAPA::clean_username($user);
                   14584: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     14585: 	if ($user ne '' && $domain ne '') {
1.487     albertel 14586: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 14587: 	}
                   14588:     }
                   14589: 
1.1075.2.59  raeburn  14590: #
                   14591: #  generate and store uniquecode (available to course requester), if course should have one.
                   14592: #
                   14593:     if ($args->{'uniquecode'}) {
                   14594:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   14595:         if ($code) {
                   14596:             $cenv{'internal.uniquecode'} = $code;
                   14597:             my %crsinfo =
                   14598:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   14599:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   14600:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   14601:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   14602:             }
                   14603:             if (ref($coderef)) {
                   14604:                 $$coderef = $code;
                   14605:             }
                   14606:         }
                   14607:     }
                   14608: 
1.444     albertel 14609:     if ($args->{'disresdis'}) {
                   14610:         $cenv{'pch.roles.denied'}='st';
                   14611:     }
                   14612:     if ($args->{'disablechat'}) {
                   14613:         $cenv{'plc.roles.denied'}='st';
                   14614:     }
                   14615: 
                   14616:     # Record we've not yet viewed the Course Initialization Helper for this 
                   14617:     # course
                   14618:     $cenv{'course.helper.not.run'} = 1;
                   14619:     #
                   14620:     # Use new Randomseed
                   14621:     #
                   14622:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   14623:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   14624:     #
                   14625:     # The encryption code and receipt prefix for this course
                   14626:     #
                   14627:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   14628:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   14629:     #
                   14630:     # By default, use standard grading
                   14631:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   14632: 
1.541     raeburn  14633:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   14634:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14635: #
                   14636: # Open all assignments
                   14637: #
                   14638:     if ($args->{'openall'}) {
                   14639:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   14640:        my %storecontent = ($storeunder         => time,
                   14641:                            $storeunder.'.type' => 'date_start');
                   14642:        
                   14643:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  14644:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 14645:    }
                   14646: #
                   14647: # Set first page
                   14648: #
                   14649:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   14650: 	    || ($cloneid)) {
1.445     albertel 14651: 	use LONCAPA::map;
1.444     albertel 14652: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 14653: 
                   14654: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   14655:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   14656: 
1.444     albertel 14657:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   14658:         my $title; my $url;
                   14659:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   14660: 	    $title=&mt('Syllabus');
1.444     albertel 14661:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   14662:         } else {
1.963     raeburn  14663:             $title=&mt('Table of Contents');
1.444     albertel 14664:             $url='/adm/navmaps';
                   14665:         }
1.445     albertel 14666: 
                   14667:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   14668: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   14669: 
                   14670: 	if ($errtext) { $fatal=2; }
1.541     raeburn  14671:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 14672:     }
1.566     albertel 14673: 
                   14674:     return (1,$outcome);
1.444     albertel 14675: }
                   14676: 
1.1075.2.59  raeburn  14677: sub make_unique_code {
                   14678:     my ($cdom,$cnum) = @_;
                   14679:     # get lock on uniquecodes db
                   14680:     my $lockhash = {
                   14681:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   14682:                                                   ':'.$env{'user.domain'},
                   14683:                    };
                   14684:     my $tries = 0;
                   14685:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14686:     my ($code,$error);
                   14687: 
                   14688:     while (($gotlock ne 'ok') && ($tries<3)) {
                   14689:         $tries ++;
                   14690:         sleep 1;
                   14691:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   14692:     }
                   14693:     if ($gotlock eq 'ok') {
                   14694:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   14695:         my $gotcode;
                   14696:         my $attempts = 0;
                   14697:         while ((!$gotcode) && ($attempts < 100)) {
                   14698:             $code = &generate_code();
                   14699:             if (!exists($currcodes{$code})) {
                   14700:                 $gotcode = 1;
                   14701:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   14702:                     $error = 'nostore';
                   14703:                 }
                   14704:             }
                   14705:             $attempts ++;
                   14706:         }
                   14707:         my @del_lock = ($cnum."\0".'uniquecodes');
                   14708:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   14709:     } else {
                   14710:         $error = 'nolock';
                   14711:     }
                   14712:     return ($code,$error);
                   14713: }
                   14714: 
                   14715: sub generate_code {
                   14716:     my $code;
                   14717:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   14718:     for (my $i=0; $i<6; $i++) {
                   14719:         my $lettnum = int (rand 2);
                   14720:         my $item = '';
                   14721:         if ($lettnum) {
                   14722:             $item = $letts[int( rand(18) )];
                   14723:         } else {
                   14724:             $item = 1+int( rand(8) );
                   14725:         }
                   14726:         $code .= $item;
                   14727:     }
                   14728:     return $code;
                   14729: }
                   14730: 
1.444     albertel 14731: ############################################################
                   14732: ############################################################
                   14733: 
1.953     droeschl 14734: #SD
                   14735: # only Community and Course, or anything else?
1.378     raeburn  14736: sub course_type {
                   14737:     my ($cid) = @_;
                   14738:     if (!defined($cid)) {
                   14739:         $cid = $env{'request.course.id'};
                   14740:     }
1.404     albertel 14741:     if (defined($env{'course.'.$cid.'.type'})) {
                   14742:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  14743:     } else {
                   14744:         return 'Course';
1.377     raeburn  14745:     }
                   14746: }
1.156     albertel 14747: 
1.406     raeburn  14748: sub group_term {
                   14749:     my $crstype = &course_type();
                   14750:     my %names = (
                   14751:                   'Course' => 'group',
1.865     raeburn  14752:                   'Community' => 'group',
1.406     raeburn  14753:                 );
                   14754:     return $names{$crstype};
                   14755: }
                   14756: 
1.902     raeburn  14757: sub course_types {
1.1075.2.59  raeburn  14758:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  14759:     my %typename = (
                   14760:                          official   => 'Official course',
                   14761:                          unofficial => 'Unofficial course',
                   14762:                          community  => 'Community',
1.1075.2.59  raeburn  14763:                          textbook   => 'Textbook course',
1.902     raeburn  14764:                    );
                   14765:     return (\@types,\%typename);
                   14766: }
                   14767: 
1.156     albertel 14768: sub icon {
                   14769:     my ($file)=@_;
1.505     albertel 14770:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 14771:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 14772:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 14773:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   14774: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   14775: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14776: 	            $curfext.".gif") {
                   14777: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   14778: 		$curfext.".gif";
                   14779: 	}
                   14780:     }
1.249     albertel 14781:     return &lonhttpdurl($iconname);
1.154     albertel 14782: } 
1.84      albertel 14783: 
1.575     albertel 14784: sub lonhttpdurl {
1.692     www      14785: #
                   14786: # Had been used for "small fry" static images on separate port 8080.
                   14787: # Modify here if lightweight http functionality desired again.
                   14788: # Currently eliminated due to increasing firewall issues.
                   14789: #
1.575     albertel 14790:     my ($url)=@_;
1.692     www      14791:     return $url;
1.215     albertel 14792: }
                   14793: 
1.213     albertel 14794: sub connection_aborted {
                   14795:     my ($r)=@_;
                   14796:     $r->print(" ");$r->rflush();
                   14797:     my $c = $r->connection;
                   14798:     return $c->aborted();
                   14799: }
                   14800: 
1.221     foxr     14801: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     14802: #    strings as 'strings'.
                   14803: sub escape_single {
1.221     foxr     14804:     my ($input) = @_;
1.223     albertel 14805:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     14806:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   14807:     return $input;
                   14808: }
1.223     albertel 14809: 
1.222     foxr     14810: #  Same as escape_single, but escape's "'s  This 
                   14811: #  can be used for  "strings"
                   14812: sub escape_double {
                   14813:     my ($input) = @_;
                   14814:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   14815:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   14816:     return $input;
                   14817: }
1.223     albertel 14818:  
1.222     foxr     14819: #   Escapes the last element of a full URL.
                   14820: sub escape_url {
                   14821:     my ($url)   = @_;
1.238     raeburn  14822:     my @urlslices = split(/\//, $url,-1);
1.369     www      14823:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  14824:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     14825: }
1.462     albertel 14826: 
1.820     raeburn  14827: sub compare_arrays {
                   14828:     my ($arrayref1,$arrayref2) = @_;
                   14829:     my (@difference,%count);
                   14830:     @difference = ();
                   14831:     %count = ();
                   14832:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   14833:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   14834:         foreach my $element (keys(%count)) {
                   14835:             if ($count{$element} == 1) {
                   14836:                 push(@difference,$element);
                   14837:             }
                   14838:         }
                   14839:     }
                   14840:     return @difference;
                   14841: }
                   14842: 
1.817     bisitz   14843: # -------------------------------------------------------- Initialize user login
1.462     albertel 14844: sub init_user_environment {
1.463     albertel 14845:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 14846:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   14847: 
                   14848:     my $public=($username eq 'public' && $domain eq 'public');
                   14849: 
                   14850: # See if old ID present, if so, remove
                   14851: 
1.1062    raeburn  14852:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 14853:     my $now=time;
                   14854: 
                   14855:     if ($public) {
                   14856: 	my $max_public=100;
                   14857: 	my $oldest;
                   14858: 	my $oldest_time=0;
                   14859: 	for(my $next=1;$next<=$max_public;$next++) {
                   14860: 	    if (-e $lonids."/publicuser_$next.id") {
                   14861: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   14862: 		if ($mtime<$oldest_time || !$oldest_time) {
                   14863: 		    $oldest_time=$mtime;
                   14864: 		    $oldest=$next;
                   14865: 		}
                   14866: 	    } else {
                   14867: 		$cookie="publicuser_$next";
                   14868: 		last;
                   14869: 	    }
                   14870: 	}
                   14871: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   14872:     } else {
1.463     albertel 14873: 	# if this isn't a robot, kill any existing non-robot sessions
                   14874: 	if (!$args->{'robot'}) {
                   14875: 	    opendir(DIR,$lonids);
                   14876: 	    while ($filename=readdir(DIR)) {
                   14877: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   14878: 		    unlink($lonids.'/'.$filename);
                   14879: 		}
1.462     albertel 14880: 	    }
1.463     albertel 14881: 	    closedir(DIR);
1.1075.2.84  raeburn  14882: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   14883:             my $namespace = 'nohist_courseeditor';
                   14884:             my $lockingkey = 'paste'."\0".'locked_num';
                   14885:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   14886:                                                 $domain,$username);
                   14887:             if (exists($lockhash{$lockingkey})) {
                   14888:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   14889:                 unless ($delresult eq 'ok') {
                   14890:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   14891:                 }
                   14892:             }
1.462     albertel 14893: 	}
                   14894: # Give them a new cookie
1.463     albertel 14895: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      14896: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 14897: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 14898:     
                   14899: # Initialize roles
                   14900: 
1.1062    raeburn  14901: 	($userroles,$firstaccenv,$timerintenv) = 
                   14902:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 14903:     }
                   14904: # ------------------------------------ Check browser type and MathML capability
                   14905: 
1.1075.2.77  raeburn  14906:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   14907:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 14908: 
                   14909: # ------------------------------------------------------------- Get environment
                   14910: 
                   14911:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   14912:     my ($tmp) = keys(%userenv);
                   14913:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   14914:     } else {
                   14915: 	undef(%userenv);
                   14916:     }
                   14917:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   14918: 	$form->{'interface'}=$userenv{'interface'};
                   14919:     }
                   14920:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   14921: 
                   14922: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   14923:     foreach my $option ('interface','localpath','localres') {
                   14924:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 14925:     }
                   14926: # --------------------------------------------------------- Write first profile
                   14927: 
                   14928:     {
                   14929: 	my %initial_env = 
                   14930: 	    ("user.name"          => $username,
                   14931: 	     "user.domain"        => $domain,
                   14932: 	     "user.home"          => $authhost,
                   14933: 	     "browser.type"       => $clientbrowser,
                   14934: 	     "browser.version"    => $clientversion,
                   14935: 	     "browser.mathml"     => $clientmathml,
                   14936: 	     "browser.unicode"    => $clientunicode,
                   14937: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  14938:              "browser.mobile"     => $clientmobile,
                   14939:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  14940:              "browser.osversion"  => $clientosversion,
1.462     albertel 14941: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   14942: 	     "request.course.fn"  => '',
                   14943: 	     "request.course.uri" => '',
                   14944: 	     "request.course.sec" => '',
                   14945: 	     "request.role"       => 'cm',
                   14946: 	     "request.role.adv"   => $env{'user.adv'},
                   14947: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   14948: 
                   14949:         if ($form->{'localpath'}) {
                   14950: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   14951: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   14952:         }
                   14953: 	
                   14954: 	if ($form->{'interface'}) {
                   14955: 	    $form->{'interface'}=~s/\W//gs;
                   14956: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   14957: 	    $env{'browser.interface'}=$form->{'interface'};
                   14958: 	}
                   14959: 
1.1075.2.54  raeburn  14960:         if ($form->{'iptoken'}) {
                   14961:             my $lonhost = $r->dir_config('lonHostID');
                   14962:             $initial_env{"user.noloadbalance"} = $lonhost;
                   14963:             $env{'user.noloadbalance'} = $lonhost;
                   14964:         }
                   14965: 
1.981     raeburn  14966:         my %is_adv = ( is_adv => $env{'user.adv'} );
1.1016    raeburn  14967:         my %domdef;
                   14968:         unless ($domain eq 'public') {
                   14969:             %domdef = &Apache::lonnet::get_domain_defaults($domain);
                   14970:         }
1.980     raeburn  14971: 
1.1075.2.7  raeburn  14972:         foreach my $tool ('aboutme','blog','webdav','portfolio') {
1.724     raeburn  14973:             $userenv{'availabletools.'.$tool} = 
1.980     raeburn  14974:                 &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   14975:                                                   undef,\%userenv,\%domdef,\%is_adv);
1.724     raeburn  14976:         }
                   14977: 
1.1075.2.59  raeburn  14978:         foreach my $crstype ('official','unofficial','community','textbook') {
1.765     raeburn  14979:             $userenv{'canrequest.'.$crstype} =
                   14980:                 &Apache::lonnet::usertools_access($username,$domain,$crstype,
1.980     raeburn  14981:                                                   'reload','requestcourses',
                   14982:                                                   \%userenv,\%domdef,\%is_adv);
1.765     raeburn  14983:         }
                   14984: 
1.1075.2.14  raeburn  14985:         $userenv{'canrequest.author'} =
                   14986:             &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   14987:                                         'reload','requestauthor',
                   14988:                                         \%userenv,\%domdef,\%is_adv);
                   14989:         my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   14990:                                              $domain,$username);
                   14991:         my $reqstatus = $reqauthor{'author_status'};
                   14992:         if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   14993:             if (ref($reqauthor{'author'}) eq 'HASH') {
                   14994:                 $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   14995:                                                   $reqauthor{'author'}{'timestamp'};
                   14996:             }
                   14997:         }
                   14998: 
1.462     albertel 14999: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15000: 
1.462     albertel 15001: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15002: 		 &GDBM_WRCREAT(),0640)) {
                   15003: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15004: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15005: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15006:             if (ref($firstaccenv) eq 'HASH') {
                   15007:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15008:             }
                   15009:             if (ref($timerintenv) eq 'HASH') {
                   15010:                 &_add_to_env(\%disk_env,$timerintenv);
                   15011:             }
1.463     albertel 15012: 	    if (ref($args->{'extra_env'})) {
                   15013: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15014: 	    }
1.462     albertel 15015: 	    untie(%disk_env);
                   15016: 	} else {
1.705     tempelho 15017: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15018: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15019: 	    return 'error: '.$!;
                   15020: 	}
                   15021:     }
                   15022:     $env{'request.role'}='cm';
                   15023:     $env{'request.role.adv'}=$env{'user.adv'};
                   15024:     $env{'browser.type'}=$clientbrowser;
                   15025: 
                   15026:     return $cookie;
                   15027: 
                   15028: }
                   15029: 
                   15030: sub _add_to_env {
                   15031:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15032:     if (ref($env_data) eq 'HASH') {
                   15033:         while (my ($key,$value) = each(%$env_data)) {
                   15034: 	    $idf->{$prefix.$key} = $value;
                   15035: 	    $env{$prefix.$key}   = $value;
                   15036:         }
1.462     albertel 15037:     }
                   15038: }
                   15039: 
1.685     tempelho 15040: # --- Get the symbolic name of a problem and the url
                   15041: sub get_symb {
                   15042:     my ($request,$silent) = @_;
1.726     raeburn  15043:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15044:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15045:     if ($symb eq '') {
                   15046:         if (!$silent) {
1.1071    raeburn  15047:             if (ref($request)) { 
                   15048:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15049:             }
1.685     tempelho 15050:             return ();
                   15051:         }
                   15052:     }
                   15053:     &Apache::lonenc::check_decrypt(\$symb);
                   15054:     return ($symb);
                   15055: }
                   15056: 
                   15057: # --------------------------------------------------------------Get annotation
                   15058: 
                   15059: sub get_annotation {
                   15060:     my ($symb,$enc) = @_;
                   15061: 
                   15062:     my $key = $symb;
                   15063:     if (!$enc) {
                   15064:         $key =
                   15065:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15066:     }
                   15067:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15068:     return $annotation{$key};
                   15069: }
                   15070: 
                   15071: sub clean_symb {
1.731     raeburn  15072:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15073: 
                   15074:     &Apache::lonenc::check_decrypt(\$symb);
                   15075:     my $enc = $env{'request.enc'};
1.731     raeburn  15076:     if ($delete_enc) {
1.730     raeburn  15077:         delete($env{'request.enc'});
                   15078:     }
1.685     tempelho 15079: 
                   15080:     return ($symb,$enc);
                   15081: }
1.462     albertel 15082: 
1.1075.2.69  raeburn  15083: ############################################################
                   15084: ############################################################
                   15085: 
                   15086: =pod
                   15087: 
                   15088: =head1 Routines for building display used to search for courses
                   15089: 
                   15090: 
                   15091: =over 4
                   15092: 
                   15093: =item * &build_filters()
                   15094: 
                   15095: Create markup for a table used to set filters to use when selecting
                   15096: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15097: and quotacheck.pl
                   15098: 
                   15099: 
                   15100: Inputs:
                   15101: 
                   15102: filterlist - anonymous array of fields to include as potential filters
                   15103: 
                   15104: crstype - course type
                   15105: 
                   15106: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15107:               to pop-open a course selector (will contain "extra element").
                   15108: 
                   15109: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15110: 
                   15111: filter - anonymous hash of criteria and their values
                   15112: 
                   15113: action - form action
                   15114: 
                   15115: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15116: 
                   15117: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15118: 
                   15119: cloneruname - username of owner of new course who wants to clone
                   15120: 
                   15121: clonerudom - domain of owner of new course who wants to clone
                   15122: 
                   15123: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15124: 
                   15125: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15126: 
                   15127: codedom - domain
                   15128: 
                   15129: formname - value of form element named "form".
                   15130: 
                   15131: fixeddom - domain, if fixed.
                   15132: 
                   15133: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15134: 
                   15135: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15136: 
                   15137: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15138: 
                   15139: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15140: 
                   15141: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15142: 
                   15143: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15144: 
                   15145: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15146: 
                   15147: 
                   15148: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15149: 
                   15150: 
                   15151: Side Effects: None
                   15152: 
                   15153: =cut
                   15154: 
                   15155: # ---------------------------------------------- search for courses based on last activity etc.
                   15156: 
                   15157: sub build_filters {
                   15158:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15159:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15160:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15161:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15162:         $clonetext,$clonewarning) = @_;
                   15163:     my ($list,$jscript);
                   15164:     my $onchange = 'javascript:updateFilters(this)';
                   15165:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15166:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15167:         $typeselectform,$instcodetitle);
                   15168:     if ($formname eq '') {
                   15169:         $formname = $caller;
                   15170:     }
                   15171:     foreach my $item (@{$filterlist}) {
                   15172:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15173:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15174:             if ($item eq 'domainfilter') {
                   15175:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15176:             } elsif ($item eq 'coursefilter') {
                   15177:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15178:             } elsif ($item eq 'ownerfilter') {
                   15179:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15180:             } elsif ($item eq 'ownerdomfilter') {
                   15181:                 $filter->{'ownerdomfilter'} =
                   15182:                     &LONCAPA::clean_domain($filter->{$item});
                   15183:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15184:                                                        'ownerdomfilter',1);
                   15185:             } elsif ($item eq 'personfilter') {
                   15186:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15187:             } elsif ($item eq 'persondomfilter') {
                   15188:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15189:                                                         'persondomfilter',1);
                   15190:             } else {
                   15191:                 $filter->{$item} =~ s/\W//g;
                   15192:             }
                   15193:             if (!$filter->{$item}) {
                   15194:                 $filter->{$item} = '';
                   15195:             }
                   15196:         }
                   15197:         if ($item eq 'domainfilter') {
                   15198:             my $allow_blank = 1;
                   15199:             if ($formname eq 'portform') {
                   15200:                 $allow_blank=0;
                   15201:             } elsif ($formname eq 'studentform') {
                   15202:                 $allow_blank=0;
                   15203:             }
                   15204:             if ($fixeddom) {
                   15205:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15206:                                     ' value="'.$codedom.'" />'.
                   15207:                                     &Apache::lonnet::domain($codedom,'description');
                   15208:             } else {
                   15209:                 $domainselectform = &select_dom_form($filter->{$item},
                   15210:                                                      'domainfilter',
                   15211:                                                       $allow_blank,'',$onchange);
                   15212:             }
                   15213:         } else {
                   15214:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15215:         }
                   15216:     }
                   15217: 
                   15218:     # last course activity filter and selection
                   15219:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15220: 
                   15221:     # course created filter and selection
                   15222:     if (exists($filter->{'createdfilter'})) {
                   15223:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15224:     }
                   15225: 
                   15226:     my %lt = &Apache::lonlocal::texthash(
                   15227:                 'cac' => "$crstype Activity",
                   15228:                 'ccr' => "$crstype Created",
                   15229:                 'cde' => "$crstype Title",
                   15230:                 'cdo' => "$crstype Domain",
                   15231:                 'ins' => 'Institutional Code',
                   15232:                 'inc' => 'Institutional Categorization',
                   15233:                 'cow' => "$crstype Owner/Co-owner",
                   15234:                 'cop' => "$crstype Personnel Includes",
                   15235:                 'cog' => 'Type',
                   15236:              );
                   15237: 
                   15238:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15239:         my $typeval = 'Course';
                   15240:         if ($crstype eq 'Community') {
                   15241:             $typeval = 'Community';
                   15242:         }
                   15243:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15244:     } else {
                   15245:         $typeselectform =  '<select name="type" size="1"';
                   15246:         if ($onchange) {
                   15247:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15248:         }
                   15249:         $typeselectform .= '>'."\n";
                   15250:         foreach my $posstype ('Course','Community') {
                   15251:             $typeselectform.='<option value="'.$posstype.'"'.
                   15252:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15253:         }
                   15254:         $typeselectform.="</select>";
                   15255:     }
                   15256: 
                   15257:     my ($cloneableonlyform,$cloneabletitle);
                   15258:     if (exists($filter->{'cloneableonly'})) {
                   15259:         my $cloneableon = '';
                   15260:         my $cloneableoff = ' checked="checked"';
                   15261:         if ($filter->{'cloneableonly'}) {
                   15262:             $cloneableon = $cloneableoff;
                   15263:             $cloneableoff = '';
                   15264:         }
                   15265:         $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>';
                   15266:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15267:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15268:         } else {
                   15269:             $cloneabletitle = &mt('Cloneable by you');
                   15270:         }
                   15271:     }
                   15272:     my $officialjs;
                   15273:     if ($crstype eq 'Course') {
                   15274:         if (exists($filter->{'instcodefilter'})) {
                   15275: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15276: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15277:             if ($codedom) {
                   15278:                 $officialjs = 1;
                   15279:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15280:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15281:                                                                   $officialjs,$codetitlesref);
                   15282:                 if ($jscript) {
                   15283:                     $jscript = '<script type="text/javascript">'."\n".
                   15284:                                '// <![CDATA['."\n".
                   15285:                                $jscript."\n".
                   15286:                                '// ]]>'."\n".
                   15287:                                '</script>'."\n";
                   15288:                 }
                   15289:             }
                   15290:             if ($instcodeform eq '') {
                   15291:                 $instcodeform =
                   15292:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15293:                     $list->{'instcodefilter'}.'" />';
                   15294:                 $instcodetitle = $lt{'ins'};
                   15295:             } else {
                   15296:                 $instcodetitle = $lt{'inc'};
                   15297:             }
                   15298:             if ($fixeddom) {
                   15299:                 $instcodetitle .= '<br />('.$codedom.')';
                   15300:             }
                   15301:         }
                   15302:     }
                   15303:     my $output = qq|
                   15304: <form method="post" name="filterpicker" action="$action">
                   15305: <input type="hidden" name="form" value="$formname" />
                   15306: |;
                   15307:     if ($formname eq 'modifycourse') {
                   15308:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15309:                    '<input type="hidden" name="prevphase" value="'.
                   15310:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15311:     } elsif ($formname eq 'quotacheck') {
                   15312:         $output .= qq|
                   15313: <input type="hidden" name="sortby" value="" />
                   15314: <input type="hidden" name="sortorder" value="" />
                   15315: |;
                   15316:     } else {
1.1075.2.69  raeburn  15317:         my $name_input;
                   15318:         if ($cnameelement ne '') {
                   15319:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15320:                           $cnameelement.'" />';
                   15321:         }
                   15322:         $output .= qq|
                   15323: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15324: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15325: $name_input
                   15326: $roleelement
                   15327: $multelement
                   15328: $typeelement
                   15329: |;
                   15330:         if ($formname eq 'portform') {
                   15331:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15332:         }
                   15333:     }
                   15334:     if ($fixeddom) {
                   15335:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15336:     }
                   15337:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15338:     if ($sincefilterform) {
                   15339:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15340:                   .$sincefilterform
                   15341:                   .&Apache::lonhtmlcommon::row_closure();
                   15342:     }
                   15343:     if ($createdfilterform) {
                   15344:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15345:                   .$createdfilterform
                   15346:                   .&Apache::lonhtmlcommon::row_closure();
                   15347:     }
                   15348:     if ($domainselectform) {
                   15349:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15350:                   .$domainselectform
                   15351:                   .&Apache::lonhtmlcommon::row_closure();
                   15352:     }
                   15353:     if ($typeselectform) {
                   15354:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15355:             $output .= $typeselectform;
                   15356:         } else {
                   15357:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   15358:                       .$typeselectform
                   15359:                       .&Apache::lonhtmlcommon::row_closure();
                   15360:         }
                   15361:     }
                   15362:     if ($instcodeform) {
                   15363:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   15364:                   .$instcodeform
                   15365:                   .&Apache::lonhtmlcommon::row_closure();
                   15366:     }
                   15367:     if (exists($filter->{'ownerfilter'})) {
                   15368:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   15369:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15370:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   15371:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15372:                    $ownerdomselectform.'</td></tr></table>'.
                   15373:                    &Apache::lonhtmlcommon::row_closure();
                   15374:     }
                   15375:     if (exists($filter->{'personfilter'})) {
                   15376:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   15377:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   15378:                    '<input type="text" name="personfilter" size="20" value="'.
                   15379:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   15380:                    $persondomselectform.'</td></tr></table>'.
                   15381:                    &Apache::lonhtmlcommon::row_closure();
                   15382:     }
                   15383:     if (exists($filter->{'coursefilter'})) {
                   15384:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   15385:                   .'<input type="text" name="coursefilter" size="25" value="'
                   15386:                   .$list->{'coursefilter'}.'" />'
                   15387:                   .&Apache::lonhtmlcommon::row_closure();
                   15388:     }
                   15389:     if ($cloneableonlyform) {
                   15390:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   15391:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   15392:     }
                   15393:     if (exists($filter->{'descriptfilter'})) {
                   15394:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   15395:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   15396:                   .$list->{'descriptfilter'}.'" />'
                   15397:                   .&Apache::lonhtmlcommon::row_closure(1);
                   15398:     }
                   15399:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   15400:                '<input type="hidden" name="updater" value="" />'."\n".
                   15401:                '<input type="submit" name="gosearch" value="'.
                   15402:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   15403:     return $jscript.$clonewarning.$output;
                   15404: }
                   15405: 
                   15406: =pod
                   15407: 
                   15408: =item * &timebased_select_form()
                   15409: 
                   15410: Create markup for a dropdown list used to select a time-based
                   15411: filter e.g., Course Activity, Course Created, when searching for courses
                   15412: or communities
                   15413: 
                   15414: Inputs:
                   15415: 
                   15416: item - name of form element (sincefilter or createdfilter)
                   15417: 
                   15418: filter - anonymous hash of criteria and their values
                   15419: 
                   15420: Returns: HTML for a select box contained a blank, then six time selections,
                   15421:          with value set in incoming form variables currently selected.
                   15422: 
                   15423: Side Effects: None
                   15424: 
                   15425: =cut
                   15426: 
                   15427: sub timebased_select_form {
                   15428:     my ($item,$filter) = @_;
                   15429:     if (ref($filter) eq 'HASH') {
                   15430:         $filter->{$item} =~ s/[^\d-]//g;
                   15431:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   15432:         return &select_form(
                   15433:                             $filter->{$item},
                   15434:                             $item,
                   15435:                             {      '-1' => '',
                   15436:                                 '86400' => &mt('today'),
                   15437:                                '604800' => &mt('last week'),
                   15438:                               '2592000' => &mt('last month'),
                   15439:                               '7776000' => &mt('last three months'),
                   15440:                              '15552000' => &mt('last six months'),
                   15441:                              '31104000' => &mt('last year'),
                   15442:                     'select_form_order' =>
                   15443:                            ['-1','86400','604800','2592000','7776000',
                   15444:                             '15552000','31104000']});
                   15445:     }
                   15446: }
                   15447: 
                   15448: =pod
                   15449: 
                   15450: =item * &js_changer()
                   15451: 
                   15452: Create script tag containing Javascript used to submit course search form
                   15453: when course type or domain is changed, and also to hide 'Searching ...' on
                   15454: page load completion for page showing search result.
                   15455: 
                   15456: Inputs: None
                   15457: 
                   15458: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   15459: 
                   15460: Side Effects: None
                   15461: 
                   15462: =cut
                   15463: 
                   15464: sub js_changer {
                   15465:     return <<ENDJS;
                   15466: <script type="text/javascript">
                   15467: // <![CDATA[
                   15468: function updateFilters(caller) {
                   15469:     if (typeof(caller) != "undefined") {
                   15470:         document.filterpicker.updater.value = caller.name;
                   15471:     }
                   15472:     document.filterpicker.submit();
                   15473: }
                   15474: 
                   15475: function hideSearching() {
                   15476:     if (document.getElementById('searching')) {
                   15477:         document.getElementById('searching').style.display = 'none';
                   15478:     }
                   15479:     return;
                   15480: }
                   15481: 
                   15482: // ]]>
                   15483: </script>
                   15484: 
                   15485: ENDJS
                   15486: }
                   15487: 
                   15488: =pod
                   15489: 
                   15490: =item * &search_courses()
                   15491: 
                   15492: Process selected filters form course search form and pass to lonnet::courseiddump
                   15493: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   15494: 
                   15495: Inputs:
                   15496: 
                   15497: dom - domain being searched
                   15498: 
                   15499: type - course type ('Course' or 'Community' or '.' if any).
                   15500: 
                   15501: filter - anonymous hash of criteria and their values
                   15502: 
                   15503: numtitles - for institutional codes - number of categories
                   15504: 
                   15505: cloneruname - optional username of new course owner
                   15506: 
                   15507: clonerudom - optional domain of new course owner
                   15508: 
1.1075.2.95  raeburn  15509: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  15510:             (used when DC is using course creation form)
                   15511: 
                   15512: codetitles - reference to array of titles of components in institutional codes (official courses).
                   15513: 
1.1075.2.95  raeburn  15514: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   15515:            (and so can clone automatically)
                   15516: 
                   15517: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   15518: 
                   15519: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   15520:               courses to clone
1.1075.2.69  raeburn  15521: 
                   15522: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   15523: 
                   15524: 
                   15525: Side Effects: None
                   15526: 
                   15527: =cut
                   15528: 
                   15529: 
                   15530: sub search_courses {
1.1075.2.95  raeburn  15531:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   15532:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  15533:     my (%courses,%showcourses,$cloner);
                   15534:     if (($filter->{'ownerfilter'} ne '') ||
                   15535:         ($filter->{'ownerdomfilter'} ne '')) {
                   15536:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   15537:                                        $filter->{'ownerdomfilter'};
                   15538:     }
                   15539:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   15540:         if (!$filter->{$item}) {
                   15541:             $filter->{$item}='.';
                   15542:         }
                   15543:     }
                   15544:     my $now = time;
                   15545:     my $timefilter =
                   15546:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   15547:     my ($createdbefore,$createdafter);
                   15548:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   15549:         $createdbefore = $now;
                   15550:         $createdafter = $now-$filter->{'createdfilter'};
                   15551:     }
                   15552:     my ($instcodefilter,$regexpok);
                   15553:     if ($numtitles) {
                   15554:         if ($env{'form.official'} eq 'on') {
                   15555:             $instcodefilter =
                   15556:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15557:             $regexpok = 1;
                   15558:         } elsif ($env{'form.official'} eq 'off') {
                   15559:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   15560:             unless ($instcodefilter eq '') {
                   15561:                 $regexpok = -1;
                   15562:             }
                   15563:         }
                   15564:     } else {
                   15565:         $instcodefilter = $filter->{'instcodefilter'};
                   15566:     }
                   15567:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   15568:     if ($type eq '') { $type = '.'; }
                   15569: 
                   15570:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   15571:         $cloner = $cloneruname.':'.$clonerudom;
                   15572:     }
                   15573:     %courses = &Apache::lonnet::courseiddump($dom,
                   15574:                                              $filter->{'descriptfilter'},
                   15575:                                              $timefilter,
                   15576:                                              $instcodefilter,
                   15577:                                              $filter->{'combownerfilter'},
                   15578:                                              $filter->{'coursefilter'},
                   15579:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  15580:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  15581:                                              $filter->{'cloneableonly'},
                   15582:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  15583:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  15584:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   15585:         my $ccrole;
                   15586:         if ($type eq 'Community') {
                   15587:             $ccrole = 'co';
                   15588:         } else {
                   15589:             $ccrole = 'cc';
                   15590:         }
                   15591:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   15592:                                                      $filter->{'persondomfilter'},
                   15593:                                                      'userroles',undef,
                   15594:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   15595:                                                      $dom);
                   15596:         foreach my $role (keys(%rolehash)) {
                   15597:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   15598:             my $cid = $cdom.'_'.$cnum;
                   15599:             if (exists($courses{$cid})) {
                   15600:                 if (ref($courses{$cid}) eq 'HASH') {
                   15601:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   15602:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
                   15603:                             push (@{$courses{$cid}{roles}},$courserole);
                   15604:                         }
                   15605:                     } else {
                   15606:                         $courses{$cid}{roles} = [$courserole];
                   15607:                     }
                   15608:                     $showcourses{$cid} = $courses{$cid};
                   15609:                 }
                   15610:             }
                   15611:         }
                   15612:         %courses = %showcourses;
                   15613:     }
                   15614:     return %courses;
                   15615: }
                   15616: 
                   15617: =pod
                   15618: 
                   15619: =back
                   15620: 
1.1075.2.88  raeburn  15621: =head1 Routines for version requirements for current course.
                   15622: 
                   15623: =over 4
                   15624: 
                   15625: =item * &check_release_required()
                   15626: 
                   15627: Compares required LON-CAPA version with version on server, and
                   15628: if required version is newer looks for a server with the required version.
                   15629: 
                   15630: Looks first at servers in user's owen domain; if none suitable, looks at
                   15631: servers in course's domain are permitted to host sessions for user's domain.
                   15632: 
                   15633: Inputs:
                   15634: 
                   15635: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15636: 
                   15637: $courseid - Course ID of current course
                   15638: 
                   15639: $rolecode - User's current role in course (for switchserver query string).
                   15640: 
                   15641: $required - LON-CAPA version needed by course (format: Major.Minor).
                   15642: 
                   15643: 
                   15644: Returns:
                   15645: 
                   15646: $switchserver - query string tp append to /adm/switchserver call (if
                   15647:                 current server's LON-CAPA version is too old.
                   15648: 
                   15649: $warning - Message is displayed if no suitable server could be found.
                   15650: 
                   15651: =cut
                   15652: 
                   15653: sub check_release_required {
                   15654:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   15655:     my ($switchserver,$warning);
                   15656:     if ($required ne '') {
                   15657:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   15658:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15659:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   15660:             my $otherserver;
                   15661:             if (($major eq '' && $minor eq '') ||
                   15662:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   15663:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   15664:                 my $switchlcrev =
                   15665:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   15666:                                                            $userdomserver);
                   15667:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   15668:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   15669:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   15670:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   15671:                     if ($cdom ne $env{'user.domain'}) {
                   15672:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   15673:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   15674:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   15675:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   15676:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   15677:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   15678:                         my $canhost =
                   15679:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   15680:                                                               $coursedomserver,
                   15681:                                                               $remoterev,
                   15682:                                                               $udomdefaults{'remotesessions'},
                   15683:                                                               $defdomdefaults{'hostedsessions'});
                   15684: 
                   15685:                         if ($canhost) {
                   15686:                             $otherserver = $coursedomserver;
                   15687:                         } else {
                   15688:                             $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.");
                   15689:                         }
                   15690:                     } else {
                   15691:                         $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).");
                   15692:                     }
                   15693:                 } else {
                   15694:                     $otherserver = $userdomserver;
                   15695:                 }
                   15696:             }
                   15697:             if ($otherserver ne '') {
                   15698:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   15699:             }
                   15700:         }
                   15701:     }
                   15702:     return ($switchserver,$warning);
                   15703: }
                   15704: 
                   15705: =pod
                   15706: 
                   15707: =item * &check_release_result()
                   15708: 
                   15709: Inputs:
                   15710: 
                   15711: $switchwarning - Warning message if no suitable server found to host session.
                   15712: 
                   15713: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15714:                 and current role.
                   15715: 
                   15716: Returns: HTML to display with information about requirement to switch server.
                   15717:          Either displaying warning with link to Roles/Courses screen or
                   15718:          display link to switchserver.
                   15719: 
1.1075.2.69  raeburn  15720: =cut
                   15721: 
1.1075.2.88  raeburn  15722: sub check_release_result {
                   15723:     my ($switchwarning,$switchserver) = @_;
                   15724:     my $output = &start_page('Selected course unavailable on this server').
                   15725:                  '<p class="LC_warning">';
                   15726:     if ($switchwarning) {
                   15727:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   15728:         if (&show_course()) {
                   15729:             $output .= &mt('Display courses');
                   15730:         } else {
                   15731:             $output .= &mt('Display roles');
                   15732:         }
                   15733:         $output .= '</a>';
                   15734:     } elsif ($switchserver) {
                   15735:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   15736:                    '<br />'.
                   15737:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   15738:                    &mt('Switch Server').
                   15739:                    '</a>';
                   15740:     }
                   15741:     $output .= '</p>'.&end_page();
                   15742:     return $output;
                   15743: }
                   15744: 
                   15745: =pod
                   15746: 
                   15747: =item * &needs_coursereinit()
                   15748: 
                   15749: Determine if course contents stored for user's session needs to be
                   15750: refreshed, because content has changed since "Big Hash" last tied.
                   15751: 
                   15752: Check for change is made if time last checked is more than 10 minutes ago
                   15753: (by default).
                   15754: 
                   15755: Inputs:
                   15756: 
                   15757: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   15758: 
                   15759: $interval (optional) - Time which may elapse (in s) between last check for content
                   15760:                        change in current course. (default: 600 s).
                   15761: 
                   15762: Returns: an array; first element is:
                   15763: 
                   15764: =over 4
                   15765: 
                   15766: 'switch' - if content updates mean user's session
                   15767:            needs to be switched to a server running a newer LON-CAPA version
                   15768: 
                   15769: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   15770:            on current server hosting user's session
                   15771: 
                   15772: ''       - if no action required.
                   15773: 
                   15774: =back
                   15775: 
                   15776: If first item element is 'switch':
                   15777: 
                   15778: second item is $switchwarning - Warning message if no suitable server found to host session.
                   15779: 
                   15780: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   15781:                               and current role.
                   15782: 
                   15783: otherwise: no other elements returned.
                   15784: 
                   15785: =back
                   15786: 
                   15787: =cut
                   15788: 
                   15789: sub needs_coursereinit {
                   15790:     my ($loncaparev,$interval) = @_;
                   15791:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   15792:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   15793:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   15794:     my $now = time;
                   15795:     if ($interval eq '') {
                   15796:         $interval = 600;
                   15797:     }
                   15798:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   15799:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15800:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   15801:         if ($lastchange > $env{'request.course.tied'}) {
                   15802:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15803:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   15804:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   15805:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   15806:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   15807:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   15808:                     my ($switchserver,$switchwarning) =
                   15809:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   15810:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   15811:                     if ($switchwarning ne '' || $switchserver ne '') {
                   15812:                         return ('switch',$switchwarning,$switchserver);
                   15813:                     }
                   15814:                 }
                   15815:             }
                   15816:             return ('update');
                   15817:         }
                   15818:     }
                   15819:     return ();
                   15820: }
1.1075.2.69  raeburn  15821: 
1.1075.2.11  raeburn  15822: sub update_content_constraints {
                   15823:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15824:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   15825:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   15826:     my %checkresponsetypes;
                   15827:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   15828:         my ($item,$name,$value) = split(/:/,$key);
                   15829:         if ($item eq 'resourcetag') {
                   15830:             if ($name eq 'responsetype') {
                   15831:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   15832:             }
                   15833:         }
                   15834:     }
                   15835:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15836:     if (defined($navmap)) {
                   15837:         my %allresponses;
                   15838:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   15839:             my %responses = $res->responseTypes();
                   15840:             foreach my $key (keys(%responses)) {
                   15841:                 next unless(exists($checkresponsetypes{$key}));
                   15842:                 $allresponses{$key} += $responses{$key};
                   15843:             }
                   15844:         }
                   15845:         foreach my $key (keys(%allresponses)) {
                   15846:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   15847:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   15848:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   15849:             }
                   15850:         }
                   15851:         undef($navmap);
                   15852:     }
                   15853:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   15854:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   15855:     }
                   15856:     return;
                   15857: }
                   15858: 
1.1075.2.27  raeburn  15859: sub allmaps_incourse {
                   15860:     my ($cdom,$cnum,$chome,$cid) = @_;
                   15861:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   15862:         $cid = $env{'request.course.id'};
                   15863:         $cdom = $env{'course.'.$cid.'.domain'};
                   15864:         $cnum = $env{'course.'.$cid.'.num'};
                   15865:         $chome = $env{'course.'.$cid.'.home'};
                   15866:     }
                   15867:     my %allmaps = ();
                   15868:     my $lastchange =
                   15869:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   15870:     if ($lastchange > $env{'request.course.tied'}) {
                   15871:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   15872:         unless ($ferr) {
                   15873:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   15874:         }
                   15875:     }
                   15876:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15877:     if (defined($navmap)) {
                   15878:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   15879:             $allmaps{$res->src()} = 1;
                   15880:         }
                   15881:     }
                   15882:     return \%allmaps;
                   15883: }
                   15884: 
1.1075.2.11  raeburn  15885: sub parse_supplemental_title {
                   15886:     my ($title) = @_;
                   15887: 
                   15888:     my ($foldertitle,$renametitle);
                   15889:     if ($title =~ /&amp;&amp;&amp;/) {
                   15890:         $title = &HTML::Entites::decode($title);
                   15891:     }
                   15892:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   15893:         $renametitle=$4;
                   15894:         my ($time,$uname,$udom) = ($1,$2,$3);
                   15895:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   15896:         my $name =  &plainname($uname,$udom);
                   15897:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   15898:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   15899:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   15900:             $name.': <br />'.$foldertitle;
                   15901:     }
                   15902:     if (wantarray) {
                   15903:         return ($title,$foldertitle,$renametitle);
                   15904:     }
                   15905:     return $title;
                   15906: }
                   15907: 
1.1075.2.43  raeburn  15908: sub recurse_supplemental {
                   15909:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   15910:     if ($suppmap) {
                   15911:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   15912:         if ($fatal) {
                   15913:             $errors ++;
                   15914:         } else {
                   15915:             if ($#LONCAPA::map::resources > 0) {
                   15916:                 foreach my $res (@LONCAPA::map::resources) {
                   15917:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   15918:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  15919:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   15920:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  15921:                         } else {
                   15922:                             $numfiles ++;
                   15923:                         }
                   15924:                     }
                   15925:                 }
                   15926:             }
                   15927:         }
                   15928:     }
                   15929:     return ($numfiles,$errors);
                   15930: }
                   15931: 
1.1075.2.18  raeburn  15932: sub symb_to_docspath {
                   15933:     my ($symb) = @_;
                   15934:     return unless ($symb);
                   15935:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   15936:     if ($resurl=~/\.(sequence|page)$/) {
                   15937:         $mapurl=$resurl;
                   15938:     } elsif ($resurl eq 'adm/navmaps') {
                   15939:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   15940:     }
                   15941:     my $mapresobj;
                   15942:     my $navmap = Apache::lonnavmaps::navmap->new();
                   15943:     if (ref($navmap)) {
                   15944:         $mapresobj = $navmap->getResourceByUrl($mapurl);
                   15945:     }
                   15946:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   15947:     my $type=$2;
                   15948:     my $path;
                   15949:     if (ref($mapresobj)) {
                   15950:         my $pcslist = $mapresobj->map_hierarchy();
                   15951:         if ($pcslist ne '') {
                   15952:             foreach my $pc (split(/,/,$pcslist)) {
                   15953:                 next if ($pc <= 1);
                   15954:                 my $res = $navmap->getByMapPc($pc);
                   15955:                 if (ref($res)) {
                   15956:                     my $thisurl = $res->src();
                   15957:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   15958:                     my $thistitle = $res->title();
                   15959:                     $path .= '&'.
                   15960:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  15961:                              &escape($thistitle).
1.1075.2.18  raeburn  15962:                              ':'.$res->randompick().
                   15963:                              ':'.$res->randomout().
                   15964:                              ':'.$res->encrypted().
                   15965:                              ':'.$res->randomorder().
                   15966:                              ':'.$res->is_page();
                   15967:                 }
                   15968:             }
                   15969:         }
                   15970:         $path =~ s/^\&//;
                   15971:         my $maptitle = $mapresobj->title();
                   15972:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  15973:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  15974:         }
                   15975:         $path .= (($path ne '')? '&' : '').
                   15976:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  15977:                  &escape($maptitle).
1.1075.2.18  raeburn  15978:                  ':'.$mapresobj->randompick().
                   15979:                  ':'.$mapresobj->randomout().
                   15980:                  ':'.$mapresobj->encrypted().
                   15981:                  ':'.$mapresobj->randomorder().
                   15982:                  ':'.$mapresobj->is_page();
                   15983:     } else {
                   15984:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   15985:         my $ispage = (($type eq 'page')? 1 : '');
                   15986:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  15987:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  15988:         }
                   15989:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  15990:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  15991:     }
                   15992:     unless ($mapurl eq 'default') {
                   15993:         $path = 'default&'.
1.1075.2.46  raeburn  15994:                 &escape('Main Content').
1.1075.2.18  raeburn  15995:                 ':::::&'.$path;
                   15996:     }
                   15997:     return $path;
                   15998: }
                   15999: 
1.1075.2.14  raeburn  16000: sub captcha_display {
                   16001:     my ($context,$lonhost) = @_;
                   16002:     my ($output,$error);
                   16003:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   16004:     if ($captcha eq 'original') {
                   16005:         $output = &create_captcha();
                   16006:         unless ($output) {
                   16007:             $error = 'captcha';
                   16008:         }
                   16009:     } elsif ($captcha eq 'recaptcha') {
                   16010:         $output = &create_recaptcha($pubkey);
                   16011:         unless ($output) {
                   16012:             $error = 'recaptcha';
                   16013:         }
                   16014:     }
1.1075.2.66  raeburn  16015:     return ($output,$error,$captcha);
1.1075.2.14  raeburn  16016: }
                   16017: 
                   16018: sub captcha_response {
                   16019:     my ($context,$lonhost) = @_;
                   16020:     my ($captcha_chk,$captcha_error);
                   16021:     my ($captcha,$pubkey,$privkey) = &get_captcha_config($context,$lonhost);
                   16022:     if ($captcha eq 'original') {
                   16023:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16024:     } elsif ($captcha eq 'recaptcha') {
                   16025:         $captcha_chk = &check_recaptcha($privkey);
                   16026:     } else {
                   16027:         $captcha_chk = 1;
                   16028:     }
                   16029:     return ($captcha_chk,$captcha_error);
                   16030: }
                   16031: 
                   16032: sub get_captcha_config {
                   16033:     my ($context,$lonhost) = @_;
                   16034:     my ($captcha,$pubkey,$privkey,$hashtocheck);
                   16035:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16036:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16037:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16038:     if ($context eq 'usercreation') {
                   16039:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16040:         if (ref($domconfig{$context}) eq 'HASH') {
                   16041:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16042:             if (ref($hashtocheck) eq 'HASH') {
                   16043:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16044:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16045:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16046:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16047:                     }
                   16048:                     if ($privkey && $pubkey) {
                   16049:                         $captcha = 'recaptcha';
                   16050:                     } else {
                   16051:                         $captcha = 'original';
                   16052:                     }
                   16053:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16054:                     $captcha = 'original';
                   16055:                 }
                   16056:             }
                   16057:         } else {
                   16058:             $captcha = 'captcha';
                   16059:         }
                   16060:     } elsif ($context eq 'login') {
                   16061:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16062:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16063:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16064:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16065:             if ($privkey && $pubkey) {
                   16066:                 $captcha = 'recaptcha';
                   16067:             } else {
                   16068:                 $captcha = 'original';
                   16069:             }
                   16070:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16071:             $captcha = 'original';
                   16072:         }
                   16073:     }
                   16074:     return ($captcha,$pubkey,$privkey);
                   16075: }
                   16076: 
                   16077: sub create_captcha {
                   16078:     my %captcha_params = &captcha_settings();
                   16079:     my ($output,$maxtries,$tries) = ('',10,0);
                   16080:     while ($tries < $maxtries) {
                   16081:         $tries ++;
                   16082:         my $captcha = Authen::Captcha->new (
                   16083:                                            output_folder => $captcha_params{'output_dir'},
                   16084:                                            data_folder   => $captcha_params{'db_dir'},
                   16085:                                           );
                   16086:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16087: 
                   16088:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16089:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16090:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16091:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16092:                       '<br />'.
                   16093:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16094:             last;
                   16095:         }
                   16096:     }
                   16097:     return $output;
                   16098: }
                   16099: 
                   16100: sub captcha_settings {
                   16101:     my %captcha_params = (
                   16102:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16103:                            www_output_dir => "/captchaspool",
                   16104:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16105:                            numchars       => '5',
                   16106:                          );
                   16107:     return %captcha_params;
                   16108: }
                   16109: 
                   16110: sub check_captcha {
                   16111:     my ($captcha_chk,$captcha_error);
                   16112:     my $code = $env{'form.code'};
                   16113:     my $md5sum = $env{'form.crypt'};
                   16114:     my %captcha_params = &captcha_settings();
                   16115:     my $captcha = Authen::Captcha->new(
                   16116:                       output_folder => $captcha_params{'output_dir'},
                   16117:                       data_folder   => $captcha_params{'db_dir'},
                   16118:                   );
1.1075.2.26  raeburn  16119:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16120:     my %captcha_hash = (
                   16121:                         0       => 'Code not checked (file error)',
                   16122:                        -1      => 'Failed: code expired',
                   16123:                        -2      => 'Failed: invalid code (not in database)',
                   16124:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16125:     );
                   16126:     if ($captcha_chk != 1) {
                   16127:         $captcha_error = $captcha_hash{$captcha_chk}
                   16128:     }
                   16129:     return ($captcha_chk,$captcha_error);
                   16130: }
                   16131: 
                   16132: sub create_recaptcha {
                   16133:     my ($pubkey) = @_;
1.1075.2.51  raeburn  16134:     my $use_ssl;
                   16135:     if ($ENV{'SERVER_PORT'} == 443) {
                   16136:         $use_ssl = 1;
                   16137:     }
1.1075.2.14  raeburn  16138:     my $captcha = Captcha::reCAPTCHA->new;
                   16139:     return $captcha->get_options_setter({theme => 'white'})."\n".
1.1075.2.51  raeburn  16140:            $captcha->get_html($pubkey,undef,$use_ssl).
1.1075.2.92  raeburn  16141:            &mt('If the text is hard to read, [_1] will replace them.',
1.1075.2.39  raeburn  16142:                '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
1.1075.2.14  raeburn  16143:            '<br /><br />';
                   16144: }
                   16145: 
                   16146: sub check_recaptcha {
                   16147:     my ($privkey) = @_;
                   16148:     my $captcha_chk;
                   16149:     my $captcha = Captcha::reCAPTCHA->new;
                   16150:     my $captcha_result =
                   16151:         $captcha->check_answer(
                   16152:                                 $privkey,
                   16153:                                 $ENV{'REMOTE_ADDR'},
                   16154:                                 $env{'form.recaptcha_challenge_field'},
                   16155:                                 $env{'form.recaptcha_response_field'},
                   16156:                               );
                   16157:     if ($captcha_result->{is_valid}) {
                   16158:         $captcha_chk = 1;
                   16159:     }
                   16160:     return $captcha_chk;
                   16161: }
                   16162: 
1.1075.2.64  raeburn  16163: sub emailusername_info {
1.1075.2.67  raeburn  16164:     my @fields = ('firstname','lastname','institution','web','location','officialemail');
1.1075.2.64  raeburn  16165:     my %titles = &Apache::lonlocal::texthash (
                   16166:                      lastname      => 'Last Name',
                   16167:                      firstname     => 'First Name',
                   16168:                      institution   => 'School/college/university',
                   16169:                      location      => "School's city, state/province, country",
                   16170:                      web           => "School's web address",
                   16171:                      officialemail => 'E-mail address at institution (if different)',
                   16172:                  );
                   16173:     return (\@fields,\%titles);
                   16174: }
                   16175: 
1.1075.2.56  raeburn  16176: sub cleanup_html {
                   16177:     my ($incoming) = @_;
                   16178:     my $outgoing;
                   16179:     if ($incoming ne '') {
                   16180:         $outgoing = $incoming;
                   16181:         $outgoing =~ s/;/&#059;/g;
                   16182:         $outgoing =~ s/\#/&#035;/g;
                   16183:         $outgoing =~ s/\&/&#038;/g;
                   16184:         $outgoing =~ s/</&#060;/g;
                   16185:         $outgoing =~ s/>/&#062;/g;
                   16186:         $outgoing =~ s/\(/&#040/g;
                   16187:         $outgoing =~ s/\)/&#041;/g;
                   16188:         $outgoing =~ s/"/&#034;/g;
                   16189:         $outgoing =~ s/'/&#039;/g;
                   16190:         $outgoing =~ s/\$/&#036;/g;
                   16191:         $outgoing =~ s{/}{&#047;}g;
                   16192:         $outgoing =~ s/=/&#061;/g;
                   16193:         $outgoing =~ s/\\/&#092;/g
                   16194:     }
                   16195:     return $outgoing;
                   16196: }
                   16197: 
1.1075.2.74  raeburn  16198: # Checks for critical messages and returns a redirect url if one exists.
                   16199: # $interval indicates how often to check for messages.
                   16200: sub critical_redirect {
                   16201:     my ($interval) = @_;
                   16202:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16203:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16204:                                         $env{'user.name'});
                   16205:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16206:         my $redirecturl;
                   16207:         if ($what[0]) {
                   16208:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16209:                 $redirecturl='/adm/email?critical=display';
                   16210:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16211:                 return (1, $url);
                   16212:             }
                   16213:         }
                   16214:     }
                   16215:     return ();
                   16216: }
                   16217: 
1.1075.2.64  raeburn  16218: # Use:
                   16219: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16220: #
                   16221: ##################################################
                   16222: #          password associated functions         #
                   16223: ##################################################
                   16224: sub des_keys {
                   16225:     # Make a new key for DES encryption.
                   16226:     # Each key has two parts which are returned separately.
                   16227:     # Please note:  Each key must be passed through the &hex function
                   16228:     # before it is output to the web browser.  The hex versions cannot
                   16229:     # be used to decrypt.
                   16230:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16231:                 '8','9','a','b','c','d','e','f');
                   16232:     my $lkey='';
                   16233:     for (0..7) {
                   16234:         $lkey.=$hexstr[rand(15)];
                   16235:     }
                   16236:     my $ukey='';
                   16237:     for (0..7) {
                   16238:         $ukey.=$hexstr[rand(15)];
                   16239:     }
                   16240:     return ($lkey,$ukey);
                   16241: }
                   16242: 
                   16243: sub des_decrypt {
                   16244:     my ($key,$cyphertext) = @_;
                   16245:     my $keybin=pack("H16",$key);
                   16246:     my $cypher;
                   16247:     if ($Crypt::DES::VERSION>=2.03) {
                   16248:         $cypher=new Crypt::DES $keybin;
                   16249:     } else {
                   16250:         $cypher=new DES $keybin;
                   16251:     }
                   16252:     my $plaintext=
                   16253:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,0,16))));
                   16254:     $plaintext.=
                   16255:         $cypher->decrypt(unpack("a8",pack("H16",substr($cyphertext,16,16))));
                   16256:     $plaintext=substr($plaintext,1,ord(substr($plaintext,0,1)) );
                   16257:     return $plaintext;
                   16258: }
                   16259: 
1.112     bowersj2 16260: 1;
                   16261: __END__;
1.41      ng       16262: 

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