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

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.133! raeburn     4: # $Id: loncommon.pm,v 1.1075.2.132 2019/07/19 13:19:50 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.1075.2.102  raeburn    75: use DateTime::Locale;
1.1075.2.94  raeburn    76: use Encode();
1.1075.2.14  raeburn    77: use Authen::Captcha;
                     78: use Captcha::reCAPTCHA;
1.1075.2.107  raeburn    79: use JSON::DWIW;
                     80: use LWP::UserAgent;
1.1075.2.64  raeburn    81: use Crypt::DES;
                     82: use DynaLoader; # for Crypt::DES version
1.1075.2.128  raeburn    83: use File::Copy();
                     84: use File::Path();
1.117     www        85: 
1.517     raeburn    86: # ---------------------------------------------- Designs
                     87: use vars qw(%defaultdesign);
                     88: 
1.22      www        89: my $readit;
                     90: 
1.517     raeburn    91: 
1.157     matthew    92: ##
                     93: ## Global Variables
                     94: ##
1.46      matthew    95: 
1.643     foxr       96: 
                     97: # ----------------------------------------------- SSI with retries:
                     98: #
                     99: 
                    100: =pod
                    101: 
1.648     raeburn   102: =head1 Server Side include with retries:
1.643     foxr      103: 
                    104: =over 4
                    105: 
1.648     raeburn   106: =item * &ssi_with_retries(resource,retries form)
1.643     foxr      107: 
                    108: Performs an ssi with some number of retries.  Retries continue either
                    109: until the result is ok or until the retry count supplied by the
                    110: caller is exhausted.  
                    111: 
                    112: Inputs:
1.648     raeburn   113: 
                    114: =over 4
                    115: 
1.643     foxr      116: resource   - Identifies the resource to insert.
1.648     raeburn   117: 
1.643     foxr      118: retries    - Count of the number of retries allowed.
1.648     raeburn   119: 
1.643     foxr      120: form       - Hash that identifies the rendering options.
                    121: 
1.648     raeburn   122: =back
                    123: 
                    124: Returns:
                    125: 
                    126: =over 4
                    127: 
1.643     foxr      128: content    - The content of the response.  If retries were exhausted this is empty.
1.648     raeburn   129: 
1.643     foxr      130: response   - The response from the last attempt (which may or may not have been successful.
                    131: 
1.648     raeburn   132: =back
                    133: 
                    134: =back
                    135: 
1.643     foxr      136: =cut
                    137: 
                    138: sub ssi_with_retries {
                    139:     my ($resource, $retries, %form) = @_;
                    140: 
                    141: 
                    142:     my $ok = 0;			# True if we got a good response.
                    143:     my $content;
                    144:     my $response;
                    145: 
                    146:     # Try to get the ssi done. within the retries count:
                    147: 
                    148:     do {
                    149: 	($content, $response) = &Apache::lonnet::ssi($resource, %form);
                    150: 	$ok      = $response->is_success;
1.650     www       151:         if (!$ok) {
                    152:             &Apache::lonnet::logthis("Failed ssi_with_retries on $resource: ".$response->is_success.', '.$response->code.', '.$response->message);
                    153:         }
1.643     foxr      154: 	$retries--;
                    155:     } while (!$ok && ($retries > 0));
                    156: 
                    157:     if (!$ok) {
                    158: 	$content = '';		# On error return an empty content.
                    159:     }
                    160:     return ($content, $response);
                    161: 
                    162: }
                    163: 
                    164: 
                    165: 
1.20      www       166: # ----------------------------------------------- Filetypes/Languages/Copyright
1.12      harris41  167: my %language;
1.124     www       168: my %supported_language;
1.1048    foxr      169: my %latex_language;		# For choosing hyphenation in <transl..>
                    170: my %latex_language_bykey;	# for choosing hyphenation from metadata
1.12      harris41  171: my %cprtag;
1.192     taceyjo1  172: my %scprtag;
1.351     www       173: my %fe; my %fd; my %fm;
1.41      ng        174: my %category_extensions;
1.12      harris41  175: 
1.46      matthew   176: # ---------------------------------------------- Thesaurus variables
1.144     matthew   177: #
                    178: # %Keywords:
                    179: #      A hash used by &keyword to determine if a word is considered a keyword.
                    180: # $thesaurus_db_file 
                    181: #      Scalar containing the full path to the thesaurus database.
1.46      matthew   182: 
                    183: my %Keywords;
                    184: my $thesaurus_db_file;
                    185: 
1.144     matthew   186: #
                    187: # Initialize values from language.tab, copyright.tab, filetypes.tab,
                    188: # thesaurus.tab, and filecategories.tab.
                    189: #
1.18      www       190: BEGIN {
1.46      matthew   191:     # Variable initialization
                    192:     $thesaurus_db_file = $Apache::lonnet::perlvar{'lonTabDir'}."/thesaurus.db";
                    193:     #
1.22      www       194:     unless ($readit) {
1.12      harris41  195: # ------------------------------------------------------------------- languages
                    196:     {
1.158     raeburn   197:         my $langtabfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    198:                                    '/language.tab';
1.1075.2.128  raeburn   199:         if ( open(my $fh,'<',$langtabfile) ) {
1.356     albertel  200:             while (my $line = <$fh>) {
                    201:                 next if ($line=~/^\#/);
                    202:                 chomp($line);
1.1048    foxr      203:                 my ($key,$two,$country,$three,$enc,$val,$sup,$latex)=(split(/\t/,$line));
1.158     raeburn   204:                 $language{$key}=$val.' - '.$enc;
                    205:                 if ($sup) {
                    206:                     $supported_language{$key}=$sup;
                    207:                 }
1.1048    foxr      208: 		if ($latex) {
                    209: 		    $latex_language_bykey{$key} = $latex;
                    210: 		    $latex_language{$two} = $latex;
                    211: 		}
1.158     raeburn   212:             }
                    213:             close($fh);
                    214:         }
1.12      harris41  215:     }
                    216: # ------------------------------------------------------------------ copyrights
                    217:     {
1.158     raeburn   218:         my $copyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    219:                                   '/copyright.tab';
1.1075.2.128  raeburn   220:         if ( open (my $fh,'<',$copyrightfile) ) {
1.356     albertel  221:             while (my $line = <$fh>) {
                    222:                 next if ($line=~/^\#/);
                    223:                 chomp($line);
                    224:                 my ($key,$val)=(split(/\s+/,$line,2));
1.158     raeburn   225:                 $cprtag{$key}=$val;
                    226:             }
                    227:             close($fh);
                    228:         }
1.12      harris41  229:     }
1.351     www       230: # ----------------------------------------------------------- source copyrights
1.192     taceyjo1  231:     {
                    232:         my $sourcecopyrightfile = $Apache::lonnet::perlvar{'lonIncludes'}.
                    233:                                   '/source_copyright.tab';
1.1075.2.128  raeburn   234:         if ( open (my $fh,'<',$sourcecopyrightfile) ) {
1.356     albertel  235:             while (my $line = <$fh>) {
                    236:                 next if ($line =~ /^\#/);
                    237:                 chomp($line);
                    238:                 my ($key,$val)=(split(/\s+/,$line,2));
1.192     taceyjo1  239:                 $scprtag{$key}=$val;
                    240:             }
                    241:             close($fh);
                    242:         }
                    243:     }
1.63      www       244: 
1.517     raeburn   245: # -------------------------------------------------------------- default domain designs
1.63      www       246:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
1.517     raeburn   247:     my $designfile = $designdir.'/default.tab';
1.1075.2.128  raeburn   248:     if ( open (my $fh,'<',$designfile) ) {
1.517     raeburn   249:         while (my $line = <$fh>) {
                    250:             next if ($line =~ /^\#/);
                    251:             chomp($line);
                    252:             my ($key,$val)=(split(/\=/,$line));
                    253:             if ($val) { $defaultdesign{$key}=$val; }
                    254:         }
                    255:         close($fh);
1.63      www       256:     }
                    257: 
1.15      harris41  258: # ------------------------------------------------------------- file categories
                    259:     {
1.158     raeburn   260:         my $categoryfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    261:                                   '/filecategories.tab';
1.1075.2.128  raeburn   262:         if ( open (my $fh,'<',$categoryfile) ) {
1.356     albertel  263: 	    while (my $line = <$fh>) {
                    264: 		next if ($line =~ /^\#/);
                    265: 		chomp($line);
                    266:                 my ($extension,$category)=(split(/\s+/,$line,2));
1.1075.2.119  raeburn   267:                 push(@{$category_extensions{lc($category)}},$extension);
1.158     raeburn   268:             }
                    269:             close($fh);
                    270:         }
                    271: 
1.15      harris41  272:     }
1.12      harris41  273: # ------------------------------------------------------------------ file types
                    274:     {
1.158     raeburn   275:         my $typesfile = $Apache::lonnet::perlvar{'lonTabDir'}.
                    276:                '/filetypes.tab';
1.1075.2.128  raeburn   277:         if ( open (my $fh,'<',$typesfile) ) {
1.356     albertel  278:             while (my $line = <$fh>) {
                    279: 		next if ($line =~ /^\#/);
                    280: 		chomp($line);
                    281:                 my ($ending,$emb,$mime,$descr)=split(/\s+/,$line,4);
1.158     raeburn   282:                 if ($descr ne '') {
                    283:                     $fe{$ending}=lc($emb);
                    284:                     $fd{$ending}=$descr;
1.351     www       285:                     if ($mime ne 'unk') { $fm{$ending}=$mime; }
1.158     raeburn   286:                 }
                    287:             }
                    288:             close($fh);
                    289:         }
1.12      harris41  290:     }
1.22      www       291:     &Apache::lonnet::logthis(
1.705     tempelho  292:              "<span style='color:yellow;'>INFO: Read file types</span>");
1.22      www       293:     $readit=1;
1.46      matthew   294:     }  # end of unless($readit) 
1.32      matthew   295:     
                    296: }
1.112     bowersj2  297: 
1.42      matthew   298: ###############################################################
                    299: ##           HTML and Javascript Helper Functions            ##
                    300: ###############################################################
                    301: 
                    302: =pod 
                    303: 
1.112     bowersj2  304: =head1 HTML and Javascript Functions
1.42      matthew   305: 
1.112     bowersj2  306: =over 4
                    307: 
1.648     raeburn   308: =item * &browser_and_searcher_javascript()
1.112     bowersj2  309: 
                    310: X<browsing, javascript>X<searching, javascript>Returns a string
                    311: containing javascript with two functions, C<openbrowser> and
                    312: C<opensearcher>. Returned string does not contain E<lt>scriptE<gt>
                    313: tags.
1.42      matthew   314: 
1.648     raeburn   315: =item * &openbrowser(formname,elementname,only,omit) [javascript]
1.42      matthew   316: 
                    317: inputs: formname, elementname, only, omit
                    318: 
                    319: formname and elementname indicate the name of the html form and name of
                    320: the element that the results of the browsing selection are to be placed in. 
                    321: 
                    322: Specifying 'only' will restrict the browser to displaying only files
1.185     www       323: with the given extension.  Can be a comma separated list.
1.42      matthew   324: 
                    325: Specifying 'omit' will restrict the browser to NOT displaying files
1.185     www       326: with the given extension.  Can be a comma separated list.
1.42      matthew   327: 
1.648     raeburn   328: =item * &opensearcher(formname,elementname) [javascript]
1.42      matthew   329: 
                    330: Inputs: formname, elementname
                    331: 
                    332: formname and elementname specify the name of the html form and the name
                    333: of the element the selection from the search results will be placed in.
1.542     raeburn   334: 
1.42      matthew   335: =cut
                    336: 
                    337: sub browser_and_searcher_javascript {
1.199     albertel  338:     my ($mode)=@_;
                    339:     if (!defined($mode)) { $mode='edit'; }
1.453     albertel  340:     my $resurl=&escape_single(&lastresurl());
1.42      matthew   341:     return <<END;
1.219     albertel  342: // <!-- BEGIN LON-CAPA Internal
1.50      matthew   343:     var editbrowser = null;
1.135     albertel  344:     function openbrowser(formname,elementname,only,omit,titleelement) {
1.170     www       345:         var url = '$resurl/?';
1.42      matthew   346:         if (editbrowser == null) {
                    347:             url += 'launch=1&';
                    348:         }
                    349:         url += 'catalogmode=interactive&';
1.199     albertel  350:         url += 'mode=$mode&';
1.611     albertel  351:         url += 'inhibitmenu=yes&';
1.42      matthew   352:         url += 'form=' + formname + '&';
                    353:         if (only != null) {
                    354:             url += 'only=' + only + '&';
1.217     albertel  355:         } else {
                    356:             url += 'only=&';
                    357: 	}
1.42      matthew   358:         if (omit != null) {
                    359:             url += 'omit=' + omit + '&';
1.217     albertel  360:         } else {
                    361:             url += 'omit=&';
                    362: 	}
1.135     albertel  363:         if (titleelement != null) {
                    364:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  365:         } else {
                    366: 	    url += 'titleelement=&';
                    367: 	}
1.42      matthew   368:         url += 'element=' + elementname + '';
                    369:         var title = 'Browser';
1.435     albertel  370:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   371:         options += ',width=700,height=600';
                    372:         editbrowser = open(url,title,options,'1');
                    373:         editbrowser.focus();
                    374:     }
                    375:     var editsearcher;
1.135     albertel  376:     function opensearcher(formname,elementname,titleelement) {
1.42      matthew   377:         var url = '/adm/searchcat?';
                    378:         if (editsearcher == null) {
                    379:             url += 'launch=1&';
                    380:         }
                    381:         url += 'catalogmode=interactive&';
1.199     albertel  382:         url += 'mode=$mode&';
1.42      matthew   383:         url += 'form=' + formname + '&';
1.135     albertel  384:         if (titleelement != null) {
                    385:             url += 'titleelement=' + titleelement + '&';
1.217     albertel  386:         } else {
                    387: 	    url += 'titleelement=&';
                    388: 	}
1.42      matthew   389:         url += 'element=' + elementname + '';
                    390:         var title = 'Search';
1.435     albertel  391:         var options = 'scrollbars=1,resizable=1,menubar=0,toolbar=1,location=1';
1.42      matthew   392:         options += ',width=700,height=600';
                    393:         editsearcher = open(url,title,options,'1');
                    394:         editsearcher.focus();
                    395:     }
1.219     albertel  396: // END LON-CAPA Internal -->
1.42      matthew   397: END
1.170     www       398: }
                    399: 
                    400: sub lastresurl {
1.258     albertel  401:     if ($env{'environment.lastresurl'}) {
                    402: 	return $env{'environment.lastresurl'}
1.170     www       403:     } else {
                    404: 	return '/res';
                    405:     }
                    406: }
                    407: 
                    408: sub storeresurl {
                    409:     my $resurl=&Apache::lonnet::clutter(shift);
                    410:     unless ($resurl=~/^\/res/) { return 0; }
                    411:     $resurl=~s/\/$//;
                    412:     &Apache::lonnet::put('environment',{'lastresurl' => $resurl});
1.646     raeburn   413:     &Apache::lonnet::appenv({'environment.lastresurl' => $resurl});
1.170     www       414:     return 1;
1.42      matthew   415: }
                    416: 
1.74      www       417: sub studentbrowser_javascript {
1.111     www       418:    unless (
1.258     albertel  419:             (($env{'request.course.id'}) && 
1.302     albertel  420:              (&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    421: 	      || &Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    422: 					  '/'.$env{'request.course.sec'})
                    423: 	      ))
1.258     albertel  424:          || ($env{'request.role'}=~/^(au|dc|su)/)
1.111     www       425:           ) { return ''; }  
1.74      www       426:    return (<<'ENDSTDBRW');
1.776     bisitz    427: <script type="text/javascript" language="Javascript">
1.824     bisitz    428: // <![CDATA[
1.74      www       429:     var stdeditbrowser;
1.999     www       430:     function openstdbrowser(formname,uname,udom,clicker,roleflag,ignorefilter,courseadvonly) {
1.74      www       431:         var url = '/adm/pickstudent?';
                    432:         var filter;
1.558     albertel  433: 	if (!ignorefilter) {
                    434: 	    eval('filter=document.'+formname+'.'+uname+'.value;');
                    435: 	}
1.74      www       436:         if (filter != null) {
                    437:            if (filter != '') {
                    438:                url += 'filter='+filter+'&';
                    439: 	   }
                    440:         }
                    441:         url += 'form=' + formname + '&unameelement='+uname+
1.999     www       442:                                     '&udomelement='+udom+
                    443:                                     '&clicker='+clicker;
1.111     www       444: 	if (roleflag) { url+="&roles=1"; }
1.793     raeburn   445:         if (courseadvonly) { url+="&courseadvonly=1"; }
1.102     www       446:         var title = 'Student_Browser';
1.74      www       447:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    448:         options += ',width=700,height=600';
                    449:         stdeditbrowser = open(url,title,options,'1');
                    450:         stdeditbrowser.focus();
                    451:     }
1.824     bisitz    452: // ]]>
1.74      www       453: </script>
                    454: ENDSTDBRW
                    455: }
1.42      matthew   456: 
1.1003    www       457: sub resourcebrowser_javascript {
                    458:    unless ($env{'request.course.id'}) { return ''; }
1.1004    www       459:    return (<<'ENDRESBRW');
1.1003    www       460: <script type="text/javascript" language="Javascript">
                    461: // <![CDATA[
                    462:     var reseditbrowser;
1.1004    www       463:     function openresbrowser(formname,reslink) {
1.1005    www       464:         var url = '/adm/pickresource?form='+formname+'&reslink='+reslink;
1.1003    www       465:         var title = 'Resource_Browser';
                    466:         var options = 'scrollbars=1,resizable=1,menubar=0';
1.1005    www       467:         options += ',width=700,height=500';
1.1004    www       468:         reseditbrowser = open(url,title,options,'1');
                    469:         reseditbrowser.focus();
1.1003    www       470:     }
                    471: // ]]>
                    472: </script>
1.1004    www       473: ENDRESBRW
1.1003    www       474: }
                    475: 
1.74      www       476: sub selectstudent_link {
1.999     www       477:    my ($form,$unameele,$udomele,$courseadvonly,$clickerid)=@_;
                    478:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    479:                       &Apache::lonhtmlcommon::entity_encode($unameele)."','".
                    480:                       &Apache::lonhtmlcommon::entity_encode($udomele)."'";
1.258     albertel  481:    if ($env{'request.course.id'}) {  
1.302     albertel  482:        if (!&Apache::lonnet::allowed('srm',$env{'request.course.id'})
                    483: 	   && !&Apache::lonnet::allowed('srm',$env{'request.course.id'}.
                    484: 					'/'.$env{'request.course.sec'})) {
1.111     www       485: 	   return '';
                    486:        }
1.999     www       487:        $callargs.=",'".&Apache::lonhtmlcommon::entity_encode($clickerid)."'";
1.793     raeburn   488:        if ($courseadvonly)  {
                    489:            $callargs .= ",'',1,1";
                    490:        }
                    491:        return '<span class="LC_nobreak">'.
                    492:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    493:               &mt('Select User').'</a></span>';
1.74      www       494:    }
1.258     albertel  495:    if ($env{'request.role'}=~/^(au|dc|su)/) {
1.1012    www       496:        $callargs .= ",'',1"; 
1.793     raeburn   497:        return '<span class="LC_nobreak">'.
                    498:               '<a href="javascript:openstdbrowser('.$callargs.');">'.
                    499:               &mt('Select User').'</a></span>';
1.111     www       500:    }
                    501:    return '';
1.91      www       502: }
                    503: 
1.1004    www       504: sub selectresource_link {
                    505:    my ($form,$reslink,$arg)=@_;
                    506:    
                    507:    my $callargs = "'".&Apache::lonhtmlcommon::entity_encode($form)."','".
                    508:                       &Apache::lonhtmlcommon::entity_encode($reslink)."'";
                    509:    unless ($env{'request.course.id'}) { return $arg; }
                    510:    return '<span class="LC_nobreak">'.
                    511:               '<a href="javascript:openresbrowser('.$callargs.');">'.
                    512:               $arg.'</a></span>';
                    513: }
                    514: 
                    515: 
                    516: 
1.653     raeburn   517: sub authorbrowser_javascript {
                    518:     return <<"ENDAUTHORBRW";
1.776     bisitz    519: <script type="text/javascript" language="JavaScript">
1.824     bisitz    520: // <![CDATA[
1.653     raeburn   521: var stdeditbrowser;
                    522: 
                    523: function openauthorbrowser(formname,udom) {
                    524:     var url = '/adm/pickauthor?';
                    525:     url += 'form='+formname+'&roledom='+udom;
                    526:     var title = 'Author_Browser';
                    527:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    528:     options += ',width=700,height=600';
                    529:     stdeditbrowser = open(url,title,options,'1');
                    530:     stdeditbrowser.focus();
                    531: }
                    532: 
1.824     bisitz    533: // ]]>
1.653     raeburn   534: </script>
                    535: ENDAUTHORBRW
                    536: }
                    537: 
1.91      www       538: sub coursebrowser_javascript {
1.1075.2.31  raeburn   539:     my ($domainfilter,$sec_element,$formname,$role_element,$crstype,
1.1075.2.95  raeburn   540:         $credits_element,$instcode) = @_;
1.932     raeburn   541:     my $wintitle = 'Course_Browser';
1.931     raeburn   542:     if ($crstype eq 'Community') {
1.932     raeburn   543:         $wintitle = 'Community_Browser';
1.909     raeburn   544:     }
1.876     raeburn   545:     my $id_functions = &javascript_index_functions();
                    546:     my $output = '
1.776     bisitz    547: <script type="text/javascript" language="JavaScript">
1.824     bisitz    548: // <![CDATA[
1.468     raeburn   549:     var stdeditbrowser;'."\n";
1.876     raeburn   550: 
                    551:     $output .= <<"ENDSTDBRW";
1.909     raeburn   552:     function opencrsbrowser(formname,uname,udom,desc,extra_element,multflag,type,type_elem) {
1.91      www       553:         var url = '/adm/pickcourse?';
1.895     raeburn   554:         var formid = getFormIdByName(formname);
1.876     raeburn   555:         var domainfilter = getDomainFromSelectbox(formname,udom);
1.128     albertel  556:         if (domainfilter != null) {
                    557:            if (domainfilter != '') {
                    558:                url += 'domainfilter='+domainfilter+'&';
                    559: 	   }
                    560:         }
1.91      www       561:         url += 'form=' + formname + '&cnumelement='+uname+
1.187     albertel  562: 	                            '&cdomelement='+udom+
                    563:                                     '&cnameelement='+desc;
1.468     raeburn   564:         if (extra_element !=null && extra_element != '') {
1.594     raeburn   565:             if (formname == 'rolechoice' || formname == 'studentform') {
1.468     raeburn   566:                 url += '&roleelement='+extra_element;
                    567:                 if (domainfilter == null || domainfilter == '') {
                    568:                     url += '&domainfilter='+extra_element;
                    569:                 }
1.234     raeburn   570:             }
1.468     raeburn   571:             else {
                    572:                 if (formname == 'portform') {
                    573:                     url += '&setroles='+extra_element;
1.800     raeburn   574:                 } else {
                    575:                     if (formname == 'rules') {
                    576:                         url += '&fixeddom='+extra_element; 
                    577:                     }
1.468     raeburn   578:                 }
                    579:             }     
1.230     raeburn   580:         }
1.909     raeburn   581:         if (type != null && type != '') {
                    582:             url += '&type='+type;
                    583:         }
                    584:         if (type_elem != null && type_elem != '') {
                    585:             url += '&typeelement='+type_elem;
                    586:         }
1.872     raeburn   587:         if (formname == 'ccrs') {
                    588:             var ownername = document.forms[formid].ccuname.value;
                    589:             var ownerdom =  document.forms[formid].ccdomain.options[document.forms[formid].ccdomain.selectedIndex].value;
1.1075.2.101  raeburn   590:             url += '&cloner='+ownername+':'+ownerdom;
                    591:             if (type == 'Course') {
                    592:                 url += '&crscode='+document.forms[formid].crscode.value;
                    593:             }
1.1075.2.95  raeburn   594:         }
                    595:         if (formname == 'requestcrs') {
                    596:             url += '&crsdom=$domainfilter&crscode=$instcode';
1.872     raeburn   597:         }
1.293     raeburn   598:         if (multflag !=null && multflag != '') {
                    599:             url += '&multiple='+multflag;
                    600:         }
1.909     raeburn   601:         var title = '$wintitle';
1.91      www       602:         var options = 'scrollbars=1,resizable=1,menubar=0';
                    603:         options += ',width=700,height=600';
                    604:         stdeditbrowser = open(url,title,options,'1');
                    605:         stdeditbrowser.focus();
                    606:     }
1.876     raeburn   607: $id_functions
                    608: ENDSTDBRW
1.1075.2.31  raeburn   609:     if (($sec_element ne '') || ($role_element ne '') || ($credits_element ne '')) {
                    610:         $output .= &setsec_javascript($sec_element,$formname,$role_element,
                    611:                                       $credits_element);
1.876     raeburn   612:     }
                    613:     $output .= '
                    614: // ]]>
                    615: </script>';
                    616:     return $output;
                    617: }
                    618: 
                    619: sub javascript_index_functions {
                    620:     return <<"ENDJS";
                    621: 
                    622: function getFormIdByName(formname) {
                    623:     for (var i=0;i<document.forms.length;i++) {
                    624:         if (document.forms[i].name == formname) {
                    625:             return i;
                    626:         }
                    627:     }
                    628:     return -1;
                    629: }
                    630: 
                    631: function getIndexByName(formid,item) {
                    632:     for (var i=0;i<document.forms[formid].elements.length;i++) {
                    633:         if (document.forms[formid].elements[i].name == item) {
                    634:             return i;
                    635:         }
                    636:     }
                    637:     return -1;
                    638: }
1.468     raeburn   639: 
1.876     raeburn   640: function getDomainFromSelectbox(formname,udom) {
                    641:     var userdom;
                    642:     var formid = getFormIdByName(formname);
                    643:     if (formid > -1) {
                    644:         var domid = getIndexByName(formid,udom);
                    645:         if (domid > -1) {
                    646:             if (document.forms[formid].elements[domid].type == 'select-one') {
                    647:                 userdom=document.forms[formid].elements[domid].options[document.forms[formid].elements[domid].selectedIndex].value;
                    648:             }
                    649:             if (document.forms[formid].elements[domid].type == 'hidden') {
                    650:                 userdom=document.forms[formid].elements[domid].value;
1.468     raeburn   651:             }
                    652:         }
                    653:     }
1.876     raeburn   654:     return userdom;
                    655: }
                    656: 
                    657: ENDJS
1.468     raeburn   658: 
1.876     raeburn   659: }
                    660: 
1.1017    raeburn   661: sub javascript_array_indexof {
1.1018    raeburn   662:     return <<ENDJS;
1.1017    raeburn   663: <script type="text/javascript" language="JavaScript">
                    664: // <![CDATA[
                    665: 
                    666: if (!Array.prototype.indexOf) {
                    667:     Array.prototype.indexOf = function (searchElement /*, fromIndex */ ) {
                    668:         "use strict";
                    669:         if (this === void 0 || this === null) {
                    670:             throw new TypeError();
                    671:         }
                    672:         var t = Object(this);
                    673:         var len = t.length >>> 0;
                    674:         if (len === 0) {
                    675:             return -1;
                    676:         }
                    677:         var n = 0;
                    678:         if (arguments.length > 0) {
                    679:             n = Number(arguments[1]);
                    680:             if (n !== n) { // shortcut for verifying if it's NaN
                    681:                 n = 0;
                    682:             } else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0)) {
                    683:                 n = (n > 0 || -1) * Math.floor(Math.abs(n));
                    684:             }
                    685:         }
                    686:         if (n >= len) {
                    687:             return -1;
                    688:         }
                    689:         var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
                    690:         for (; k < len; k++) {
                    691:             if (k in t && t[k] === searchElement) {
                    692:                 return k;
                    693:             }
                    694:         }
                    695:         return -1;
                    696:     }
                    697: }
                    698: 
                    699: // ]]>
                    700: </script>
                    701: 
                    702: ENDJS
                    703: 
                    704: }
                    705: 
1.876     raeburn   706: sub userbrowser_javascript {
                    707:     my $id_functions = &javascript_index_functions();
                    708:     return <<"ENDUSERBRW";
                    709: 
1.888     raeburn   710: function openuserbrowser(formname,uname,udom,ulast,ufirst,uemail,hideudom,crsdom,caller) {
1.876     raeburn   711:     var url = '/adm/pickuser?';
                    712:     var userdom = getDomainFromSelectbox(formname,udom);
                    713:     if (userdom != null) {
                    714:        if (userdom != '') {
                    715:            url += 'srchdom='+userdom+'&';
                    716:        }
                    717:     }
                    718:     url += 'form=' + formname + '&unameelement='+uname+
                    719:                                 '&udomelement='+udom+
                    720:                                 '&ulastelement='+ulast+
                    721:                                 '&ufirstelement='+ufirst+
                    722:                                 '&uemailelement='+uemail+
1.881     raeburn   723:                                 '&hideudomelement='+hideudom+
                    724:                                 '&coursedom='+crsdom;
1.888     raeburn   725:     if ((caller != null) && (caller != undefined)) {
                    726:         url += '&caller='+caller;
                    727:     }
1.876     raeburn   728:     var title = 'User_Browser';
                    729:     var options = 'scrollbars=1,resizable=1,menubar=0';
                    730:     options += ',width=700,height=600';
                    731:     var stdeditbrowser = open(url,title,options,'1');
                    732:     stdeditbrowser.focus();
                    733: }
                    734: 
1.888     raeburn   735: function fix_domain (formname,udom,origdom,uname) {
1.876     raeburn   736:     var formid = getFormIdByName(formname);
                    737:     if (formid > -1) {
1.888     raeburn   738:         var unameid = getIndexByName(formid,uname);
1.876     raeburn   739:         var domid = getIndexByName(formid,udom);
                    740:         var hidedomid = getIndexByName(formid,origdom);
                    741:         if (hidedomid > -1) {
                    742:             var fixeddom = document.forms[formid].elements[hidedomid].value;
1.888     raeburn   743:             var unameval = document.forms[formid].elements[unameid].value;
                    744:             if ((fixeddom != '') && (fixeddom != undefined) && (fixeddom != null) && (unameval != '') && (unameval != undefined) && (unameval != null)) {
                    745:                 if (domid > -1) {
                    746:                     var slct = document.forms[formid].elements[domid];
                    747:                     if (slct.type == 'select-one') {
                    748:                         var i;
                    749:                         for (i=0;i<slct.length;i++) {
                    750:                             if (slct.options[i].value==fixeddom) { slct.selectedIndex=i; }
                    751:                         }
                    752:                     }
                    753:                     if (slct.type == 'hidden') {
                    754:                         slct.value = fixeddom;
1.876     raeburn   755:                     }
                    756:                 }
1.468     raeburn   757:             }
                    758:         }
                    759:     }
1.876     raeburn   760:     return;
                    761: }
                    762: 
                    763: $id_functions
                    764: ENDUSERBRW
1.468     raeburn   765: }
                    766: 
                    767: sub setsec_javascript {
1.1075.2.31  raeburn   768:     my ($sec_element,$formname,$role_element,$credits_element) = @_;
1.905     raeburn   769:     my (@courserolenames,@communityrolenames,$rolestr,$courserolestr,
                    770:         $communityrolestr);
                    771:     if ($role_element ne '') {
                    772:         my @allroles = ('st','ta','ep','in','ad');
                    773:         foreach my $crstype ('Course','Community') {
                    774:             if ($crstype eq 'Community') {
                    775:                 foreach my $role (@allroles) {
                    776:                     push(@communityrolenames,&Apache::lonnet::plaintext($role,$crstype));
                    777:                 }
                    778:                 push(@communityrolenames,&Apache::lonnet::plaintext('co'));
                    779:             } else {
                    780:                 foreach my $role (@allroles) {
                    781:                     push(@courserolenames,&Apache::lonnet::plaintext($role,$crstype));
                    782:                 }
                    783:                 push(@courserolenames,&Apache::lonnet::plaintext('cc'));
                    784:             }
                    785:         }
                    786:         $rolestr = '"'.join('","',@allroles).'"';
                    787:         $courserolestr = '"'.join('","',@courserolenames).'"';
                    788:         $communityrolestr = '"'.join('","',@communityrolenames).'"';
                    789:     }
1.468     raeburn   790:     my $setsections = qq|
                    791: function setSect(sectionlist) {
1.629     raeburn   792:     var sectionsArray = new Array();
                    793:     if ((sectionlist != '') && (typeof sectionlist != "undefined")) {
                    794:         sectionsArray = sectionlist.split(",");
                    795:     }
1.468     raeburn   796:     var numSections = sectionsArray.length;
                    797:     document.$formname.$sec_element.length = 0;
                    798:     if (numSections == 0) {
                    799:         document.$formname.$sec_element.multiple=false;
                    800:         document.$formname.$sec_element.size=1;
                    801:         document.$formname.$sec_element.options[0] = new Option('No existing sections','',false,false)
                    802:     } else {
                    803:         if (numSections == 1) {
                    804:             document.$formname.$sec_element.multiple=false;
                    805:             document.$formname.$sec_element.size=1;
                    806:             document.$formname.$sec_element.options[0] = new Option('Select','',true,true);
                    807:             document.$formname.$sec_element.options[1] = new Option('No section','',false,false)
                    808:             document.$formname.$sec_element.options[2] = new Option(sectionsArray[0],sectionsArray[0],false,false);
                    809:         } else {
                    810:             for (var i=0; i<numSections; i++) {
                    811:                 document.$formname.$sec_element.options[i] = new Option(sectionsArray[i],sectionsArray[i],false,false)
                    812:             }
                    813:             document.$formname.$sec_element.multiple=true
                    814:             if (numSections < 3) {
                    815:                 document.$formname.$sec_element.size=numSections;
                    816:             } else {
                    817:                 document.$formname.$sec_element.size=3;
                    818:             }
                    819:             document.$formname.$sec_element.options[0].selected = false
                    820:         }
                    821:     }
1.91      www       822: }
1.905     raeburn   823: 
                    824: function setRole(crstype) {
1.468     raeburn   825: |;
1.905     raeburn   826:     if ($role_element eq '') {
                    827:         $setsections .= '    return;
                    828: }
                    829: ';
                    830:     } else {
                    831:         $setsections .= qq|
                    832:     var elementLength = document.$formname.$role_element.length;
                    833:     var allroles = Array($rolestr);
                    834:     var courserolenames = Array($courserolestr);
                    835:     var communityrolenames = Array($communityrolestr);
                    836:     if (elementLength != undefined) {
                    837:         if (document.$formname.$role_element.options[5].value == 'cc') {
                    838:             if (crstype == 'Course') {
                    839:                 return;
                    840:             } else {
                    841:                 allroles[5] = 'co';
                    842:                 for (var i=0; i<6; i++) {
                    843:                     document.$formname.$role_element.options[i].value = allroles[i];
                    844:                     document.$formname.$role_element.options[i].text = communityrolenames[i];
                    845:                 }
                    846:             }
                    847:         } else {
                    848:             if (crstype == 'Community') {
                    849:                 return;
                    850:             } else {
                    851:                 allroles[5] = 'cc';
                    852:                 for (var i=0; i<6; i++) {
                    853:                     document.$formname.$role_element.options[i].value = allroles[i];
                    854:                     document.$formname.$role_element.options[i].text = courserolenames[i];
                    855:                 }
                    856:             }
                    857:         }
                    858:     }
                    859:     return;
                    860: }
                    861: |;
                    862:     }
1.1075.2.31  raeburn   863:     if ($credits_element) {
                    864:         $setsections .= qq|
                    865: function setCredits(defaultcredits) {
                    866:     document.$formname.$credits_element.value = defaultcredits;
                    867:     return;
                    868: }
                    869: |;
                    870:     }
1.468     raeburn   871:     return $setsections;
                    872: }
                    873: 
1.91      www       874: sub selectcourse_link {
1.909     raeburn   875:    my ($form,$unameele,$udomele,$desc,$extra_element,$multflag,$selecttype,
                    876:        $typeelement) = @_;
                    877:    my $type = $selecttype;
1.871     raeburn   878:    my $linktext = &mt('Select Course');
                    879:    if ($selecttype eq 'Community') {
1.909     raeburn   880:        $linktext = &mt('Select Community');
1.906     raeburn   881:    } elsif ($selecttype eq 'Course/Community') {
                    882:        $linktext = &mt('Select Course/Community');
1.909     raeburn   883:        $type = '';
1.1019    raeburn   884:    } elsif ($selecttype eq 'Select') {
                    885:        $linktext = &mt('Select');
                    886:        $type = '';
1.871     raeburn   887:    }
1.787     bisitz    888:    return '<span class="LC_nobreak">'
                    889:          ."<a href='"
                    890:          .'javascript:opencrsbrowser("'.$form.'","'.$unameele
                    891:          .'","'.$udomele.'","'.$desc.'","'.$extra_element
1.909     raeburn   892:          .'","'.$multflag.'","'.$type.'","'.$typeelement.'");'
1.871     raeburn   893:          ."'>".$linktext.'</a>'
1.787     bisitz    894:          .'</span>';
1.74      www       895: }
1.42      matthew   896: 
1.653     raeburn   897: sub selectauthor_link {
                    898:    my ($form,$udom)=@_;
                    899:    return '<a href="javascript:openauthorbrowser('."'$form','$udom'".');">'.
                    900:           &mt('Select Author').'</a>';
                    901: }
                    902: 
1.876     raeburn   903: sub selectuser_link {
1.881     raeburn   904:     my ($form,$unameelem,$domelem,$lastelem,$firstelem,$emailelem,$hdomelem,
1.888     raeburn   905:         $coursedom,$linktext,$caller) = @_;
1.876     raeburn   906:     return '<a href="javascript:openuserbrowser('."'$form','$unameelem','$domelem',".
1.888     raeburn   907:            "'$lastelem','$firstelem','$emailelem','$hdomelem','$coursedom','$caller'".
1.881     raeburn   908:            ');">'.$linktext.'</a>';
1.876     raeburn   909: }
                    910: 
1.273     raeburn   911: sub check_uncheck_jscript {
                    912:     my $jscript = <<"ENDSCRT";
                    913: function checkAll(field) {
                    914:     if (field.length > 0) {
                    915:         for (i = 0; i < field.length; i++) {
1.1075.2.14  raeburn   916:             if (!field[i].disabled) {
                    917:                 field[i].checked = true;
                    918:             }
1.273     raeburn   919:         }
                    920:     } else {
1.1075.2.14  raeburn   921:         if (!field.disabled) {
                    922:             field.checked = true;
                    923:         }
1.273     raeburn   924:     }
                    925: }
                    926:  
                    927: function uncheckAll(field) {
                    928:     if (field.length > 0) {
                    929:         for (i = 0; i < field.length; i++) {
                    930:             field[i].checked = false ;
1.543     albertel  931:         }
                    932:     } else {
1.273     raeburn   933:         field.checked = false ;
                    934:     }
                    935: }
                    936: ENDSCRT
                    937:     return $jscript;
                    938: }
                    939: 
1.656     www       940: sub select_timezone {
1.1075.2.115  raeburn   941:    my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    942:    my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.659     raeburn   943:    if ($includeempty) {
                    944:        $output .= '<option value=""';
                    945:        if (($selected eq '') || ($selected eq 'local')) {
                    946:            $output .= ' selected="selected" ';
                    947:        }
                    948:        $output .= '> </option>';
                    949:    }
1.657     raeburn   950:    my @timezones = DateTime::TimeZone->all_names;
                    951:    foreach my $tzone (@timezones) {
                    952:        $output.= '<option value="'.$tzone.'"';
                    953:        if ($tzone eq $selected) {
                    954:            $output.=' selected="selected"';
                    955:        }
                    956:        $output.=">$tzone</option>\n";
1.656     www       957:    }
                    958:    $output.="</select>";
                    959:    return $output;
                    960: }
1.273     raeburn   961: 
1.687     raeburn   962: sub select_datelocale {
1.1075.2.115  raeburn   963:     my ($name,$selected,$onchange,$includeempty,$disabled)=@_;
                    964:     my $output='<select name="'.$name.'" '.$onchange.$disabled.'>'."\n";
1.687     raeburn   965:     if ($includeempty) {
                    966:         $output .= '<option value=""';
                    967:         if ($selected eq '') {
                    968:             $output .= ' selected="selected" ';
                    969:         }
                    970:         $output .= '> </option>';
                    971:     }
1.1075.2.102  raeburn   972:     my @languages = &Apache::lonlocal::preferred_languages();
1.687     raeburn   973:     my (@possibles,%locale_names);
1.1075.2.102  raeburn   974:     my @locales = DateTime::Locale->ids();
                    975:     foreach my $id (@locales) {
                    976:         if ($id ne '') {
                    977:             my ($en_terr,$native_terr);
                    978:             my $loc = DateTime::Locale->load($id);
                    979:             if (ref($loc)) {
                    980:                 $en_terr = $loc->name();
                    981:                 $native_terr = $loc->native_name();
1.687     raeburn   982:                 if (grep(/^en$/,@languages) || !@languages) {
                    983:                     if ($en_terr ne '') {
                    984:                         $locale_names{$id} = '('.$en_terr.')';
                    985:                     } elsif ($native_terr ne '') {
                    986:                         $locale_names{$id} = $native_terr;
                    987:                     }
                    988:                 } else {
                    989:                     if ($native_terr ne '') {
                    990:                         $locale_names{$id} = $native_terr.' ';
                    991:                     } elsif ($en_terr ne '') {
                    992:                         $locale_names{$id} = '('.$en_terr.')';
                    993:                     }
                    994:                 }
1.1075.2.94  raeburn   995:                 $locale_names{$id} = Encode::encode('UTF-8',$locale_names{$id});
1.1075.2.102  raeburn   996:                 push(@possibles,$id);
1.687     raeburn   997:             }
                    998:         }
                    999:     }
                   1000:     foreach my $item (sort(@possibles)) {
                   1001:         $output.= '<option value="'.$item.'"';
                   1002:         if ($item eq $selected) {
                   1003:             $output.=' selected="selected"';
                   1004:         }
                   1005:         $output.=">$item";
                   1006:         if ($locale_names{$item} ne '') {
1.1075.2.94  raeburn  1007:             $output.='  '.$locale_names{$item};
1.687     raeburn  1008:         }
                   1009:         $output.="</option>\n";
                   1010:     }
                   1011:     $output.="</select>";
                   1012:     return $output;
                   1013: }
                   1014: 
1.792     raeburn  1015: sub select_language {
1.1075.2.115  raeburn  1016:     my ($name,$selected,$includeempty,$noedit) = @_;
1.792     raeburn  1017:     my %langchoices;
                   1018:     if ($includeempty) {
1.1075.2.32  raeburn  1019:         %langchoices = ('' => 'No language preference');
1.792     raeburn  1020:     }
                   1021:     foreach my $id (&languageids()) {
                   1022:         my $code = &supportedlanguagecode($id);
                   1023:         if ($code) {
                   1024:             $langchoices{$code} = &plainlanguagedescription($id);
                   1025:         }
                   1026:     }
1.1075.2.32  raeburn  1027:     %langchoices = &Apache::lonlocal::texthash(%langchoices);
1.1075.2.115  raeburn  1028:     return &select_form($selected,$name,\%langchoices,undef,$noedit);
1.792     raeburn  1029: }
                   1030: 
1.42      matthew  1031: =pod
1.36      matthew  1032: 
1.648     raeburn  1033: =item * &linked_select_forms(...)
1.36      matthew  1034: 
                   1035: linked_select_forms returns a string containing a <script></script> block
                   1036: and html for two <select> menus.  The select menus will be linked in that
                   1037: changing the value of the first menu will result in new values being placed
                   1038: in the second menu.  The values in the select menu will appear in alphabetical
1.609     raeburn  1039: order unless a defined order is provided.
1.36      matthew  1040: 
                   1041: linked_select_forms takes the following ordered inputs:
                   1042: 
                   1043: =over 4
                   1044: 
1.112     bowersj2 1045: =item * $formname, the name of the <form> tag
1.36      matthew  1046: 
1.112     bowersj2 1047: =item * $middletext, the text which appears between the <select> tags
1.36      matthew  1048: 
1.112     bowersj2 1049: =item * $firstdefault, the default value for the first menu
1.36      matthew  1050: 
1.112     bowersj2 1051: =item * $firstselectname, the name of the first <select> tag
1.36      matthew  1052: 
1.112     bowersj2 1053: =item * $secondselectname, the name of the second <select> tag
1.36      matthew  1054: 
1.112     bowersj2 1055: =item * $hashref, a reference to a hash containing the data for the menus.
1.36      matthew  1056: 
1.609     raeburn  1057: =item * $menuorder, the order of values in the first menu
                   1058: 
1.1075.2.31  raeburn  1059: =item * $onchangefirst, additional javascript call to execute for an onchange
                   1060:         event for the first <select> tag
                   1061: 
                   1062: =item * $onchangesecond, additional javascript call to execute for an onchange
                   1063:         event for the second <select> tag
                   1064: 
1.41      ng       1065: =back 
                   1066: 
1.36      matthew  1067: Below is an example of such a hash.  Only the 'text', 'default', and 
                   1068: 'select2' keys must appear as stated.  keys(%menu) are the possible 
                   1069: values for the first select menu.  The text that coincides with the 
1.41      ng       1070: first menu value is given in $menu{$choice1}->{'text'}.  The values 
1.36      matthew  1071: and text for the second menu are given in the hash pointed to by 
                   1072: $menu{$choice1}->{'select2'}.  
                   1073: 
1.112     bowersj2 1074:  my %menu = ( A1 => { text =>"Choice A1" ,
                   1075:                        default => "B3",
                   1076:                        select2 => { 
                   1077:                            B1 => "Choice B1",
                   1078:                            B2 => "Choice B2",
                   1079:                            B3 => "Choice B3",
                   1080:                            B4 => "Choice B4"
1.609     raeburn  1081:                            },
                   1082:                        order => ['B4','B3','B1','B2'],
1.112     bowersj2 1083:                    },
                   1084:                A2 => { text =>"Choice A2" ,
                   1085:                        default => "C2",
                   1086:                        select2 => { 
                   1087:                            C1 => "Choice C1",
                   1088:                            C2 => "Choice C2",
                   1089:                            C3 => "Choice C3"
1.609     raeburn  1090:                            },
                   1091:                        order => ['C2','C1','C3'],
1.112     bowersj2 1092:                    },
                   1093:                A3 => { text =>"Choice A3" ,
                   1094:                        default => "D6",
                   1095:                        select2 => { 
                   1096:                            D1 => "Choice D1",
                   1097:                            D2 => "Choice D2",
                   1098:                            D3 => "Choice D3",
                   1099:                            D4 => "Choice D4",
                   1100:                            D5 => "Choice D5",
                   1101:                            D6 => "Choice D6",
                   1102:                            D7 => "Choice D7"
1.609     raeburn  1103:                            },
                   1104:                        order => ['D4','D3','D2','D1','D7','D6','D5'],
1.112     bowersj2 1105:                    }
                   1106:                );
1.36      matthew  1107: 
                   1108: =cut
                   1109: 
                   1110: sub linked_select_forms {
                   1111:     my ($formname,
                   1112:         $middletext,
                   1113:         $firstdefault,
                   1114:         $firstselectname,
                   1115:         $secondselectname, 
1.609     raeburn  1116:         $hashref,
                   1117:         $menuorder,
1.1075.2.31  raeburn  1118:         $onchangefirst,
                   1119:         $onchangesecond
1.36      matthew  1120:         ) = @_;
                   1121:     my $second = "document.$formname.$secondselectname";
                   1122:     my $first = "document.$formname.$firstselectname";
                   1123:     # output the javascript to do the changing
                   1124:     my $result = '';
1.776     bisitz   1125:     $result.='<script type="text/javascript" language="JavaScript">'."\n";
1.824     bisitz   1126:     $result.="// <![CDATA[\n";
1.36      matthew  1127:     $result.="var select2data = new Object();\n";
                   1128:     $" = '","';
                   1129:     my $debug = '';
                   1130:     foreach my $s1 (sort(keys(%$hashref))) {
                   1131:         $result.="select2data.d_$s1 = new Object();\n";        
                   1132:         $result.="select2data.d_$s1.def = new String('".
                   1133:             $hashref->{$s1}->{'default'}."');\n";
1.609     raeburn  1134:         $result.="select2data.d_$s1.values = new Array(";
1.36      matthew  1135:         my @s2values = sort(keys( %{ $hashref->{$s1}->{'select2'} } ));
1.609     raeburn  1136:         if (ref($hashref->{$s1}->{'order'}) eq 'ARRAY') {
                   1137:             @s2values = @{$hashref->{$s1}->{'order'}};
                   1138:         }
1.36      matthew  1139:         $result.="\"@s2values\");\n";
                   1140:         $result.="select2data.d_$s1.texts = new Array(";        
                   1141:         my @s2texts;
                   1142:         foreach my $value (@s2values) {
1.1075.2.119  raeburn  1143:             push(@s2texts, $hashref->{$s1}->{'select2'}->{$value});
1.36      matthew  1144:         }
                   1145:         $result.="\"@s2texts\");\n";
                   1146:     }
                   1147:     $"=' ';
                   1148:     $result.= <<"END";
                   1149: 
                   1150: function select1_changed() {
                   1151:     // Determine new choice
                   1152:     var newvalue = "d_" + $first.value;
                   1153:     // update select2
                   1154:     var values     = select2data[newvalue].values;
                   1155:     var texts      = select2data[newvalue].texts;
                   1156:     var select2def = select2data[newvalue].def;
                   1157:     var i;
                   1158:     // out with the old
                   1159:     for (i = 0; i < $second.options.length; i++) {
                   1160:         $second.options[i] = null;
                   1161:     }
                   1162:     // in with the nuclear
                   1163:     for (i=0;i<values.length; i++) {
                   1164:         $second.options[i] = new Option(values[i]);
1.143     matthew  1165:         $second.options[i].value = values[i];
1.36      matthew  1166:         $second.options[i].text = texts[i];
                   1167:         if (values[i] == select2def) {
                   1168:             $second.options[i].selected = true;
                   1169:         }
                   1170:     }
                   1171: }
1.824     bisitz   1172: // ]]>
1.36      matthew  1173: </script>
                   1174: END
                   1175:     # output the initial values for the selection lists
1.1075.2.31  raeburn  1176:     $result .= "<select size=\"1\" name=\"$firstselectname\" onchange=\"select1_changed();$onchangefirst\">\n";
1.609     raeburn  1177:     my @order = sort(keys(%{$hashref}));
                   1178:     if (ref($menuorder) eq 'ARRAY') {
                   1179:         @order = @{$menuorder};
                   1180:     }
                   1181:     foreach my $value (@order) {
1.36      matthew  1182:         $result.="    <option value=\"$value\" ";
1.253     albertel 1183:         $result.=" selected=\"selected\" " if ($value eq $firstdefault);
1.119     www      1184:         $result.=">".&mt($hashref->{$value}->{'text'})."</option>\n";
1.36      matthew  1185:     }
                   1186:     $result .= "</select>\n";
                   1187:     my %select2 = %{$hashref->{$firstdefault}->{'select2'}};
                   1188:     $result .= $middletext;
1.1075.2.31  raeburn  1189:     $result .= "<select size=\"1\" name=\"$secondselectname\"";
                   1190:     if ($onchangesecond) {
                   1191:         $result .= ' onchange="'.$onchangesecond.'"';
                   1192:     }
                   1193:     $result .= ">\n";
1.36      matthew  1194:     my $seconddefault = $hashref->{$firstdefault}->{'default'};
1.609     raeburn  1195:     
                   1196:     my @secondorder = sort(keys(%select2));
                   1197:     if (ref($hashref->{$firstdefault}->{'order'}) eq 'ARRAY') {
                   1198:         @secondorder = @{$hashref->{$firstdefault}->{'order'}};
                   1199:     }
                   1200:     foreach my $value (@secondorder) {
1.36      matthew  1201:         $result.="    <option value=\"$value\" ";        
1.253     albertel 1202:         $result.=" selected=\"selected\" " if ($value eq $seconddefault);
1.119     www      1203:         $result.=">".&mt($select2{$value})."</option>\n";
1.36      matthew  1204:     }
                   1205:     $result .= "</select>\n";
                   1206:     #    return $debug;
                   1207:     return $result;
                   1208: }   #  end of sub linked_select_forms {
                   1209: 
1.45      matthew  1210: =pod
1.44      bowersj2 1211: 
1.973     raeburn  1212: =item * &help_open_topic($topic,$text,$stayOnPage,$width,$height,$imgid)
1.44      bowersj2 1213: 
1.112     bowersj2 1214: Returns a string corresponding to an HTML link to the given help
                   1215: $topic, where $topic corresponds to the name of a .tex file in
                   1216: /home/httpd/html/adm/help/tex, with underscores replaced by
                   1217: spaces. 
                   1218: 
                   1219: $text will optionally be linked to the same topic, allowing you to
                   1220: link text in addition to the graphic. If you do not want to link
                   1221: text, but wish to specify one of the later parameters, pass an
                   1222: empty string. 
                   1223: 
                   1224: $stayOnPage is a value that will be interpreted as a boolean. If true,
                   1225: the link will not open a new window. If false, the link will open
                   1226: a new window using Javascript. (Default is false.) 
                   1227: 
                   1228: $width and $height are optional numerical parameters that will
                   1229: override the width and height of the popped up window, which may
1.973     raeburn  1230: be useful for certain help topics with big pictures included.
                   1231: 
                   1232: $imgid is the id of the img tag used for the help icon. This may be
                   1233: used in a javascript call to switch the image src.  See 
                   1234: lonhtmlcommon::htmlareaselectactive() for an example.
1.44      bowersj2 1235: 
                   1236: =cut
                   1237: 
                   1238: sub help_open_topic {
1.973     raeburn  1239:     my ($topic, $text, $stayOnPage, $width, $height, $imgid) = @_;
1.48      bowersj2 1240:     $text = "" if (not defined $text);
1.44      bowersj2 1241:     $stayOnPage = 0 if (not defined $stayOnPage);
1.1033    www      1242:     $width = 500 if (not defined $width);
1.44      bowersj2 1243:     $height = 400 if (not defined $height);
                   1244:     my $filename = $topic;
                   1245:     $filename =~ s/ /_/g;
                   1246: 
1.48      bowersj2 1247:     my $template = "";
                   1248:     my $link;
1.572     banghart 1249:     
1.159     www      1250:     $topic=~s/\W/\_/g;
1.44      bowersj2 1251: 
1.572     banghart 1252:     if (!$stayOnPage) {
1.1075.2.50  raeburn  1253:         if ($env{'browser.mobile'}) {
                   1254: 	    $link = "javascript:openMyModal('/adm/help/${filename}.hlp',$width,$height,'yes');";
                   1255:         } else {
                   1256:             $link = "javascript:void(open('/adm/help/${filename}.hlp', 'Help_for_$topic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1257:         }
1.1037    www      1258:     } elsif ($stayOnPage eq 'popup') {
                   1259:         $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 1260:     } else {
1.48      bowersj2 1261: 	$link = "/adm/help/${filename}.hlp";
                   1262:     }
                   1263: 
                   1264:     # Add the text
1.755     neumanie 1265:     if ($text ne "") {	
1.763     bisitz   1266: 	$template.='<span class="LC_help_open_topic">'
                   1267:                   .'<a target="_top" href="'.$link.'">'
                   1268:                   .$text.'</a>';
1.48      bowersj2 1269:     }
                   1270: 
1.763     bisitz   1271:     # (Always) Add the graphic
1.179     matthew  1272:     my $title = &mt('Online Help');
1.667     raeburn  1273:     my $helpicon=&lonhttpdurl("/adm/help/help.png");
1.973     raeburn  1274:     if ($imgid ne '') {
                   1275:         $imgid = ' id="'.$imgid.'"';
                   1276:     }
1.763     bisitz   1277:     $template.=' <a target="_top" href="'.$link.'" title="'.$title.'">'
                   1278:               .'<img src="'.$helpicon.'" border="0"'
                   1279:               .' alt="'.&mt('Help: [_1]',$topic).'"'
1.973     raeburn  1280:               .' title="'.$title.'" style="vertical-align:middle;"'.$imgid 
1.763     bisitz   1281:               .' /></a>';
                   1282:     if ($text ne "") {	
                   1283:         $template.='</span>';
                   1284:     }
1.44      bowersj2 1285:     return $template;
                   1286: 
1.106     bowersj2 1287: }
                   1288: 
                   1289: # This is a quicky function for Latex cheatsheet editing, since it 
                   1290: # appears in at least four places
                   1291: sub helpLatexCheatsheet {
1.1037    www      1292:     my ($topic,$text,$not_author,$stayOnPage) = @_;
1.732     raeburn  1293:     my $out;
1.106     bowersj2 1294:     my $addOther = '';
1.732     raeburn  1295:     if ($topic) {
1.1037    www      1296: 	$addOther = '<span>'.&help_open_topic($topic,&mt($text),$stayOnPage, undef, 600).'</span> ';
1.763     bisitz   1297:     }
                   1298:     $out = '<span>' # Start cheatsheet
                   1299: 	  .$addOther
                   1300:           .'<span>'
1.1037    www      1301: 	  .&help_open_topic('Greek_Symbols',&mt('Greek Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1302: 	  .'</span> <span>'
1.1037    www      1303: 	  .&help_open_topic('Other_Symbols',&mt('Other Symbols'),$stayOnPage,undef,600)
1.763     bisitz   1304: 	  .'</span>';
1.732     raeburn  1305:     unless ($not_author) {
1.763     bisitz   1306:         $out .= ' <span>'
1.1037    www      1307: 	       .&help_open_topic('Authoring_Output_Tags',&mt('Output Tags'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1308: 	       .'</span> <span>'
1.1075.2.78  raeburn  1309:                .&help_open_topic('Authoring_Multilingual_Problems',&mt('Languages'),$stayOnPage,undef,600)
1.1075.2.71  raeburn  1310:                .'</span>';
1.732     raeburn  1311:     }
1.763     bisitz   1312:     $out .= '</span>'; # End cheatsheet
1.732     raeburn  1313:     return $out;
1.172     www      1314: }
                   1315: 
1.430     albertel 1316: sub general_help {
                   1317:     my $helptopic='Student_Intro';
                   1318:     if ($env{'request.role'}=~/^(ca|au)/) {
                   1319: 	$helptopic='Authoring_Intro';
1.907     raeburn  1320:     } elsif ($env{'request.role'}=~/^(cc|co)/) {
1.430     albertel 1321: 	$helptopic='Course_Coordination_Intro';
1.672     raeburn  1322:     } elsif ($env{'request.role'}=~/^dc/) {
                   1323:         $helptopic='Domain_Coordination_Intro';
1.430     albertel 1324:     }
                   1325:     return $helptopic;
                   1326: }
                   1327: 
                   1328: sub update_help_link {
                   1329:     my ($topic,$component_help,$faq,$bug,$stayOnPage) = @_;
                   1330:     my $origurl = $ENV{'REQUEST_URI'};
                   1331:     $origurl=~s|^/~|/priv/|;
                   1332:     my $timestamp = time;
                   1333:     foreach my $datum (\$topic,\$component_help,\$faq,\$bug,\$origurl) {
                   1334:         $$datum = &escape($$datum);
                   1335:     }
                   1336: 
                   1337:     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";
                   1338:     my $output .= <<"ENDOUTPUT";
                   1339: <script type="text/javascript">
1.824     bisitz   1340: // <![CDATA[
1.430     albertel 1341: banner_link = '$banner_link';
1.824     bisitz   1342: // ]]>
1.430     albertel 1343: </script>
                   1344: ENDOUTPUT
                   1345:     return $output;
                   1346: }
                   1347: 
                   1348: # now just updates the help link and generates a blue icon
1.193     raeburn  1349: sub help_open_menu {
1.430     albertel 1350:     my ($topic,$component_help,$faq,$bug,$stayOnPage,$width,$height,$text) 
1.552     banghart 1351: 	= @_;    
1.949     droeschl 1352:     $stayOnPage = 1;
1.430     albertel 1353:     my $output;
                   1354:     if ($component_help) {
                   1355: 	if (!$text) {
                   1356: 	    $output=&help_open_topic($component_help,undef,$stayOnPage,
                   1357: 				       $width,$height);
                   1358: 	} else {
                   1359: 	    my $help_text;
                   1360: 	    $help_text=&unescape($topic);
                   1361: 	    $output='<table><tr><td>'.
                   1362: 		&help_open_topic($component_help,$help_text,$stayOnPage,
                   1363: 				 $width,$height).'</td></tr></table>';
                   1364: 	}
                   1365:     }
                   1366:     my $banner_link = &update_help_link($topic,$component_help,$faq,$bug,$stayOnPage);
                   1367:     return $output.$banner_link;
                   1368: }
                   1369: 
                   1370: sub top_nav_help {
                   1371:     my ($text) = @_;
1.436     albertel 1372:     $text = &mt($text);
1.1075.2.60  raeburn  1373:     my $stay_on_page;
                   1374:     unless ($env{'environment.remote'} eq 'on') {
                   1375:         $stay_on_page = 1;
                   1376:     }
1.1075.2.61  raeburn  1377:     my ($link,$banner_link);
                   1378:     unless ($env{'request.noversionuri'} =~ m{^/adm/helpmenu}) {
                   1379:         $link = ($stay_on_page) ? "javascript:helpMenu('display')"
                   1380: 	                         : "javascript:helpMenu('open')";
                   1381:         $banner_link = &update_help_link(undef,undef,undef,undef,$stay_on_page);
                   1382:     }
1.201     raeburn  1383:     my $title = &mt('Get help');
1.1075.2.61  raeburn  1384:     if ($link) {
                   1385:         return <<"END";
1.436     albertel 1386: $banner_link
1.1075.2.56  raeburn  1387: <a href="$link" title="$title">$text</a>
1.436     albertel 1388: END
1.1075.2.61  raeburn  1389:     } else {
                   1390:         return '&nbsp;'.$text.'&nbsp;';
                   1391:     }
1.436     albertel 1392: }
                   1393: 
                   1394: sub help_menu_js {
1.1075.2.52  raeburn  1395:     my ($httphost) = @_;
1.949     droeschl 1396:     my $stayOnPage = 1;
1.436     albertel 1397:     my $width = 620;
                   1398:     my $height = 600;
1.430     albertel 1399:     my $helptopic=&general_help();
1.1075.2.52  raeburn  1400:     my $details_link = $httphost.'/adm/help/'.$helptopic.'.hlp';
1.261     albertel 1401:     my $nothing=&Apache::lonhtmlcommon::javascript_nothing();
1.331     albertel 1402:     my $start_page =
                   1403:         &Apache::loncommon::start_page('Help Menu', undef,
                   1404: 				       {'frameset'    => 1,
                   1405: 					'js_ready'    => 1,
1.1075.2.52  raeburn  1406:                                         'use_absolute' => $httphost, 
1.331     albertel 1407: 					'add_entries' => {
                   1408: 					    'border' => '0',
1.579     raeburn  1409: 					    'rows'   => "110,*",},});
1.331     albertel 1410:     my $end_page =
                   1411:         &Apache::loncommon::end_page({'frameset' => 1,
                   1412: 				      'js_ready' => 1,});
                   1413: 
1.436     albertel 1414:     my $template .= <<"ENDTEMPLATE";
                   1415: <script type="text/javascript">
1.877     bisitz   1416: // <![CDATA[
1.253     albertel 1417: // <!-- BEGIN LON-CAPA Internal
1.430     albertel 1418: var banner_link = '';
1.243     raeburn  1419: function helpMenu(target) {
                   1420:     var caller = this;
                   1421:     if (target == 'open') {
                   1422:         var newWindow = null;
                   1423:         try {
1.262     albertel 1424:             newWindow =  window.open($nothing,"helpmenu","HEIGHT=$height,WIDTH=$width,resizable=yes,scrollbars=yes" )
1.243     raeburn  1425:         }
                   1426:         catch(error) {
                   1427:             writeHelp(caller);
                   1428:             return;
                   1429:         }
                   1430:         if (newWindow) {
                   1431:             caller = newWindow;
                   1432:         }
1.193     raeburn  1433:     }
1.243     raeburn  1434:     writeHelp(caller);
                   1435:     return;
                   1436: }
                   1437: function writeHelp(caller) {
1.1075.2.61  raeburn  1438:     caller.document.writeln('$start_page\\n<frame name="bannerframe" src="'+banner_link+'" marginwidth="0" marginheight="0" frameborder="0">\\n');
                   1439:     caller.document.writeln('<frame name="bodyframe" src="$details_link" marginwidth="0" marginheight="0" frameborder="0">\\n$end_page');
                   1440:     caller.document.close();
                   1441:     caller.focus();
1.193     raeburn  1442: }
1.877     bisitz   1443: // END LON-CAPA Internal -->
1.253     albertel 1444: // ]]>
1.436     albertel 1445: </script>
1.193     raeburn  1446: ENDTEMPLATE
                   1447:     return $template;
                   1448: }
                   1449: 
1.172     www      1450: sub help_open_bug {
                   1451:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1452:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1453:     unless ($Apache::lonnet::perlvar{'BugzillaHost'}) { return ''; }
                   1454:     $text = "" if (not defined $text);
                   1455: 	$stayOnPage=1;
1.184     albertel 1456:     $width = 600 if (not defined $width);
                   1457:     $height = 600 if (not defined $height);
1.172     www      1458: 
                   1459:     $topic=~s/\W+/\+/g;
                   1460:     my $link='';
                   1461:     my $template='';
1.379     albertel 1462:     my $url=$Apache::lonnet::perlvar{'BugzillaHost'}.'enter_bug.cgi?product=LON-CAPA&amp;bug_file_loc='.
                   1463: 	&escape($ENV{'REQUEST_URI'}).'&amp;component='.$topic;
1.172     www      1464:     if (!$stayOnPage)
                   1465:     {
                   1466: 	$link = "javascript:void(open('$url', 'Bugzilla', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1467:     }
                   1468:     else
                   1469:     {
                   1470: 	$link = $url;
                   1471:     }
                   1472:     # Add the text
                   1473:     if ($text ne "")
                   1474:     {
                   1475: 	$template .= 
                   1476:   "<table bgcolor='#AA3333' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1477:   "<td bgcolor='#FF5555'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF;font-size:10pt;\">$text</span></a>";
1.172     www      1478:     }
                   1479: 
                   1480:     # Add the graphic
1.179     matthew  1481:     my $title = &mt('Report a Bug');
1.215     albertel 1482:     my $bugicon=&lonhttpdurl("/adm/lonMisc/smallBug.gif");
1.172     www      1483:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1484:  <a target="_top" href="$link" title="$title"><img src="$bugicon" border="0" alt="(Bug: $topic)" /></a>
1.172     www      1485: ENDTEMPLATE
                   1486:     if ($text ne '') { $template.='</td></tr></table>' };
                   1487:     return $template;
                   1488: 
                   1489: }
                   1490: 
                   1491: sub help_open_faq {
                   1492:     my ($topic, $text, $stayOnPage, $width, $height) = @_;
1.258     albertel 1493:     unless ($env{'user.adv'}) { return ''; }
1.172     www      1494:     unless ($Apache::lonnet::perlvar{'FAQHost'}) { return ''; }
                   1495:     $text = "" if (not defined $text);
                   1496: 	$stayOnPage=1;
                   1497:     $width = 350 if (not defined $width);
                   1498:     $height = 400 if (not defined $height);
                   1499: 
                   1500:     $topic=~s/\W+/\+/g;
                   1501:     my $link='';
                   1502:     my $template='';
                   1503:     my $url=$Apache::lonnet::perlvar{'FAQHost'}.'/fom/cache/'.$topic.'.html';
                   1504:     if (!$stayOnPage)
                   1505:     {
                   1506: 	$link = "javascript:void(open('$url', 'FAQ-O-Matic', 'menubar=0,toolbar=1,scrollbars=1,width=$width,height=$height,resizable=yes'))";
                   1507:     }
                   1508:     else
                   1509:     {
                   1510: 	$link = $url;
                   1511:     }
                   1512: 
                   1513:     # Add the text
                   1514:     if ($text ne "")
                   1515:     {
                   1516: 	$template .= 
1.173     www      1517:   "<table bgcolor='#337733' cellspacing='1' cellpadding='1' border='0'><tr>".
1.705     tempelho 1518:   "<td bgcolor='#448844'><a target=\"_top\" href=\"$link\"><span style=\"color:#FFFFFF; font-size:10pt;\">$text</span></a>";
1.172     www      1519:     }
                   1520: 
                   1521:     # Add the graphic
1.179     matthew  1522:     my $title = &mt('View the FAQ');
1.215     albertel 1523:     my $faqicon=&lonhttpdurl("/adm/lonMisc/smallFAQ.gif");
1.172     www      1524:     $template .= <<"ENDTEMPLATE";
1.436     albertel 1525:  <a target="_top" href="$link" title="$title"><img src="$faqicon" border="0" alt="(FAQ: $topic)" /></a>
1.172     www      1526: ENDTEMPLATE
                   1527:     if ($text ne '') { $template.='</td></tr></table>' };
                   1528:     return $template;
                   1529: 
1.44      bowersj2 1530: }
1.37      matthew  1531: 
1.180     matthew  1532: ###############################################################
                   1533: ###############################################################
                   1534: 
1.45      matthew  1535: =pod
                   1536: 
1.648     raeburn  1537: =item * &change_content_javascript():
1.256     matthew  1538: 
                   1539: This and the next function allow you to create small sections of an
                   1540: otherwise static HTML page that you can update on the fly with
                   1541: Javascript, even in Netscape 4.
                   1542: 
                   1543: The Javascript fragment returned by this function (no E<lt>scriptE<gt> tag)
                   1544: must be written to the HTML page once. It will prove the Javascript
                   1545: function "change(name, content)". Calling the change function with the
                   1546: name of the section 
                   1547: you want to update, matching the name passed to C<changable_area>, and
                   1548: the new content you want to put in there, will put the content into
                   1549: that area.
                   1550: 
                   1551: B<Note>: Netscape 4 only reserves enough space for the changable area
                   1552: to contain room for the original contents. You need to "make space"
                   1553: for whatever changes you wish to make, and be B<sure> to check your
                   1554: code in Netscape 4. This feature in Netscape 4 is B<not> powerful;
                   1555: it's adequate for updating a one-line status display, but little more.
                   1556: This script will set the space to 100% width, so you only need to
                   1557: worry about height in Netscape 4.
                   1558: 
                   1559: Modern browsers are much less limiting, and if you can commit to the
                   1560: user not using Netscape 4, this feature may be used freely with
                   1561: pretty much any HTML.
                   1562: 
                   1563: =cut
                   1564: 
                   1565: sub change_content_javascript {
                   1566:     # If we're on Netscape 4, we need to use Layer-based code
1.258     albertel 1567:     if ($env{'browser.type'} eq 'netscape' &&
                   1568: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1569: 	return (<<NETSCAPE4);
                   1570: 	function change(name, content) {
                   1571: 	    doc = document.layers[name+"___escape"].layers[0].document;
                   1572: 	    doc.open();
                   1573: 	    doc.write(content);
                   1574: 	    doc.close();
                   1575: 	}
                   1576: NETSCAPE4
                   1577:     } else {
                   1578: 	# Otherwise, we need to use semi-standards-compliant code
                   1579: 	# (technically, "innerHTML" isn't standard but the equivalent
                   1580: 	# is really scary, and every useful browser supports it
                   1581: 	return (<<DOMBASED);
                   1582: 	function change(name, content) {
                   1583: 	    element = document.getElementById(name);
                   1584: 	    element.innerHTML = content;
                   1585: 	}
                   1586: DOMBASED
                   1587:     }
                   1588: }
                   1589: 
                   1590: =pod
                   1591: 
1.648     raeburn  1592: =item * &changable_area($name,$origContent):
1.256     matthew  1593: 
                   1594: This provides a "changable area" that can be modified on the fly via
                   1595: the Javascript code provided in C<change_content_javascript>. $name is
                   1596: the name you will use to reference the area later; do not repeat the
                   1597: same name on a given HTML page more then once. $origContent is what
                   1598: the area will originally contain, which can be left blank.
                   1599: 
                   1600: =cut
                   1601: 
                   1602: sub changable_area {
                   1603:     my ($name, $origContent) = @_;
                   1604: 
1.258     albertel 1605:     if ($env{'browser.type'} eq 'netscape' &&
                   1606: 	$env{'browser.version'} =~ /^4\./) {
1.256     matthew  1607: 	# If this is netscape 4, we need to use the Layer tag
                   1608: 	return "<ilayer width='100%' id='${name}___escape' overflow='none'><layer width='100%' id='$name' overflow='none'>$origContent</layer></ilayer>";
                   1609:     } else {
                   1610: 	return "<span id='$name'>$origContent</span>";
                   1611:     }
                   1612: }
                   1613: 
                   1614: =pod
                   1615: 
1.648     raeburn  1616: =item * &viewport_geometry_js 
1.590     raeburn  1617: 
                   1618: Provides javascript object (Geometry) which can provide information about the viewport geometry for the client browser.
                   1619: 
                   1620: =cut
                   1621: 
                   1622: 
                   1623: sub viewport_geometry_js { 
                   1624:     return <<"GEOMETRY";
                   1625: var Geometry = {};
                   1626: function init_geometry() {
                   1627:     if (Geometry.init) { return };
                   1628:     Geometry.init=1;
                   1629:     if (window.innerHeight) {
                   1630:         Geometry.getViewportHeight   = function() { return window.innerHeight; };
                   1631:         Geometry.getViewportWidth   = function() { return window.innerWidth; };
                   1632:         Geometry.getHorizontalScroll = function() { return window.pageXOffset; };
                   1633:         Geometry.getVerticalScroll   = function() { return window.pageYOffset; };
                   1634:     }
                   1635:     else if (document.documentElement && document.documentElement.clientHeight) {
                   1636:         Geometry.getViewportHeight =
                   1637:             function() { return document.documentElement.clientHeight; };
                   1638:         Geometry.getViewportWidth =
                   1639:             function() { return document.documentElement.clientWidth; };
                   1640: 
                   1641:         Geometry.getHorizontalScroll =
                   1642:             function() { return document.documentElement.scrollLeft; };
                   1643:         Geometry.getVerticalScroll =
                   1644:             function() { return document.documentElement.scrollTop; };
                   1645:     }
                   1646:     else if (document.body.clientHeight) {
                   1647:         Geometry.getViewportHeight =
                   1648:             function() { return document.body.clientHeight; };
                   1649:         Geometry.getViewportWidth =
                   1650:             function() { return document.body.clientWidth; };
                   1651:         Geometry.getHorizontalScroll =
                   1652:             function() { return document.body.scrollLeft; };
                   1653:         Geometry.getVerticalScroll =
                   1654:             function() { return document.body.scrollTop; };
                   1655:     }
                   1656: }
                   1657: 
                   1658: GEOMETRY
                   1659: }
                   1660: 
                   1661: =pod
                   1662: 
1.648     raeburn  1663: =item * &viewport_size_js()
1.590     raeburn  1664: 
                   1665: 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. 
                   1666: 
                   1667: =cut
                   1668: 
                   1669: sub viewport_size_js {
                   1670:     my $geometry = &viewport_geometry_js();
                   1671:     return <<"DIMS";
                   1672: 
                   1673: $geometry
                   1674: 
                   1675: function getViewportDims(width,height) {
                   1676:     init_geometry();
                   1677:     width.value = Geometry.getViewportWidth();
                   1678:     height.value = Geometry.getViewportHeight();
                   1679:     return;
                   1680: }
                   1681: 
                   1682: DIMS
                   1683: }
                   1684: 
                   1685: =pod
                   1686: 
1.648     raeburn  1687: =item * &resize_textarea_js()
1.565     albertel 1688: 
                   1689: emits the needed javascript to resize a textarea to be as big as possible
                   1690: 
                   1691: creates a function resize_textrea that takes two IDs first should be
                   1692: the id of the element to resize, second should be the id of a div that
                   1693: surrounds everything that comes after the textarea, this routine needs
                   1694: to be attached to the <body> for the onload and onresize events.
                   1695: 
1.648     raeburn  1696: =back
1.565     albertel 1697: 
                   1698: =cut
                   1699: 
                   1700: sub resize_textarea_js {
1.590     raeburn  1701:     my $geometry = &viewport_geometry_js();
1.565     albertel 1702:     return <<"RESIZE";
                   1703:     <script type="text/javascript">
1.824     bisitz   1704: // <![CDATA[
1.590     raeburn  1705: $geometry
1.565     albertel 1706: 
1.588     albertel 1707: function getX(element) {
                   1708:     var x = 0;
                   1709:     while (element) {
                   1710: 	x += element.offsetLeft;
                   1711: 	element = element.offsetParent;
                   1712:     }
                   1713:     return x;
                   1714: }
                   1715: function getY(element) {
                   1716:     var y = 0;
                   1717:     while (element) {
                   1718: 	y += element.offsetTop;
                   1719: 	element = element.offsetParent;
                   1720:     }
                   1721:     return y;
                   1722: }
                   1723: 
                   1724: 
1.565     albertel 1725: function resize_textarea(textarea_id,bottom_id) {
                   1726:     init_geometry();
                   1727:     var textarea        = document.getElementById(textarea_id);
                   1728:     //alert(textarea);
                   1729: 
1.588     albertel 1730:     var textarea_top    = getY(textarea);
1.565     albertel 1731:     var textarea_height = textarea.offsetHeight;
                   1732:     var bottom          = document.getElementById(bottom_id);
1.588     albertel 1733:     var bottom_top      = getY(bottom);
1.565     albertel 1734:     var bottom_height   = bottom.offsetHeight;
                   1735:     var window_height   = Geometry.getViewportHeight();
1.588     albertel 1736:     var fudge           = 23;
1.565     albertel 1737:     var new_height      = window_height-fudge-textarea_top-bottom_height;
                   1738:     if (new_height < 300) {
                   1739: 	new_height = 300;
                   1740:     }
                   1741:     textarea.style.height=new_height+'px';
                   1742: }
1.824     bisitz   1743: // ]]>
1.565     albertel 1744: </script>
                   1745: RESIZE
                   1746: 
                   1747: }
                   1748: 
1.1075.2.112  raeburn  1749: sub colorfuleditor_js {
                   1750:     return <<"COLORFULEDIT"
                   1751: <script type="text/javascript">
                   1752: // <![CDATA[>
                   1753:     function fold_box(curDepth, lastresource){
                   1754: 
                   1755:     // we need a list because there can be several blocks you need to fold in one tag
                   1756:         var block = document.getElementsByName('foldblock_'+curDepth);
                   1757:     // but there is only one folding button per tag
                   1758:         var foldbutton = document.getElementById('folding_btn_'+curDepth);
                   1759: 
                   1760:         if(block.item(0).style.display == 'none'){
                   1761: 
                   1762:             foldbutton.value = '@{[&mt("Hide")]}';
                   1763:             for (i = 0; i < block.length; i++){
                   1764:                 block.item(i).style.display = '';
                   1765:             }
                   1766:         }else{
                   1767: 
                   1768:             foldbutton.value = '@{[&mt("Show")]}';
                   1769:             for (i = 0; i < block.length; i++){
                   1770:                 // block.item(i).style.visibility = 'collapse';
                   1771:                 block.item(i).style.display = 'none';
                   1772:             }
                   1773:         };
                   1774:         saveState(lastresource);
                   1775:     }
                   1776: 
                   1777:     function saveState (lastresource) {
                   1778: 
                   1779:         var tag_list = getTagList();
                   1780:         if(tag_list != null){
                   1781:             var timestamp = new Date().getTime();
                   1782:             var key = lastresource;
                   1783: 
                   1784:             // the value pattern is: 'time;key1,value1;key2,value2; ... '
                   1785:             // starting with timestamp
                   1786:             var value = timestamp+';';
                   1787: 
                   1788:             // building the list of key-value pairs
                   1789:             for(var i = 0; i < tag_list.length; i++){
                   1790:                 value += tag_list[i]+',';
                   1791:                 value += document.getElementsByName(tag_list[i])[0].style.display+';';
                   1792:             }
                   1793: 
                   1794:             // only iterate whole storage if nothing to override
                   1795:             if(localStorage.getItem(key) == null){
                   1796: 
                   1797:                 // prevent storage from growing large
                   1798:                 if(localStorage.length > 50){
                   1799:                     var regex_getTimestamp = /^(?:\d)+;/;
                   1800:                     var oldest_timestamp = regex_getTimestamp.exec(localStorage.key(0));
                   1801:                     var oldest_key;
                   1802: 
                   1803:                     for(var i = 1; i < localStorage.length; i++){
                   1804:                         if (regex_getTimestamp.exec(localStorage.key(i)) < oldest_timestamp) {
                   1805:                             oldest_key = localStorage.key(i);
                   1806:                             oldest_timestamp = regex_getTimestamp.exec(oldest_key);
                   1807:                         }
                   1808:                     }
                   1809:                     localStorage.removeItem(oldest_key);
                   1810:                 }
                   1811:             }
                   1812:             localStorage.setItem(key,value);
                   1813:         }
                   1814:     }
                   1815: 
                   1816:     // restore folding status of blocks (on page load)
                   1817:     function restoreState (lastresource) {
                   1818:         if(localStorage.getItem(lastresource) != null){
                   1819:             var key = lastresource;
                   1820:             var value = localStorage.getItem(key);
                   1821:             var regex_delTimestamp = /^\d+;/;
                   1822: 
                   1823:             value.replace(regex_delTimestamp, '');
                   1824: 
                   1825:             var valueArr = value.split(';');
                   1826:             var pairs;
                   1827:             var elements;
                   1828:             for (var i = 0; i < valueArr.length; i++){
                   1829:                 pairs = valueArr[i].split(',');
                   1830:                 elements = document.getElementsByName(pairs[0]);
                   1831: 
                   1832:                 for (var j = 0; j < elements.length; j++){
                   1833:                     elements[j].style.display = pairs[1];
                   1834:                     if (pairs[1] == "none"){
                   1835:                         var regex_id = /([_\\d]+)\$/;
                   1836:                         regex_id.exec(pairs[0]);
                   1837:                         document.getElementById("folding_btn"+RegExp.\$1).value = "Show";
                   1838:                     }
                   1839:                 }
                   1840:             }
                   1841:         }
                   1842:     }
                   1843: 
                   1844:     function getTagList () {
                   1845: 
                   1846:         var stringToSearch = document.lonhomework.innerHTML;
                   1847: 
                   1848:         var ret = new Array();
                   1849:         var regex_findBlock = /(foldblock_.*?)"/g;
                   1850:         var tag_list = stringToSearch.match(regex_findBlock);
                   1851: 
                   1852:         if(tag_list != null){
                   1853:             for(var i = 0; i < tag_list.length; i++){
                   1854:                 ret.push(tag_list[i].replace(/"/, ''));
                   1855:             }
                   1856:         }
                   1857:         return ret;
                   1858:     }
                   1859: 
                   1860:     function saveScrollPosition (resource) {
                   1861:         var tag_list = getTagList();
                   1862: 
                   1863:         // we dont always want to jump to the first block
                   1864:         // 170 is roughly above the "Problem Editing" header. we just want to save if the user scrolled down further than this
                   1865:         if(\$(window).scrollTop() > 170){
                   1866:             if(tag_list != null){
                   1867:                 var result;
                   1868:                 for(var i = 0; i < tag_list.length; i++){
                   1869:                     if(isElementInViewport(tag_list[i])){
                   1870:                         result += tag_list[i]+';';
                   1871:                     }
                   1872:                 }
                   1873:                 sessionStorage.setItem('anchor_'+resource, result);
                   1874:             }
                   1875:         } else {
                   1876:             // we dont need to save zero, just delete the item to leave everything tidy
                   1877:             sessionStorage.removeItem('anchor_'+resource);
                   1878:         }
                   1879:     }
                   1880: 
                   1881:     function restoreScrollPosition(resource){
                   1882: 
                   1883:         var elem = sessionStorage.getItem('anchor_'+resource);
                   1884:         if(elem != null){
                   1885:             var tag_list = elem.split(';');
                   1886:             var elem_list;
                   1887: 
                   1888:             for(var i = 0; i < tag_list.length; i++){
                   1889:                 elem_list = document.getElementsByName(tag_list[i]);
                   1890: 
                   1891:                 if(elem_list.length > 0){
                   1892:                     elem = elem_list[0];
                   1893:                     break;
                   1894:                 }
                   1895:             }
                   1896:             elem.scrollIntoView();
                   1897:         }
                   1898:     }
                   1899: 
                   1900:     function isElementInViewport(el) {
                   1901: 
                   1902:         // change to last element instead of first
                   1903:         var elem = document.getElementsByName(el);
                   1904:         var rect = elem[0].getBoundingClientRect();
                   1905: 
                   1906:         return (
                   1907:             rect.top >= 0 &&
                   1908:             rect.left >= 0 &&
                   1909:             rect.bottom <= (window.innerHeight || document.documentElement.clientHeight) && /*or $(window).height() */
                   1910:             rect.right <= (window.innerWidth || document.documentElement.clientWidth) /*or $(window).width() */
                   1911:         );
                   1912:     }
                   1913: 
                   1914:     function autosize(depth){
                   1915:         var cmInst = window['cm'+depth];
                   1916:         var fitsizeButton = document.getElementById('fitsize'+depth);
                   1917: 
                   1918:         // is fixed size, switching to dynamic
                   1919:         if (sessionStorage.getItem("autosized_"+depth) == null) {
                   1920:             cmInst.setSize("","auto");
                   1921:             fitsizeButton.value = "@{[&mt('Fixed size')]}";
                   1922:             sessionStorage.setItem("autosized_"+depth, "yes");
                   1923: 
                   1924:         // is dynamic size, switching to fixed
                   1925:         } else {
                   1926:             cmInst.setSize("","300px");
                   1927:             fitsizeButton.value = "@{[&mt('Dynamic size')]}";
                   1928:             sessionStorage.removeItem("autosized_"+depth);
                   1929:         }
                   1930:     }
                   1931: 
                   1932: 
                   1933: 
                   1934: // ]]>
                   1935: </script>
                   1936: COLORFULEDIT
                   1937: }
                   1938: 
                   1939: sub xmleditor_js {
                   1940:     return <<XMLEDIT
                   1941: <script type="text/javascript" src="/adm/jQuery/addons/jquery-scrolltofixed.js"></script>
                   1942: <script type="text/javascript">
                   1943: // <![CDATA[>
                   1944: 
                   1945:     function saveScrollPosition (resource) {
                   1946: 
                   1947:         var scrollPos = \$(window).scrollTop();
                   1948:         sessionStorage.setItem(resource,scrollPos);
                   1949:     }
                   1950: 
                   1951:     function restoreScrollPosition(resource){
                   1952: 
                   1953:         var scrollPos = sessionStorage.getItem(resource);
                   1954:         \$(window).scrollTop(scrollPos);
                   1955:     }
                   1956: 
                   1957:     // unless internet explorer
                   1958:     if (!(window.navigator.appName == "Microsoft Internet Explorer" && (document.documentMode || document.compatMode))){
                   1959: 
                   1960:         \$(document).ready(function() {
                   1961:              \$(".LC_edit_actionbar").scrollToFixed(\{zIndex: 100\});
                   1962:         });
                   1963:     }
                   1964: 
                   1965:     // inserts text at cursor position into codemirror (xml editor only)
                   1966:     function insertText(text){
                   1967:         cm.focus();
                   1968:         var curPos = cm.getCursor();
                   1969:         cm.replaceRange(text.replace(/ESCAPEDSCRIPT/g,'script'), {line: curPos.line,ch: curPos.ch});
                   1970:     }
                   1971: // ]]>
                   1972: </script>
                   1973: XMLEDIT
                   1974: }
                   1975: 
                   1976: sub insert_folding_button {
                   1977:     my $curDepth = $Apache::lonxml::curdepth;
                   1978:     my $lastresource = $env{'request.ambiguous'};
                   1979: 
                   1980:     return "<input type=\"button\" id=\"folding_btn_$curDepth\"
                   1981:             value=\"".&mt('Hide')."\" onclick=\"fold_box('$curDepth','$lastresource')\">";
                   1982: }
                   1983: 
                   1984: 
1.565     albertel 1985: =pod
                   1986: 
1.256     matthew  1987: =head1 Excel and CSV file utility routines
                   1988: 
                   1989: =cut
                   1990: 
                   1991: ###############################################################
                   1992: ###############################################################
                   1993: 
                   1994: =pod
                   1995: 
1.1075.2.56  raeburn  1996: =over 4
                   1997: 
1.648     raeburn  1998: =item * &csv_translate($text) 
1.37      matthew  1999: 
1.185     www      2000: Translate $text to allow it to be output as a 'comma separated values' 
1.37      matthew  2001: format.
                   2002: 
                   2003: =cut
                   2004: 
1.180     matthew  2005: ###############################################################
                   2006: ###############################################################
1.37      matthew  2007: sub csv_translate {
                   2008:     my $text = shift;
                   2009:     $text =~ s/\"/\"\"/g;
1.209     albertel 2010:     $text =~ s/\n/ /g;
1.37      matthew  2011:     return $text;
                   2012: }
1.180     matthew  2013: 
                   2014: ###############################################################
                   2015: ###############################################################
                   2016: 
                   2017: =pod
                   2018: 
1.648     raeburn  2019: =item * &define_excel_formats()
1.180     matthew  2020: 
                   2021: Define some commonly used Excel cell formats.
                   2022: 
                   2023: Currently supported formats:
                   2024: 
                   2025: =over 4
                   2026: 
                   2027: =item header
                   2028: 
                   2029: =item bold
                   2030: 
                   2031: =item h1
                   2032: 
                   2033: =item h2
                   2034: 
                   2035: =item h3
                   2036: 
1.256     matthew  2037: =item h4
                   2038: 
                   2039: =item i
                   2040: 
1.180     matthew  2041: =item date
                   2042: 
                   2043: =back
                   2044: 
                   2045: Inputs: $workbook
                   2046: 
                   2047: Returns: $format, a hash reference.
                   2048: 
1.1057    foxr     2049: 
1.180     matthew  2050: =cut
                   2051: 
                   2052: ###############################################################
                   2053: ###############################################################
                   2054: sub define_excel_formats {
                   2055:     my ($workbook) = @_;
                   2056:     my $format;
                   2057:     $format->{'header'} = $workbook->add_format(bold      => 1, 
                   2058:                                                 bottom    => 1,
                   2059:                                                 align     => 'center');
                   2060:     $format->{'bold'} = $workbook->add_format(bold=>1);
                   2061:     $format->{'h1'}   = $workbook->add_format(bold=>1, size=>18);
                   2062:     $format->{'h2'}   = $workbook->add_format(bold=>1, size=>16);
                   2063:     $format->{'h3'}   = $workbook->add_format(bold=>1, size=>14);
1.255     matthew  2064:     $format->{'h4'}   = $workbook->add_format(bold=>1, size=>12);
1.246     matthew  2065:     $format->{'i'}    = $workbook->add_format(italic=>1);
1.180     matthew  2066:     $format->{'date'} = $workbook->add_format(num_format=>
1.207     matthew  2067:                                             'mm/dd/yyyy hh:mm:ss');
1.180     matthew  2068:     return $format;
                   2069: }
                   2070: 
                   2071: ###############################################################
                   2072: ###############################################################
1.113     bowersj2 2073: 
                   2074: =pod
                   2075: 
1.648     raeburn  2076: =item * &create_workbook()
1.255     matthew  2077: 
                   2078: Create an Excel worksheet.  If it fails, output message on the
                   2079: request object and return undefs.
                   2080: 
                   2081: Inputs: Apache request object
                   2082: 
                   2083: Returns (undef) on failure, 
                   2084:     Excel worksheet object, scalar with filename, and formats 
                   2085:     from &Apache::loncommon::define_excel_formats on success
                   2086: 
                   2087: =cut
                   2088: 
                   2089: ###############################################################
                   2090: ###############################################################
                   2091: sub create_workbook {
                   2092:     my ($r) = @_;
                   2093:         #
                   2094:     # Create the excel spreadsheet
                   2095:     my $filename = '/prtspool/'.
1.258     albertel 2096:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.255     matthew  2097:         time.'_'.rand(1000000000).'.xls';
                   2098:     my $workbook  = Spreadsheet::WriteExcel->new('/home/httpd'.$filename);
                   2099:     if (! defined($workbook)) {
                   2100:         $r->log_error("Error creating excel spreadsheet $filename: $!");
1.928     bisitz   2101:         $r->print(
                   2102:             '<p class="LC_error">'
                   2103:            .&mt('Problems occurred in creating the new Excel file.')
                   2104:            .' '.&mt('This error has been logged.')
                   2105:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2106:            .'</p>'
                   2107:         );
1.255     matthew  2108:         return (undef);
                   2109:     }
                   2110:     #
1.1014    foxr     2111:     $workbook->set_tempdir(LONCAPA::tempdir());
1.255     matthew  2112:     #
                   2113:     my $format = &Apache::loncommon::define_excel_formats($workbook);
                   2114:     return ($workbook,$filename,$format);
                   2115: }
                   2116: 
                   2117: ###############################################################
                   2118: ###############################################################
                   2119: 
                   2120: =pod
                   2121: 
1.648     raeburn  2122: =item * &create_text_file()
1.113     bowersj2 2123: 
1.542     raeburn  2124: Create a file to write to and eventually make available to the user.
1.256     matthew  2125: If file creation fails, outputs an error message on the request object and 
                   2126: return undefs.
1.113     bowersj2 2127: 
1.256     matthew  2128: Inputs: Apache request object, and file suffix
1.113     bowersj2 2129: 
1.256     matthew  2130: Returns (undef) on failure, 
                   2131:     Filehandle and filename on success.
1.113     bowersj2 2132: 
                   2133: =cut
                   2134: 
1.256     matthew  2135: ###############################################################
                   2136: ###############################################################
                   2137: sub create_text_file {
                   2138:     my ($r,$suffix) = @_;
                   2139:     if (! defined($suffix)) { $suffix = 'txt'; };
                   2140:     my $fh;
                   2141:     my $filename = '/prtspool/'.
1.258     albertel 2142:         $env{'user.name'}.'_'.$env{'user.domain'}.'_'.
1.256     matthew  2143:         time.'_'.rand(1000000000).'.'.$suffix;
                   2144:     $fh = Apache::File->new('>/home/httpd'.$filename);
                   2145:     if (! defined($fh)) {
                   2146:         $r->log_error("Couldn't open $filename for output $!");
1.928     bisitz   2147:         $r->print(
                   2148:             '<p class="LC_error">'
                   2149:            .&mt('Problems occurred in creating the output file.')
                   2150:            .' '.&mt('This error has been logged.')
                   2151:            .' '.&mt('Please alert your LON-CAPA administrator.')
                   2152:            .'</p>'
                   2153:         );
1.113     bowersj2 2154:     }
1.256     matthew  2155:     return ($fh,$filename)
1.113     bowersj2 2156: }
                   2157: 
                   2158: 
1.256     matthew  2159: =pod 
1.113     bowersj2 2160: 
                   2161: =back
                   2162: 
                   2163: =cut
1.37      matthew  2164: 
                   2165: ###############################################################
1.33      matthew  2166: ##        Home server <option> list generating code          ##
                   2167: ###############################################################
1.35      matthew  2168: 
1.169     www      2169: # ------------------------------------------
                   2170: 
                   2171: sub domain_select {
                   2172:     my ($name,$value,$multiple)=@_;
                   2173:     my %domains=map { 
1.514     albertel 2174: 	$_ => $_.' '. &Apache::lonnet::domain($_,'description') 
1.512     albertel 2175:     } &Apache::lonnet::all_domains();
1.169     www      2176:     if ($multiple) {
                   2177: 	$domains{''}=&mt('Any domain');
1.550     albertel 2178: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.287     albertel 2179: 	return &multiple_select_form($name,$value,4,\%domains);
1.169     www      2180:     } else {
1.550     albertel 2181: 	$domains{'select_form_order'} = [sort {lc($a) cmp lc($b) } (keys(%domains))];
1.970     raeburn  2182: 	return &select_form($name,$value,\%domains);
1.169     www      2183:     }
                   2184: }
                   2185: 
1.282     albertel 2186: #-------------------------------------------
                   2187: 
                   2188: =pod
                   2189: 
1.519     raeburn  2190: =head1 Routines for form select boxes
                   2191: 
                   2192: =over 4
                   2193: 
1.648     raeburn  2194: =item * &multiple_select_form($name,$value,$size,$hash,$order)
1.282     albertel 2195: 
                   2196: Returns a string containing a <select> element int multiple mode
                   2197: 
                   2198: 
                   2199: Args:
                   2200:   $name - name of the <select> element
1.506     raeburn  2201:   $value - scalar or array ref of values that should already be selected
1.282     albertel 2202:   $size - number of rows long the select element is
1.283     albertel 2203:   $hash - the elements should be 'option' => 'shown text'
1.282     albertel 2204:           (shown text should already have been &mt())
1.506     raeburn  2205:   $order - (optional) array ref of the order to show the elements in
1.283     albertel 2206: 
1.282     albertel 2207: =cut
                   2208: 
                   2209: #-------------------------------------------
1.169     www      2210: sub multiple_select_form {
1.284     albertel 2211:     my ($name,$value,$size,$hash,$order)=@_;
1.169     www      2212:     my %selected = map { $_ => 1 } ref($value)?@{$value}:($value);
                   2213:     my $output='';
1.191     matthew  2214:     if (! defined($size)) {
                   2215:         $size = 4;
1.283     albertel 2216:         if (scalar(keys(%$hash))<4) {
                   2217:             $size = scalar(keys(%$hash));
1.191     matthew  2218:         }
                   2219:     }
1.734     bisitz   2220:     $output.="\n".'<select name="'.$name.'" size="'.$size.'" multiple="multiple">';
1.501     banghart 2221:     my @order;
1.506     raeburn  2222:     if (ref($order) eq 'ARRAY')  {
                   2223:         @order = @{$order};
                   2224:     } else {
                   2225:         @order = sort(keys(%$hash));
1.501     banghart 2226:     }
                   2227:     if (exists($$hash{'select_form_order'})) {
                   2228:         @order = @{$$hash{'select_form_order'}};
                   2229:     }
                   2230:         
1.284     albertel 2231:     foreach my $key (@order) {
1.356     albertel 2232:         $output.='<option value="'.&HTML::Entities::encode($key,'"<>&').'" ';
1.284     albertel 2233:         $output.='selected="selected" ' if ($selected{$key});
                   2234:         $output.='>'.$hash->{$key}."</option>\n";
1.169     www      2235:     }
                   2236:     $output.="</select>\n";
                   2237:     return $output;
                   2238: }
                   2239: 
1.88      www      2240: #-------------------------------------------
                   2241: 
                   2242: =pod
                   2243: 
1.1075.2.115  raeburn  2244: =item * &select_form($defdom,$name,$hashref,$onchange,$readonly)
1.88      www      2245: 
                   2246: Returns a string containing a <select name='$name' size='1'> form to 
1.970     raeburn  2247: allow a user to select options from a ref to a hash containing:
                   2248: option_name => displayed text. An optional $onchange can include
1.1075.2.115  raeburn  2249: a javascript onchange item, e.g., onchange="this.form.submit();".
                   2250: An optional arg -- $readonly -- if true will cause the select form
                   2251: to be disabled, e.g., for the case where an instructor has a section-
                   2252: specific role, and is viewing/modifying parameters.  
1.970     raeburn  2253: 
1.88      www      2254: See lonrights.pm for an example invocation and use.
                   2255: 
                   2256: =cut
                   2257: 
                   2258: #-------------------------------------------
                   2259: sub select_form {
1.1075.2.115  raeburn  2260:     my ($def,$name,$hashref,$onchange,$readonly) = @_;
1.970     raeburn  2261:     return unless (ref($hashref) eq 'HASH');
                   2262:     if ($onchange) {
                   2263:         $onchange = ' onchange="'.$onchange.'"';
                   2264:     }
1.1075.2.129  raeburn  2265:     my $disabled;
                   2266:     if ($readonly) {
                   2267:         $disabled = ' disabled="disabled"';
                   2268:     }
                   2269:     my $selectform = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.128     albertel 2270:     my @keys;
1.970     raeburn  2271:     if (exists($hashref->{'select_form_order'})) {
                   2272: 	@keys=@{$hashref->{'select_form_order'}};
1.128     albertel 2273:     } else {
1.970     raeburn  2274: 	@keys=sort(keys(%{$hashref}));
1.128     albertel 2275:     }
1.356     albertel 2276:     foreach my $key (@keys) {
                   2277:         $selectform.=
                   2278: 	    '<option value="'.&HTML::Entities::encode($key,'"<>&').'" '.
                   2279:             ($key eq $def ? 'selected="selected" ' : '').
1.970     raeburn  2280:                 ">".$hashref->{$key}."</option>\n";
1.88      www      2281:     }
                   2282:     $selectform.="</select>";
                   2283:     return $selectform;
                   2284: }
                   2285: 
1.475     www      2286: # For display filters
                   2287: 
                   2288: sub display_filter {
1.1074    raeburn  2289:     my ($context) = @_;
1.475     www      2290:     if (!$env{'form.show'}) { $env{'form.show'}=10; }
1.477     www      2291:     if (!$env{'form.displayfilter'}) { $env{'form.displayfilter'}='currentfolder'; }
1.1074    raeburn  2292:     my $phraseinput = 'hidden';
                   2293:     my $includeinput = 'hidden';
                   2294:     my ($checked,$includetypestext);
                   2295:     if ($env{'form.displayfilter'} eq 'containing') {
                   2296:         $phraseinput = 'text'; 
                   2297:         if ($context eq 'parmslog') {
                   2298:             $includeinput = 'checkbox';
                   2299:             if ($env{'form.includetypes'}) {
                   2300:                 $checked = ' checked="checked"';
                   2301:             }
                   2302:             $includetypestext = &mt('Include parameter types');
                   2303:         }
                   2304:     } else {
                   2305:         $includetypestext = '&nbsp;';
                   2306:     }
                   2307:     my ($additional,$secondid,$thirdid);
                   2308:     if ($context eq 'parmslog') {
                   2309:         $additional = 
                   2310:             '<label><input type="'.$includeinput.'" name="includetypes"'. 
                   2311:             $checked.' name="includetypes" value="1" id="includetypes" />'.
                   2312:             '&nbsp;<span id="includetypestext">'.$includetypestext.'</span>'.
                   2313:             '</label>';
                   2314:         $secondid = 'includetypes';
                   2315:         $thirdid = 'includetypestext';
                   2316:     }
                   2317:     my $onchange = "javascript:toggleHistoryOptions(this,'containingphrase','$context',
                   2318:                                                     '$secondid','$thirdid')";
                   2319:     return '<span class="LC_nobreak"><label>'.&mt('Records: [_1]',
1.475     www      2320: 			       &Apache::lonmeta::selectbox('show',$env{'form.show'},undef,
                   2321: 							   (&mt('all'),10,20,50,100,1000,10000))).
1.714     bisitz   2322: 	   '</label></span> <span class="LC_nobreak">'.
1.1074    raeburn  2323:            &mt('Filter: [_1]',
1.477     www      2324: 	   &select_form($env{'form.displayfilter'},
                   2325: 			'displayfilter',
1.970     raeburn  2326: 			{'currentfolder' => 'Current folder/page',
1.477     www      2327: 			 'containing' => 'Containing phrase',
1.1074    raeburn  2328: 			 'none' => 'None'},$onchange)).'&nbsp;'.
                   2329: 			 '<input type="'.$phraseinput.'" name="containingphrase" id="containingphrase" size="30" value="'.
                   2330:                          &HTML::Entities::encode($env{'form.containingphrase'}).
                   2331:                          '" />'.$additional;
                   2332: }
                   2333: 
                   2334: sub display_filter_js {
                   2335:     my $includetext = &mt('Include parameter types');
                   2336:     return <<"ENDJS";
                   2337:   
                   2338: function toggleHistoryOptions(setter,firstid,context,secondid,thirdid) {
                   2339:     var firstType = 'hidden';
                   2340:     if (setter.options[setter.selectedIndex].value == 'containing') {
                   2341:         firstType = 'text';
                   2342:     }
                   2343:     firstObject = document.getElementById(firstid);
                   2344:     if (typeof(firstObject) == 'object') {
                   2345:         if (firstObject.type != firstType) {
                   2346:             changeInputType(firstObject,firstType);
                   2347:         }
                   2348:     }
                   2349:     if (context == 'parmslog') {
                   2350:         var secondType = 'hidden';
                   2351:         if (firstType == 'text') {
                   2352:             secondType = 'checkbox';
                   2353:         }
                   2354:         secondObject = document.getElementById(secondid);  
                   2355:         if (typeof(secondObject) == 'object') {
                   2356:             if (secondObject.type != secondType) {
                   2357:                 changeInputType(secondObject,secondType);
                   2358:             }
                   2359:         }
                   2360:         var textItem = document.getElementById(thirdid);
                   2361:         var currtext = textItem.innerHTML;
                   2362:         var newtext;
                   2363:         if (firstType == 'text') {
                   2364:             newtext = '$includetext';
                   2365:         } else {
                   2366:             newtext = '&nbsp;';
                   2367:         }
                   2368:         if (currtext != newtext) {
                   2369:             textItem.innerHTML = newtext;
                   2370:         }
                   2371:     }
                   2372:     return;
                   2373: }
                   2374: 
                   2375: function changeInputType(oldObject,newType) {
                   2376:     var newObject = document.createElement('input');
                   2377:     newObject.type = newType;
                   2378:     if (oldObject.size) {
                   2379:         newObject.size = oldObject.size;
                   2380:     }
                   2381:     if (oldObject.value) {
                   2382:         newObject.value = oldObject.value;
                   2383:     }
                   2384:     if (oldObject.name) {
                   2385:         newObject.name = oldObject.name;
                   2386:     }
                   2387:     if (oldObject.id) {
                   2388:         newObject.id = oldObject.id;
                   2389:     }
                   2390:     oldObject.parentNode.replaceChild(newObject,oldObject);
                   2391:     return;
                   2392: }
                   2393: 
                   2394: ENDJS
1.475     www      2395: }
                   2396: 
1.167     www      2397: sub gradeleveldescription {
                   2398:     my $gradelevel=shift;
                   2399:     my %gradelevels=(0 => 'Not specified',
                   2400: 		     1 => 'Grade 1',
                   2401: 		     2 => 'Grade 2',
                   2402: 		     3 => 'Grade 3',
                   2403: 		     4 => 'Grade 4',
                   2404: 		     5 => 'Grade 5',
                   2405: 		     6 => 'Grade 6',
                   2406: 		     7 => 'Grade 7',
                   2407: 		     8 => 'Grade 8',
                   2408: 		     9 => 'Grade 9',
                   2409: 		     10 => 'Grade 10',
                   2410: 		     11 => 'Grade 11',
                   2411: 		     12 => 'Grade 12',
                   2412: 		     13 => 'Grade 13',
                   2413: 		     14 => '100 Level',
                   2414: 		     15 => '200 Level',
                   2415: 		     16 => '300 Level',
                   2416: 		     17 => '400 Level',
                   2417: 		     18 => 'Graduate Level');
                   2418:     return &mt($gradelevels{$gradelevel});
                   2419: }
                   2420: 
1.163     www      2421: sub select_level_form {
                   2422:     my ($deflevel,$name)=@_;
                   2423:     unless ($deflevel) { $deflevel=0; }
1.167     www      2424:     my $selectform = "<select name=\"$name\" size=\"1\">\n";
                   2425:     for (my $i=0; $i<=18; $i++) {
                   2426:         $selectform.="<option value=\"$i\" ".
1.253     albertel 2427:             ($i==$deflevel ? 'selected="selected" ' : '').
1.167     www      2428:                 ">".&gradeleveldescription($i)."</option>\n";
                   2429:     }
                   2430:     $selectform.="</select>";
                   2431:     return $selectform;
1.163     www      2432: }
1.167     www      2433: 
1.35      matthew  2434: #-------------------------------------------
                   2435: 
1.45      matthew  2436: =pod
                   2437: 
1.1075.2.115  raeburn  2438: =item * &select_dom_form($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled)
1.35      matthew  2439: 
                   2440: Returns a string containing a <select name='$name' size='1'> form to 
                   2441: allow a user to select the domain to preform an operation in.  
                   2442: See loncreateuser.pm for an example invocation and use.
                   2443: 
1.90      www      2444: If the $includeempty flag is set, it also includes an empty choice ("no domain
                   2445: selected");
                   2446: 
1.743     raeburn  2447: If the $showdomdesc flag is set, the domain name is followed by the domain description.
                   2448: 
1.910     raeburn  2449: 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.
                   2450: 
1.1075.2.36  raeburn  2451: The optional $incdoms is a reference to an array of domains which will be the only available options.
                   2452: 
1.1075.2.115  raeburn  2453: The optional $excdoms is a reference to an array of domains which will be excluded from the available options.
                   2454: 
                   2455: The optional $disabled argument, if true, adds the disabled attribute to the select tag. 
1.563     raeburn  2456: 
1.35      matthew  2457: =cut
                   2458: 
                   2459: #-------------------------------------------
1.34      matthew  2460: sub select_dom_form {
1.1075.2.115  raeburn  2461:     my ($defdom,$name,$includeempty,$showdomdesc,$onchange,$incdoms,$excdoms,$disabled) = @_;
1.872     raeburn  2462:     if ($onchange) {
1.874     raeburn  2463:         $onchange = ' onchange="'.$onchange.'"';
1.743     raeburn  2464:     }
1.1075.2.115  raeburn  2465:     if ($disabled) {
                   2466:         $disabled = ' disabled="disabled"';
                   2467:     }
1.1075.2.36  raeburn  2468:     my (@domains,%exclude);
1.910     raeburn  2469:     if (ref($incdoms) eq 'ARRAY') {
                   2470:         @domains = sort {lc($a) cmp lc($b)} (@{$incdoms});
                   2471:     } else {
                   2472:         @domains = sort {lc($a) cmp lc($b)} (&Apache::lonnet::all_domains());
                   2473:     }
1.90      www      2474:     if ($includeempty) { @domains=('',@domains); }
1.1075.2.36  raeburn  2475:     if (ref($excdoms) eq 'ARRAY') {
                   2476:         map { $exclude{$_} = 1; } @{$excdoms};
                   2477:     }
1.1075.2.115  raeburn  2478:     my $selectdomain = "<select name=\"$name\" size=\"1\"$onchange$disabled>\n";
1.356     albertel 2479:     foreach my $dom (@domains) {
1.1075.2.36  raeburn  2480:         next if ($exclude{$dom});
1.356     albertel 2481:         $selectdomain.="<option value=\"$dom\" ".
1.563     raeburn  2482:             ($dom eq $defdom ? 'selected="selected" ' : '').'>'.$dom;
                   2483:         if ($showdomdesc) {
                   2484:             if ($dom ne '') {
                   2485:                 my $domdesc = &Apache::lonnet::domain($dom,'description');
                   2486:                 if ($domdesc ne '') {
                   2487:                     $selectdomain .= ' ('.$domdesc.')';
                   2488:                 }
                   2489:             } 
                   2490:         }
                   2491:         $selectdomain .= "</option>\n";
1.34      matthew  2492:     }
                   2493:     $selectdomain.="</select>";
                   2494:     return $selectdomain;
                   2495: }
                   2496: 
1.35      matthew  2497: #-------------------------------------------
                   2498: 
1.45      matthew  2499: =pod
                   2500: 
1.648     raeburn  2501: =item * &home_server_form_item($domain,$name,$defaultflag)
1.35      matthew  2502: 
1.586     raeburn  2503: input: 4 arguments (two required, two optional) - 
                   2504:     $domain - domain of new user
                   2505:     $name - name of form element
                   2506:     $default - Value of 'default' causes a default item to be first 
                   2507:                             option, and selected by default. 
                   2508:     $hide - Value of 'hide' causes hiding of the name of the server, 
                   2509:                             if 1 server found, or default, if 0 found.
1.594     raeburn  2510: output: returns 2 items: 
1.586     raeburn  2511: (a) form element which contains either:
                   2512:    (i) <select name="$name">
                   2513:         <option value="$hostid1">$hostid $servers{$hostid}</option>
                   2514:         <option value="$hostid2">$hostid $servers{$hostid}</option>       
                   2515:        </select>
                   2516:        form item if there are multiple library servers in $domain, or
                   2517:    (ii) an <input type="hidden" name="$name" value="$hostid" /> form item 
                   2518:        if there is only one library server in $domain.
                   2519: 
                   2520: (b) number of library servers found.
                   2521: 
                   2522: See loncreateuser.pm for example of use.
1.35      matthew  2523: 
                   2524: =cut
                   2525: 
                   2526: #-------------------------------------------
1.586     raeburn  2527: sub home_server_form_item {
                   2528:     my ($domain,$name,$default,$hide) = @_;
1.513     albertel 2529:     my %servers = &Apache::lonnet::get_servers($domain,'library');
1.586     raeburn  2530:     my $result;
                   2531:     my $numlib = keys(%servers);
                   2532:     if ($numlib > 1) {
                   2533:         $result .= '<select name="'.$name.'" />'."\n";
                   2534:         if ($default) {
1.804     bisitz   2535:             $result .= '<option value="default" selected="selected">'.&mt('default').
1.586     raeburn  2536:                        '</option>'."\n";
                   2537:         }
                   2538:         foreach my $hostid (sort(keys(%servers))) {
                   2539:             $result.= '<option value="'.$hostid.'">'.
                   2540: 	              $hostid.' '.$servers{$hostid}."</option>\n";
                   2541:         }
                   2542:         $result .= '</select>'."\n";
                   2543:     } elsif ($numlib == 1) {
                   2544:         my $hostid;
                   2545:         foreach my $item (keys(%servers)) {
                   2546:             $hostid = $item;
                   2547:         }
                   2548:         $result .= '<input type="hidden" name="'.$name.'" value="'.
                   2549:                    $hostid.'" />';
                   2550:                    if (!$hide) {
                   2551:                        $result .= $hostid.' '.$servers{$hostid};
                   2552:                    }
                   2553:                    $result .= "\n";
                   2554:     } elsif ($default) {
                   2555:         $result .= '<input type="hidden" name="'.$name.
                   2556:                    '" value="default" />';
                   2557:                    if (!$hide) {
                   2558:                        $result .= &mt('default');
                   2559:                    }
                   2560:                    $result .= "\n";
1.33      matthew  2561:     }
1.586     raeburn  2562:     return ($result,$numlib);
1.33      matthew  2563: }
1.112     bowersj2 2564: 
                   2565: =pod
                   2566: 
1.534     albertel 2567: =back 
                   2568: 
1.112     bowersj2 2569: =cut
1.87      matthew  2570: 
                   2571: ###############################################################
1.112     bowersj2 2572: ##                  Decoding User Agent                      ##
1.87      matthew  2573: ###############################################################
                   2574: 
                   2575: =pod
                   2576: 
1.112     bowersj2 2577: =head1 Decoding the User Agent
                   2578: 
                   2579: =over 4
                   2580: 
                   2581: =item * &decode_user_agent()
1.87      matthew  2582: 
                   2583: Inputs: $r
                   2584: 
                   2585: Outputs:
                   2586: 
                   2587: =over 4
                   2588: 
1.112     bowersj2 2589: =item * $httpbrowser
1.87      matthew  2590: 
1.112     bowersj2 2591: =item * $clientbrowser
1.87      matthew  2592: 
1.112     bowersj2 2593: =item * $clientversion
1.87      matthew  2594: 
1.112     bowersj2 2595: =item * $clientmathml
1.87      matthew  2596: 
1.112     bowersj2 2597: =item * $clientunicode
1.87      matthew  2598: 
1.112     bowersj2 2599: =item * $clientos
1.87      matthew  2600: 
1.1075.2.42  raeburn  2601: =item * $clientmobile
                   2602: 
                   2603: =item * $clientinfo
                   2604: 
1.1075.2.77  raeburn  2605: =item * $clientosversion
                   2606: 
1.87      matthew  2607: =back
                   2608: 
1.157     matthew  2609: =back 
                   2610: 
1.87      matthew  2611: =cut
                   2612: 
                   2613: ###############################################################
                   2614: ###############################################################
                   2615: sub decode_user_agent {
1.247     albertel 2616:     my ($r)=@_;
1.87      matthew  2617:     my @browsertype=split(/\&/,$Apache::lonnet::perlvar{"lonBrowsDet"});
                   2618:     my %mathcap=split(/\&/,$$Apache::lonnet::perlvar{"lonMathML"});
                   2619:     my $httpbrowser=$ENV{"HTTP_USER_AGENT"};
1.247     albertel 2620:     if (!$httpbrowser && $r) { $httpbrowser=$r->header_in('User-Agent'); }
1.87      matthew  2621:     my $clientbrowser='unknown';
                   2622:     my $clientversion='0';
                   2623:     my $clientmathml='';
                   2624:     my $clientunicode='0';
1.1075.2.42  raeburn  2625:     my $clientmobile=0;
1.1075.2.77  raeburn  2626:     my $clientosversion='';
1.87      matthew  2627:     for (my $i=0;$i<=$#browsertype;$i++) {
1.1075.2.76  raeburn  2628:         my ($bname,$match,$notmatch,$vreg,$minv,$univ)=split(/\%/,$browsertype[$i]);
1.87      matthew  2629: 	if (($httpbrowser=~/$match/i)  && ($httpbrowser!~/$notmatch/i)) {
                   2630: 	    $clientbrowser=$bname;
                   2631:             $httpbrowser=~/$vreg/i;
                   2632: 	    $clientversion=$1;
                   2633:             $clientmathml=($clientversion>=$minv);
                   2634:             $clientunicode=($clientversion>=$univ);
                   2635: 	}
                   2636:     }
                   2637:     my $clientos='unknown';
1.1075.2.42  raeburn  2638:     my $clientinfo;
1.87      matthew  2639:     if (($httpbrowser=~/linux/i) ||
                   2640:         ($httpbrowser=~/unix/i) ||
                   2641:         ($httpbrowser=~/ux/i) ||
                   2642:         ($httpbrowser=~/solaris/i)) { $clientos='unix'; }
                   2643:     if (($httpbrowser=~/vax/i) ||
                   2644:         ($httpbrowser=~/vms/i)) { $clientos='vms'; }
                   2645:     if ($httpbrowser=~/next/i) { $clientos='next'; }
                   2646:     if (($httpbrowser=~/mac/i) ||
                   2647:         ($httpbrowser=~/powerpc/i)) { $clientos='mac'; }
1.1075.2.77  raeburn  2648:     if ($httpbrowser=~/win/i) {
                   2649:         $clientos='win';
                   2650:         if ($httpbrowser =~/Windows\s+NT\s+(\d+\.\d+)/i) {
                   2651:             $clientosversion = $1;
                   2652:         }
                   2653:     }
1.87      matthew  2654:     if ($httpbrowser=~/embed/i) { $clientos='pda'; }
1.1075.2.42  raeburn  2655:     if ($httpbrowser=~/(Android|iPod|iPad|iPhone|webOS|Blackberry|Windows Phone|Opera m(?:ob|in)|Fennec)/i) {
                   2656:         $clientmobile=lc($1);
                   2657:     }
                   2658:     if ($httpbrowser=~ m{Firefox/(\d+\.\d+)}) {
                   2659:         $clientinfo = 'firefox-'.$1;
                   2660:     } elsif ($httpbrowser=~ m{chromeframe/(\d+\.\d+)\.}) {
                   2661:         $clientinfo = 'chromeframe-'.$1;
                   2662:     }
1.87      matthew  2663:     return ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,
1.1075.2.77  raeburn  2664:             $clientunicode,$clientos,$clientmobile,$clientinfo,
                   2665:             $clientosversion);
1.87      matthew  2666: }
                   2667: 
1.32      matthew  2668: ###############################################################
                   2669: ##    Authentication changing form generation subroutines    ##
                   2670: ###############################################################
                   2671: ##
                   2672: ## All of the authform_xxxxxxx subroutines take their inputs in a
                   2673: ## hash, and have reasonable default values.
                   2674: ##
                   2675: ##    formname = the name given in the <form> tag.
1.35      matthew  2676: #-------------------------------------------
                   2677: 
1.45      matthew  2678: =pod
                   2679: 
1.112     bowersj2 2680: =head1 Authentication Routines
                   2681: 
                   2682: =over 4
                   2683: 
1.648     raeburn  2684: =item * &authform_xxxxxx()
1.35      matthew  2685: 
                   2686: The authform_xxxxxx subroutines provide javascript and html forms which 
                   2687: handle some of the conveniences required for authentication forms.  
                   2688: This is not an optimal method, but it works.  
                   2689: 
                   2690: =over 4
                   2691: 
1.112     bowersj2 2692: =item * authform_header
1.35      matthew  2693: 
1.112     bowersj2 2694: =item * authform_authorwarning
1.35      matthew  2695: 
1.112     bowersj2 2696: =item * authform_nochange
1.35      matthew  2697: 
1.112     bowersj2 2698: =item * authform_kerberos
1.35      matthew  2699: 
1.112     bowersj2 2700: =item * authform_internal
1.35      matthew  2701: 
1.112     bowersj2 2702: =item * authform_filesystem
1.35      matthew  2703: 
                   2704: =back
                   2705: 
1.648     raeburn  2706: See loncreateuser.pm for invocation and use examples.
1.157     matthew  2707: 
1.35      matthew  2708: =cut
                   2709: 
                   2710: #-------------------------------------------
1.32      matthew  2711: sub authform_header{  
                   2712:     my %in = (
                   2713:         formname => 'cu',
1.80      albertel 2714:         kerb_def_dom => '',
1.32      matthew  2715:         @_,
                   2716:     );
                   2717:     $in{'formname'} = 'document.' . $in{'formname'};
                   2718:     my $result='';
1.80      albertel 2719: 
                   2720: #---------------------------------------------- Code for upper case translation
                   2721:     my $Javascript_toUpperCase;
                   2722:     unless ($in{kerb_def_dom}) {
                   2723:         $Javascript_toUpperCase =<<"END";
                   2724:         switch (choice) {
                   2725:            case 'krb': currentform.elements[choicearg].value =
                   2726:                currentform.elements[choicearg].value.toUpperCase();
                   2727:                break;
                   2728:            default:
                   2729:         }
                   2730: END
                   2731:     } else {
                   2732:         $Javascript_toUpperCase = "";
                   2733:     }
                   2734: 
1.165     raeburn  2735:     my $radioval = "'nochange'";
1.591     raeburn  2736:     if (defined($in{'curr_authtype'})) {
                   2737:         if ($in{'curr_authtype'} ne '') {
                   2738:             $radioval = "'".$in{'curr_authtype'}."arg'";
                   2739:         }
1.174     matthew  2740:     }
1.165     raeburn  2741:     my $argfield = 'null';
1.591     raeburn  2742:     if (defined($in{'mode'})) {
1.165     raeburn  2743:         if ($in{'mode'} eq 'modifycourse')  {
1.591     raeburn  2744:             if (defined($in{'curr_autharg'})) {
                   2745:                 if ($in{'curr_autharg'} ne '') {
1.165     raeburn  2746:                     $argfield = "'$in{'curr_autharg'}'";
                   2747:                 }
                   2748:             }
                   2749:         }
                   2750:     }
                   2751: 
1.32      matthew  2752:     $result.=<<"END";
                   2753: var current = new Object();
1.165     raeburn  2754: current.radiovalue = $radioval;
                   2755: current.argfield = $argfield;
1.32      matthew  2756: 
                   2757: function changed_radio(choice,currentform) {
                   2758:     var choicearg = choice + 'arg';
                   2759:     // If a radio button in changed, we need to change the argfield
                   2760:     if (current.radiovalue != choice) {
                   2761:         current.radiovalue = choice;
                   2762:         if (current.argfield != null) {
                   2763:             currentform.elements[current.argfield].value = '';
                   2764:         }
                   2765:         if (choice == 'nochange') {
                   2766:             current.argfield = null;
                   2767:         } else {
                   2768:             current.argfield = choicearg;
                   2769:             switch(choice) {
                   2770:                 case 'krb': 
                   2771:                     currentform.elements[current.argfield].value = 
                   2772:                         "$in{'kerb_def_dom'}";
                   2773:                 break;
                   2774:               default:
                   2775:                 break;
                   2776:             }
                   2777:         }
                   2778:     }
                   2779:     return;
                   2780: }
1.22      www      2781: 
1.32      matthew  2782: function changed_text(choice,currentform) {
                   2783:     var choicearg = choice + 'arg';
                   2784:     if (currentform.elements[choicearg].value !='') {
1.80      albertel 2785:         $Javascript_toUpperCase
1.32      matthew  2786:         // clear old field
                   2787:         if ((current.argfield != choicearg) && (current.argfield != null)) {
                   2788:             currentform.elements[current.argfield].value = '';
                   2789:         }
                   2790:         current.argfield = choicearg;
                   2791:     }
                   2792:     set_auth_radio_buttons(choice,currentform);
                   2793:     return;
1.20      www      2794: }
1.32      matthew  2795: 
                   2796: function set_auth_radio_buttons(newvalue,currentform) {
1.986     raeburn  2797:     var numauthchoices = currentform.login.length;
                   2798:     if (typeof numauthchoices  == "undefined") {
                   2799:         return;
                   2800:     } 
1.32      matthew  2801:     var i=0;
1.986     raeburn  2802:     while (i < numauthchoices) {
1.32      matthew  2803:         if (currentform.login[i].value == newvalue) { break; }
                   2804:         i++;
                   2805:     }
1.986     raeburn  2806:     if (i == numauthchoices) {
1.32      matthew  2807:         return;
                   2808:     }
                   2809:     current.radiovalue = newvalue;
                   2810:     currentform.login[i].checked = true;
                   2811:     return;
                   2812: }
                   2813: END
                   2814:     return $result;
                   2815: }
                   2816: 
1.1075.2.20  raeburn  2817: sub authform_authorwarning {
1.32      matthew  2818:     my $result='';
1.144     matthew  2819:     $result='<i>'.
                   2820:         &mt('As a general rule, only authors or co-authors should be '.
                   2821:             'filesystem authenticated '.
                   2822:             '(which allows access to the server filesystem).')."</i>\n";
1.32      matthew  2823:     return $result;
                   2824: }
                   2825: 
1.1075.2.20  raeburn  2826: sub authform_nochange {
1.32      matthew  2827:     my %in = (
                   2828:               formname => 'document.cu',
                   2829:               kerb_def_dom => 'MSU.EDU',
                   2830:               @_,
                   2831:           );
1.1075.2.20  raeburn  2832:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'}); 
1.586     raeburn  2833:     my $result;
1.1075.2.20  raeburn  2834:     if (!$authnum) {
                   2835:         $result = &mt('Under your current role you are not permitted to change login settings for this user');
1.586     raeburn  2836:     } else {
                   2837:         $result = '<label>'.&mt('[_1] Do not change login data',
                   2838:                   '<input type="radio" name="login" value="nochange" '.
                   2839:                   'checked="checked" onclick="'.
1.281     albertel 2840:             "javascript:changed_radio('nochange',$in{'formname'});".'" />').
                   2841: 	    '</label>';
1.586     raeburn  2842:     }
1.32      matthew  2843:     return $result;
                   2844: }
                   2845: 
1.591     raeburn  2846: sub authform_kerberos {
1.32      matthew  2847:     my %in = (
                   2848:               formname => 'document.cu',
                   2849:               kerb_def_dom => 'MSU.EDU',
1.80      albertel 2850:               kerb_def_auth => 'krb4',
1.32      matthew  2851:               @_,
                   2852:               );
1.586     raeburn  2853:     my ($check4,$check5,$krbcheck,$krbarg,$krbver,$result,$authtype,
1.1075.2.117  raeburn  2854:         $autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2855:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.80      albertel 2856:     if ($in{'kerb_def_auth'} eq 'krb5') {
1.772     bisitz   2857:        $check5 = ' checked="checked"';
1.80      albertel 2858:     } else {
1.772     bisitz   2859:        $check4 = ' checked="checked"';
1.80      albertel 2860:     }
1.1075.2.117  raeburn  2861:     if ($in{'readonly'}) {
                   2862:         $disabled = ' disabled="disabled"';
                   2863:     }
1.165     raeburn  2864:     $krbarg = $in{'kerb_def_dom'};
1.591     raeburn  2865:     if (defined($in{'curr_authtype'})) {
                   2866:         if ($in{'curr_authtype'} eq 'krb') {
1.772     bisitz   2867:             $krbcheck = ' checked="checked"';
1.623     raeburn  2868:             if (defined($in{'mode'})) {
                   2869:                 if ($in{'mode'} eq 'modifyuser') {
                   2870:                     $krbcheck = '';
                   2871:                 }
                   2872:             }
1.591     raeburn  2873:             if (defined($in{'curr_kerb_ver'})) {
                   2874:                 if ($in{'curr_krb_ver'} eq '5') {
1.772     bisitz   2875:                     $check5 = ' checked="checked"';
1.591     raeburn  2876:                     $check4 = '';
                   2877:                 } else {
1.772     bisitz   2878:                     $check4 = ' checked="checked"';
1.591     raeburn  2879:                     $check5 = '';
                   2880:                 }
1.586     raeburn  2881:             }
1.591     raeburn  2882:             if (defined($in{'curr_autharg'})) {
1.165     raeburn  2883:                 $krbarg = $in{'curr_autharg'};
                   2884:             }
1.586     raeburn  2885:             if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
1.591     raeburn  2886:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2887:                     $result = 
                   2888:     &mt('Currently Kerberos authenticated with domain [_1] Version [_2].',
                   2889:         $in{'curr_autharg'},$krbver);
                   2890:                 } else {
                   2891:                     $result =
                   2892:     &mt('Currently Kerberos authenticated, Version [_1].',$krbver);
                   2893:                 }
                   2894:                 return $result; 
                   2895:             }
                   2896:         }
                   2897:     } else {
                   2898:         if ($authnum == 1) {
1.784     bisitz   2899:             $authtype = '<input type="hidden" name="login" value="krb" />';
1.165     raeburn  2900:         }
                   2901:     }
1.586     raeburn  2902:     if (!$can_assign{'krb4'} && !$can_assign{'krb5'}) {
                   2903:         return;
1.587     raeburn  2904:     } elsif ($authtype eq '') {
1.591     raeburn  2905:         if (defined($in{'mode'})) {
1.587     raeburn  2906:             if ($in{'mode'} eq 'modifycourse') {
                   2907:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2908:                     $authtype = '<input type="radio" name="login" value="krb"'.$disabled.' />';
1.587     raeburn  2909:                 }
                   2910:             }
                   2911:         }
1.586     raeburn  2912:     }
                   2913:     $jscall = "javascript:changed_radio('krb',$in{'formname'});";
                   2914:     if ($authtype eq '') {
                   2915:         $authtype = '<input type="radio" name="login" value="krb" '.
                   2916:                     'onclick="'.$jscall.'" onchange="'.$jscall.'"'.
1.1075.2.117  raeburn  2917:                     $krbcheck.$disabled.' />';
1.586     raeburn  2918:     }
                   2919:     if (($can_assign{'krb4'} && $can_assign{'krb5'}) ||
1.1075.2.20  raeburn  2920:         ($can_assign{'krb4'} && !$can_assign{'krb5'} &&
1.586     raeburn  2921:          $in{'curr_authtype'} eq 'krb5') ||
1.1075.2.20  raeburn  2922:         (!$can_assign{'krb4'} && $can_assign{'krb5'} &&
1.586     raeburn  2923:          $in{'curr_authtype'} eq 'krb4')) {
                   2924:         $result .= &mt
1.144     matthew  2925:         ('[_1] Kerberos authenticated with domain [_2] '.
1.281     albertel 2926:          '[_3] Version 4 [_4] Version 5 [_5]',
1.586     raeburn  2927:          '<label>'.$authtype,
1.281     albertel 2928:          '</label><input type="text" size="10" name="krbarg" '.
1.165     raeburn  2929:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2930:              'onchange="'.$jscall.'"'.$disabled.' />',
                   2931:          '<label><input type="radio" name="krbver" value="4" '.$check4.$disabled.' />',
                   2932:          '</label><label><input type="radio" name="krbver" value="5" '.$check5.$disabled.' />',
1.281     albertel 2933: 	 '</label>');
1.586     raeburn  2934:     } elsif ($can_assign{'krb4'}) {
                   2935:         $result .= &mt
                   2936:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2937:          '[_3] Version 4 [_4]',
                   2938:          '<label>'.$authtype,
                   2939:          '</label><input type="text" size="10" name="krbarg" '.
                   2940:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2941:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2942:          '<label><input type="hidden" name="krbver" value="4" />',
                   2943:          '</label>');
                   2944:     } elsif ($can_assign{'krb5'}) {
                   2945:         $result .= &mt
                   2946:         ('[_1] Kerberos authenticated with domain [_2] '.
                   2947:          '[_3] Version 5 [_4]',
                   2948:          '<label>'.$authtype,
                   2949:          '</label><input type="text" size="10" name="krbarg" '.
                   2950:              'value="'.$krbarg.'" '.
1.1075.2.117  raeburn  2951:              'onchange="'.$jscall.'"'.$disabled.' />',
1.586     raeburn  2952:          '<label><input type="hidden" name="krbver" value="5" />',
                   2953:          '</label>');
                   2954:     }
1.32      matthew  2955:     return $result;
                   2956: }
                   2957: 
1.1075.2.20  raeburn  2958: sub authform_internal {
1.586     raeburn  2959:     my %in = (
1.32      matthew  2960:                 formname => 'document.cu',
                   2961:                 kerb_def_dom => 'MSU.EDU',
                   2962:                 @_,
                   2963:                 );
1.1075.2.117  raeburn  2964:     my ($intcheck,$intarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  2965:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  2966:     if ($in{'readonly'}) {
                   2967:         $disabled = ' disabled="disabled"';
                   2968:     }
1.591     raeburn  2969:     if (defined($in{'curr_authtype'})) {
                   2970:         if ($in{'curr_authtype'} eq 'int') {
1.586     raeburn  2971:             if ($can_assign{'int'}) {
1.772     bisitz   2972:                 $intcheck = 'checked="checked" ';
1.623     raeburn  2973:                 if (defined($in{'mode'})) {
                   2974:                     if ($in{'mode'} eq 'modifyuser') {
                   2975:                         $intcheck = '';
                   2976:                     }
                   2977:                 }
1.591     raeburn  2978:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  2979:                     $intarg = $in{'curr_autharg'};
                   2980:                 }
                   2981:             } else {
                   2982:                 $result = &mt('Currently internally authenticated.');
                   2983:                 return $result;
1.165     raeburn  2984:             }
                   2985:         }
1.586     raeburn  2986:     } else {
                   2987:         if ($authnum == 1) {
1.784     bisitz   2988:             $authtype = '<input type="hidden" name="login" value="int" />';
1.586     raeburn  2989:         }
                   2990:     }
                   2991:     if (!$can_assign{'int'}) {
                   2992:         return;
1.587     raeburn  2993:     } elsif ($authtype eq '') {
1.591     raeburn  2994:         if (defined($in{'mode'})) {
1.587     raeburn  2995:             if ($in{'mode'} eq 'modifycourse') {
                   2996:                 if ($authnum == 1) {
1.1075.2.117  raeburn  2997:                     $authtype = '<input type="radio" name="login" value="int"'.$disabled.' />';
1.587     raeburn  2998:                 }
                   2999:             }
                   3000:         }
1.165     raeburn  3001:     }
1.586     raeburn  3002:     $jscall = "javascript:changed_radio('int',$in{'formname'});";
                   3003:     if ($authtype eq '') {
                   3004:         $authtype = '<input type="radio" name="login" value="int" '.$intcheck.
1.1075.2.117  raeburn  3005:                     ' onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3006:     }
1.605     bisitz   3007:     $autharg = '<input type="password" size="10" name="intarg" value="'.
1.1075.2.117  raeburn  3008:                $intarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3009:     $result = &mt
1.144     matthew  3010:         ('[_1] Internally authenticated (with initial password [_2])',
1.586     raeburn  3011:          '<label>'.$authtype,'</label>'.$autharg);
1.1075.2.118  raeburn  3012:     $result.='<label><input type="checkbox" name="visible" onclick="if (this.checked) { this.form.intarg.type='."'text'".' } else { this.form.intarg.type='."'password'".' }"'.$disabled.' />'.&mt('Visible input').'</label>';
1.32      matthew  3013:     return $result;
                   3014: }
                   3015: 
1.1075.2.20  raeburn  3016: sub authform_local {
1.32      matthew  3017:     my %in = (
                   3018:               formname => 'document.cu',
                   3019:               kerb_def_dom => 'MSU.EDU',
                   3020:               @_,
                   3021:               );
1.1075.2.117  raeburn  3022:     my ($loccheck,$locarg,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3023:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3024:     if ($in{'readonly'}) {
                   3025:         $disabled = ' disabled="disabled"';
                   3026:     }
1.591     raeburn  3027:     if (defined($in{'curr_authtype'})) {
                   3028:         if ($in{'curr_authtype'} eq 'loc') {
1.586     raeburn  3029:             if ($can_assign{'loc'}) {
1.772     bisitz   3030:                 $loccheck = 'checked="checked" ';
1.623     raeburn  3031:                 if (defined($in{'mode'})) {
                   3032:                     if ($in{'mode'} eq 'modifyuser') {
                   3033:                         $loccheck = '';
                   3034:                     }
                   3035:                 }
1.591     raeburn  3036:                 if (defined($in{'curr_autharg'})) {
1.586     raeburn  3037:                     $locarg = $in{'curr_autharg'};
                   3038:                 }
                   3039:             } else {
                   3040:                 $result = &mt('Currently using local (institutional) authentication.');
                   3041:                 return $result;
1.165     raeburn  3042:             }
                   3043:         }
1.586     raeburn  3044:     } else {
                   3045:         if ($authnum == 1) {
1.784     bisitz   3046:             $authtype = '<input type="hidden" name="login" value="loc" />';
1.586     raeburn  3047:         }
                   3048:     }
                   3049:     if (!$can_assign{'loc'}) {
                   3050:         return;
1.587     raeburn  3051:     } elsif ($authtype eq '') {
1.591     raeburn  3052:         if (defined($in{'mode'})) {
1.587     raeburn  3053:             if ($in{'mode'} eq 'modifycourse') {
                   3054:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3055:                     $authtype = '<input type="radio" name="login" value="loc"'.$disabled.' />';
1.587     raeburn  3056:                 }
                   3057:             }
                   3058:         }
1.165     raeburn  3059:     }
1.586     raeburn  3060:     $jscall = "javascript:changed_radio('loc',$in{'formname'});";
                   3061:     if ($authtype eq '') {
                   3062:         $authtype = '<input type="radio" name="login" value="loc" '.
                   3063:                     $loccheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3064:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3065:     }
                   3066:     $autharg = '<input type="text" size="10" name="locarg" value="'.
1.1075.2.117  raeburn  3067:                $locarg.'" onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3068:     $result = &mt('[_1] Local Authentication with argument [_2]',
                   3069:                   '<label>'.$authtype,'</label>'.$autharg);
1.32      matthew  3070:     return $result;
                   3071: }
                   3072: 
1.1075.2.20  raeburn  3073: sub authform_filesystem {
1.32      matthew  3074:     my %in = (
                   3075:               formname => 'document.cu',
                   3076:               kerb_def_dom => 'MSU.EDU',
                   3077:               @_,
                   3078:               );
1.1075.2.117  raeburn  3079:     my ($fsyscheck,$result,$authtype,$autharg,$jscall,$disabled);
1.1075.2.20  raeburn  3080:     my ($authnum,%can_assign) = &get_assignable_auth($in{'domain'});
1.1075.2.117  raeburn  3081:     if ($in{'readonly'}) {
                   3082:         $disabled = ' disabled="disabled"';
                   3083:     }
1.591     raeburn  3084:     if (defined($in{'curr_authtype'})) {
                   3085:         if ($in{'curr_authtype'} eq 'fsys') {
1.586     raeburn  3086:             if ($can_assign{'fsys'}) {
1.772     bisitz   3087:                 $fsyscheck = 'checked="checked" ';
1.623     raeburn  3088:                 if (defined($in{'mode'})) {
                   3089:                     if ($in{'mode'} eq 'modifyuser') {
                   3090:                         $fsyscheck = '';
                   3091:                     }
                   3092:                 }
1.586     raeburn  3093:             } else {
                   3094:                 $result = &mt('Currently Filesystem Authenticated.');
                   3095:                 return $result;
                   3096:             }           
                   3097:         }
                   3098:     } else {
                   3099:         if ($authnum == 1) {
1.784     bisitz   3100:             $authtype = '<input type="hidden" name="login" value="fsys" />';
1.586     raeburn  3101:         }
                   3102:     }
                   3103:     if (!$can_assign{'fsys'}) {
                   3104:         return;
1.587     raeburn  3105:     } elsif ($authtype eq '') {
1.591     raeburn  3106:         if (defined($in{'mode'})) {
1.587     raeburn  3107:             if ($in{'mode'} eq 'modifycourse') {
                   3108:                 if ($authnum == 1) {
1.1075.2.117  raeburn  3109:                     $authtype = '<input type="radio" name="login" value="fsys"'.$disabled.' />';
1.587     raeburn  3110:                 }
                   3111:             }
                   3112:         }
1.586     raeburn  3113:     }
                   3114:     $jscall = "javascript:changed_radio('fsys',$in{'formname'});";
                   3115:     if ($authtype eq '') {
                   3116:         $authtype = '<input type="radio" name="login" value="fsys" '.
                   3117:                     $fsyscheck.' onchange="'.$jscall.'" onclick="'.
1.1075.2.117  raeburn  3118:                     $jscall.'"'.$disabled.' />';
1.586     raeburn  3119:     }
                   3120:     $autharg = '<input type="text" size="10" name="fsysarg" value=""'.
1.1075.2.117  raeburn  3121:                ' onchange="'.$jscall.'"'.$disabled.' />';
1.586     raeburn  3122:     $result = &mt
1.144     matthew  3123:         ('[_1] Filesystem Authenticated (with initial password [_2])',
1.281     albertel 3124:          '<label><input type="radio" name="login" value="fsys" '.
1.1075.2.117  raeburn  3125:          $fsyscheck.'onchange="'.$jscall.'" onclick="'.$jscall.'"'.$disabled.' />',
1.605     bisitz   3126:          '</label><input type="password" size="10" name="fsysarg" value="" '.
1.1075.2.117  raeburn  3127:                   'onchange="'.$jscall.'"'.$disabled.' />');
1.32      matthew  3128:     return $result;
                   3129: }
                   3130: 
1.586     raeburn  3131: sub get_assignable_auth {
                   3132:     my ($dom) = @_;
                   3133:     if ($dom eq '') {
                   3134:         $dom = $env{'request.role.domain'};
                   3135:     }
                   3136:     my %can_assign = (
                   3137:                           krb4 => 1,
                   3138:                           krb5 => 1,
                   3139:                           int  => 1,
                   3140:                           loc  => 1,
                   3141:                      );
                   3142:     my %domconfig = &Apache::lonnet::get_dom('configuration',['usercreation'],$dom);
                   3143:     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   3144:         if (ref($domconfig{'usercreation'}{'authtypes'}) eq 'HASH') {
                   3145:             my $authhash = $domconfig{'usercreation'}{'authtypes'};
                   3146:             my $context;
                   3147:             if ($env{'request.role'} =~ /^au/) {
                   3148:                 $context = 'author';
1.1075.2.117  raeburn  3149:             } elsif ($env{'request.role'} =~ /^(dc|dh)/) {
1.586     raeburn  3150:                 $context = 'domain';
                   3151:             } elsif ($env{'request.course.id'}) {
                   3152:                 $context = 'course';
                   3153:             }
                   3154:             if ($context) {
                   3155:                 if (ref($authhash->{$context}) eq 'HASH') {
                   3156:                    %can_assign = %{$authhash->{$context}}; 
                   3157:                 }
                   3158:             }
                   3159:         }
                   3160:     }
                   3161:     my $authnum = 0;
                   3162:     foreach my $key (keys(%can_assign)) {
                   3163:         if ($can_assign{$key}) {
                   3164:             $authnum ++;
                   3165:         }
                   3166:     }
                   3167:     if ($can_assign{'krb4'} && $can_assign{'krb5'}) {
                   3168:         $authnum --;
                   3169:     }
                   3170:     return ($authnum,%can_assign);
                   3171: }
                   3172: 
1.80      albertel 3173: ###############################################################
                   3174: ##    Get Kerberos Defaults for Domain                 ##
                   3175: ###############################################################
                   3176: ##
                   3177: ## Returns default kerberos version and an associated argument
                   3178: ## as listed in file domain.tab. If not listed, provides
                   3179: ## appropriate default domain and kerberos version.
                   3180: ##
                   3181: #-------------------------------------------
                   3182: 
                   3183: =pod
                   3184: 
1.648     raeburn  3185: =item * &get_kerberos_defaults()
1.80      albertel 3186: 
                   3187: get_kerberos_defaults($target_domain) returns the default kerberos
1.641     raeburn  3188: version and domain. If not found, it defaults to version 4 and the 
                   3189: domain of the server.
1.80      albertel 3190: 
1.648     raeburn  3191: =over 4
                   3192: 
1.80      albertel 3193: ($def_version, $def_krb_domain) = &get_kerberos_defaults($target_domain);
                   3194: 
1.648     raeburn  3195: =back
                   3196: 
                   3197: =back
                   3198: 
1.80      albertel 3199: =cut
                   3200: 
                   3201: #-------------------------------------------
                   3202: sub get_kerberos_defaults {
                   3203:     my $domain=shift;
1.641     raeburn  3204:     my ($krbdef,$krbdefdom);
                   3205:     my %domdefaults = &Apache::lonnet::get_domain_defaults($domain);
                   3206:     if (($domdefaults{'auth_def'} =~/^krb(4|5)$/) && ($domdefaults{'auth_arg_def'} ne '')) {
                   3207:         $krbdef = $domdefaults{'auth_def'};
                   3208:         $krbdefdom = $domdefaults{'auth_arg_def'};
                   3209:     } else {
1.80      albertel 3210:         $ENV{'SERVER_NAME'}=~/(\w+\.\w+)$/;
                   3211:         my $krbdefdom=$1;
                   3212:         $krbdefdom=~tr/a-z/A-Z/;
                   3213:         $krbdef = "krb4";
                   3214:     }
                   3215:     return ($krbdef,$krbdefdom);
                   3216: }
1.112     bowersj2 3217: 
1.32      matthew  3218: 
1.46      matthew  3219: ###############################################################
                   3220: ##                Thesaurus Functions                        ##
                   3221: ###############################################################
1.20      www      3222: 
1.46      matthew  3223: =pod
1.20      www      3224: 
1.112     bowersj2 3225: =head1 Thesaurus Functions
                   3226: 
                   3227: =over 4
                   3228: 
1.648     raeburn  3229: =item * &initialize_keywords()
1.46      matthew  3230: 
                   3231: Initializes the package variable %Keywords if it is empty.  Uses the
                   3232: package variable $thesaurus_db_file.
                   3233: 
                   3234: =cut
                   3235: 
                   3236: ###################################################
                   3237: 
                   3238: sub initialize_keywords {
                   3239:     return 1 if (scalar keys(%Keywords));
                   3240:     # If we are here, %Keywords is empty, so fill it up
                   3241:     #   Make sure the file we need exists...
                   3242:     if (! -e $thesaurus_db_file) {
                   3243:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file".
                   3244:                                  " failed because it does not exist");
                   3245:         return 0;
                   3246:     }
                   3247:     #   Set up the hash as a database
                   3248:     my %thesaurus_db;
                   3249:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3250:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3251:         &Apache::lonnet::logthis("Could not tie \%thesaurus_db to ".
                   3252:                                  $thesaurus_db_file);
                   3253:         return 0;
                   3254:     } 
                   3255:     #  Get the average number of appearances of a word.
                   3256:     my $avecount = $thesaurus_db{'average.count'};
                   3257:     #  Put keywords (those that appear > average) into %Keywords
                   3258:     while (my ($word,$data)=each (%thesaurus_db)) {
                   3259:         my ($count,undef) = split /:/,$data;
                   3260:         $Keywords{$word}++ if ($count > $avecount);
                   3261:     }
                   3262:     untie %thesaurus_db;
                   3263:     # Remove special values from %Keywords.
1.356     albertel 3264:     foreach my $value ('total.count','average.count') {
                   3265:         delete($Keywords{$value}) if (exists($Keywords{$value}));
1.586     raeburn  3266:   }
1.46      matthew  3267:     return 1;
                   3268: }
                   3269: 
                   3270: ###################################################
                   3271: 
                   3272: =pod
                   3273: 
1.648     raeburn  3274: =item * &keyword($word)
1.46      matthew  3275: 
                   3276: Returns true if $word is a keyword.  A keyword is a word that appears more 
                   3277: than the average number of times in the thesaurus database.  Calls 
                   3278: &initialize_keywords
                   3279: 
                   3280: =cut
                   3281: 
                   3282: ###################################################
1.20      www      3283: 
                   3284: sub keyword {
1.46      matthew  3285:     return if (!&initialize_keywords());
                   3286:     my $word=lc(shift());
                   3287:     $word=~s/\W//g;
                   3288:     return exists($Keywords{$word});
1.20      www      3289: }
1.46      matthew  3290: 
                   3291: ###############################################################
                   3292: 
                   3293: =pod 
1.20      www      3294: 
1.648     raeburn  3295: =item * &get_related_words()
1.46      matthew  3296: 
1.160     matthew  3297: Look up a word in the thesaurus.  Takes a scalar argument and returns
1.46      matthew  3298: an array of words.  If the keyword is not in the thesaurus, an empty array
                   3299: will be returned.  The order of the words returned is determined by the
                   3300: database which holds them.
                   3301: 
                   3302: Uses global $thesaurus_db_file.
                   3303: 
1.1057    foxr     3304: 
1.46      matthew  3305: =cut
                   3306: 
                   3307: ###############################################################
                   3308: sub get_related_words {
                   3309:     my $keyword = shift;
                   3310:     my %thesaurus_db;
                   3311:     if (! -e $thesaurus_db_file) {
                   3312:         &Apache::lonnet::logthis("Attempt to access $thesaurus_db_file ".
                   3313:                                  "failed because the file does not exist");
                   3314:         return ();
                   3315:     }
                   3316:     if (! tie(%thesaurus_db,'GDBM_File',
1.53      albertel 3317:               $thesaurus_db_file,&GDBM_READER(),0640)){
1.46      matthew  3318:         return ();
                   3319:     } 
                   3320:     my @Words=();
1.429     www      3321:     my $count=0;
1.46      matthew  3322:     if (exists($thesaurus_db{$keyword})) {
1.356     albertel 3323: 	# The first element is the number of times
                   3324: 	# the word appears.  We do not need it now.
1.429     www      3325: 	my (undef,@RelatedWords) = (split(/:/,$thesaurus_db{$keyword}));
                   3326: 	my (undef,$mostfrequentcount)=split(/\,/,$RelatedWords[0]);
                   3327: 	my $threshold=$mostfrequentcount/10;
                   3328:         foreach my $possibleword (@RelatedWords) {
                   3329:             my ($word,$wordcount)=split(/\,/,$possibleword);
                   3330:             if ($wordcount>$threshold) {
                   3331: 		push(@Words,$word);
                   3332:                 $count++;
                   3333:                 if ($count>10) { last; }
                   3334: 	    }
1.20      www      3335:         }
                   3336:     }
1.46      matthew  3337:     untie %thesaurus_db;
                   3338:     return @Words;
1.14      harris41 3339: }
1.46      matthew  3340: 
1.112     bowersj2 3341: =pod
                   3342: 
                   3343: =back
                   3344: 
                   3345: =cut
1.61      www      3346: 
                   3347: # -------------------------------------------------------------- Plaintext name
1.81      albertel 3348: =pod
                   3349: 
1.112     bowersj2 3350: =head1 User Name Functions
                   3351: 
                   3352: =over 4
                   3353: 
1.648     raeburn  3354: =item * &plainname($uname,$udom,$first)
1.81      albertel 3355: 
1.112     bowersj2 3356: Takes a users logon name and returns it as a string in
1.226     albertel 3357: "first middle last generation" form 
                   3358: if $first is set to 'lastname' then it returns it as
                   3359: 'lastname generation, firstname middlename' if their is a lastname
1.81      albertel 3360: 
                   3361: =cut
1.61      www      3362: 
1.295     www      3363: 
1.81      albertel 3364: ###############################################################
1.61      www      3365: sub plainname {
1.226     albertel 3366:     my ($uname,$udom,$first)=@_;
1.537     albertel 3367:     return if (!defined($uname) || !defined($udom));
1.295     www      3368:     my %names=&getnames($uname,$udom);
1.226     albertel 3369:     my $name=&Apache::lonnet::format_name($names{'firstname'},
                   3370: 					  $names{'middlename'},
                   3371: 					  $names{'lastname'},
                   3372: 					  $names{'generation'},$first);
                   3373:     $name=~s/^\s+//;
1.62      www      3374:     $name=~s/\s+$//;
                   3375:     $name=~s/\s+/ /g;
1.353     albertel 3376:     if ($name !~ /\S/) { $name=$uname.':'.$udom; }
1.62      www      3377:     return $name;
1.61      www      3378: }
1.66      www      3379: 
                   3380: # -------------------------------------------------------------------- Nickname
1.81      albertel 3381: =pod
                   3382: 
1.648     raeburn  3383: =item * &nickname($uname,$udom)
1.81      albertel 3384: 
                   3385: Gets a users name and returns it as a string as
                   3386: 
                   3387: "&quot;nickname&quot;"
1.66      www      3388: 
1.81      albertel 3389: if the user has a nickname or
                   3390: 
                   3391: "first middle last generation"
                   3392: 
                   3393: if the user does not
                   3394: 
                   3395: =cut
1.66      www      3396: 
                   3397: sub nickname {
                   3398:     my ($uname,$udom)=@_;
1.537     albertel 3399:     return if (!defined($uname) || !defined($udom));
1.295     www      3400:     my %names=&getnames($uname,$udom);
1.68      albertel 3401:     my $name=$names{'nickname'};
1.66      www      3402:     if ($name) {
                   3403:        $name='&quot;'.$name.'&quot;'; 
                   3404:     } else {
                   3405:        $name=$names{'firstname'}.' '.$names{'middlename'}.' '.
                   3406: 	     $names{'lastname'}.' '.$names{'generation'};
                   3407:        $name=~s/\s+$//;
                   3408:        $name=~s/\s+/ /g;
                   3409:     }
                   3410:     return $name;
                   3411: }
                   3412: 
1.295     www      3413: sub getnames {
                   3414:     my ($uname,$udom)=@_;
1.537     albertel 3415:     return if (!defined($uname) || !defined($udom));
1.433     albertel 3416:     if ($udom eq 'public' && $uname eq 'public') {
                   3417: 	return ('lastname' => &mt('Public'));
                   3418:     }
1.295     www      3419:     my $id=$uname.':'.$udom;
                   3420:     my ($names,$cached)=&Apache::lonnet::is_cached_new('namescache',$id);
                   3421:     if ($cached) {
                   3422: 	return %{$names};
                   3423:     } else {
                   3424: 	my %loadnames=&Apache::lonnet::get('environment',
                   3425:                     ['firstname','middlename','lastname','generation','nickname'],
                   3426: 					 $udom,$uname);
                   3427: 	&Apache::lonnet::do_cache_new('namescache',$id,\%loadnames);
                   3428: 	return %loadnames;
                   3429:     }
                   3430: }
1.61      www      3431: 
1.542     raeburn  3432: # -------------------------------------------------------------------- getemails
1.648     raeburn  3433: 
1.542     raeburn  3434: =pod
                   3435: 
1.648     raeburn  3436: =item * &getemails($uname,$udom)
1.542     raeburn  3437: 
                   3438: Gets a user's email information and returns it as a hash with keys:
                   3439: notification, critnotification, permanentemail
                   3440: 
                   3441: For notification and critnotification, values are comma-separated lists 
1.648     raeburn  3442: of e-mail addresses; for permanentemail, value is a single e-mail address.
1.542     raeburn  3443:  
1.648     raeburn  3444: 
1.542     raeburn  3445: =cut
                   3446: 
1.648     raeburn  3447: 
1.466     albertel 3448: sub getemails {
                   3449:     my ($uname,$udom)=@_;
                   3450:     if ($udom eq 'public' && $uname eq 'public') {
                   3451: 	return;
                   3452:     }
1.467     www      3453:     if (!$udom) { $udom=$env{'user.domain'}; }
                   3454:     if (!$uname) { $uname=$env{'user.name'}; }
1.466     albertel 3455:     my $id=$uname.':'.$udom;
                   3456:     my ($names,$cached)=&Apache::lonnet::is_cached_new('emailscache',$id);
                   3457:     if ($cached) {
                   3458: 	return %{$names};
                   3459:     } else {
                   3460: 	my %loadnames=&Apache::lonnet::get('environment',
                   3461:                     			   ['notification','critnotification',
                   3462: 					    'permanentemail'],
                   3463: 					   $udom,$uname);
                   3464: 	&Apache::lonnet::do_cache_new('emailscache',$id,\%loadnames);
                   3465: 	return %loadnames;
                   3466:     }
                   3467: }
                   3468: 
1.551     albertel 3469: sub flush_email_cache {
                   3470:     my ($uname,$udom)=@_;
                   3471:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3472:     if (!$uname) { $uname=$env{'user.name'};   }
                   3473:     return if ($udom eq 'public' && $uname eq 'public');
                   3474:     my $id=$uname.':'.$udom;
                   3475:     &Apache::lonnet::devalidate_cache_new('emailscache',$id);
                   3476: }
                   3477: 
1.728     raeburn  3478: # -------------------------------------------------------------------- getlangs
                   3479: 
                   3480: =pod
                   3481: 
                   3482: =item * &getlangs($uname,$udom)
                   3483: 
                   3484: Gets a user's language preference and returns it as a hash with key:
                   3485: language.
                   3486: 
                   3487: =cut
                   3488: 
                   3489: 
                   3490: sub getlangs {
                   3491:     my ($uname,$udom) = @_;
                   3492:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3493:     if (!$uname) { $uname=$env{'user.name'};   }
                   3494:     my $id=$uname.':'.$udom;
                   3495:     my ($langs,$cached)=&Apache::lonnet::is_cached_new('userlangs',$id);
                   3496:     if ($cached) {
                   3497:         return %{$langs};
                   3498:     } else {
                   3499:         my %loadlangs=&Apache::lonnet::get('environment',['languages'],
                   3500:                                            $udom,$uname);
                   3501:         &Apache::lonnet::do_cache_new('userlangs',$id,\%loadlangs);
                   3502:         return %loadlangs;
                   3503:     }
                   3504: }
                   3505: 
                   3506: sub flush_langs_cache {
                   3507:     my ($uname,$udom)=@_;
                   3508:     if (!$udom)  { $udom =$env{'user.domain'}; }
                   3509:     if (!$uname) { $uname=$env{'user.name'};   }
                   3510:     return if ($udom eq 'public' && $uname eq 'public');
                   3511:     my $id=$uname.':'.$udom;
                   3512:     &Apache::lonnet::devalidate_cache_new('userlangs',$id);
                   3513: }
                   3514: 
1.61      www      3515: # ------------------------------------------------------------------ Screenname
1.81      albertel 3516: 
                   3517: =pod
                   3518: 
1.648     raeburn  3519: =item * &screenname($uname,$udom)
1.81      albertel 3520: 
                   3521: Gets a users screenname and returns it as a string
                   3522: 
                   3523: =cut
1.61      www      3524: 
                   3525: sub screenname {
                   3526:     my ($uname,$udom)=@_;
1.258     albertel 3527:     if ($uname eq $env{'user.name'} &&
                   3528: 	$udom eq $env{'user.domain'}) {return $env{'environment.screenname'};}
1.212     albertel 3529:     my %names=&Apache::lonnet::get('environment',['screenname'],$udom,$uname);
1.68      albertel 3530:     return $names{'screenname'};
1.62      www      3531: }
                   3532: 
1.212     albertel 3533: 
1.802     bisitz   3534: # ------------------------------------------------------------- Confirm Wrapper
                   3535: =pod
                   3536: 
1.1075.2.42  raeburn  3537: =item * &confirmwrapper($message)
1.802     bisitz   3538: 
                   3539: Wrap messages about completion of operation in box
                   3540: 
                   3541: =cut
                   3542: 
                   3543: sub confirmwrapper {
                   3544:     my ($message)=@_;
                   3545:     if ($message) {
                   3546:         return "\n".'<div class="LC_confirm_box">'."\n"
                   3547:                .$message."\n"
                   3548:                .'</div>'."\n";
                   3549:     } else {
                   3550:         return $message;
                   3551:     }
                   3552: }
                   3553: 
1.62      www      3554: # ------------------------------------------------------------- Message Wrapper
                   3555: 
                   3556: sub messagewrapper {
1.369     www      3557:     my ($link,$username,$domain,$subject,$text)=@_;
1.62      www      3558:     return 
1.441     albertel 3559:         '<a href="/adm/email?compose=individual&amp;'.
                   3560:         'recname='.$username.'&amp;recdom='.$domain.
                   3561: 	'&amp;subject='.&escape($subject).'&amp;text='.&escape($text).'" '.
1.200     matthew  3562:         'title="'.&mt('Send message').'">'.$link.'</a>';
1.74      www      3563: }
1.802     bisitz   3564: 
1.74      www      3565: # --------------------------------------------------------------- Notes Wrapper
                   3566: 
                   3567: sub noteswrapper {
                   3568:     my ($link,$un,$do)=@_;
                   3569:     return 
1.896     amueller 3570: "<a href='/adm/email?recordftf=retrieve&amp;recname=$un&amp;recdom=$do'>$link</a>";
1.62      www      3571: }
1.802     bisitz   3572: 
1.62      www      3573: # ------------------------------------------------------------- Aboutme Wrapper
                   3574: 
                   3575: sub aboutmewrapper {
1.1070    raeburn  3576:     my ($link,$username,$domain,$target,$class)=@_;
1.447     raeburn  3577:     if (!defined($username)  && !defined($domain)) {
                   3578:         return;
                   3579:     }
1.1075.2.15  raeburn  3580:     return '<a href="/adm/'.$domain.'/'.$username.'/aboutme"'.
1.1070    raeburn  3581: 	($target?' target="'.$target.'"':'').($class?' class="'.$class.'"':'').' title="'.&mt("View this user's personal information page").'">'.$link.'</a>';
1.62      www      3582: }
                   3583: 
                   3584: # ------------------------------------------------------------ Syllabus Wrapper
                   3585: 
                   3586: sub syllabuswrapper {
1.707     bisitz   3587:     my ($linktext,$coursedir,$domain)=@_;
1.208     matthew  3588:     return qq{<a href="/public/$domain/$coursedir/syllabus">$linktext</a>};
1.61      www      3589: }
1.14      harris41 3590: 
1.802     bisitz   3591: # -----------------------------------------------------------------------------
                   3592: 
1.208     matthew  3593: sub track_student_link {
1.887     raeburn  3594:     my ($linktext,$sname,$sdom,$target,$start,$only_body) = @_;
1.268     albertel 3595:     my $link ="/adm/trackstudent?";
1.208     matthew  3596:     my $title = 'View recent activity';
                   3597:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3598:         defined($sdom)  && $sdom  !~ /^\s*$/) {
1.268     albertel 3599:         $link .= "selected_student=$sname:$sdom";
1.208     matthew  3600:         $title .= ' of this student';
1.268     albertel 3601:     } 
1.208     matthew  3602:     if (defined($target) && $target !~ /^\s*$/) {
                   3603:         $target = qq{target="$target"};
                   3604:     } else {
                   3605:         $target = '';
                   3606:     }
1.268     albertel 3607:     if ($start) { $link.='&amp;start='.$start; }
1.887     raeburn  3608:     if ($only_body) { $link .= '&amp;only_body=1'; }
1.554     albertel 3609:     $title = &mt($title);
                   3610:     $linktext = &mt($linktext);
1.448     albertel 3611:     return qq{<a href="$link" title="$title" $target>$linktext</a>}.
                   3612: 	&help_open_topic('View_recent_activity');
1.208     matthew  3613: }
                   3614: 
1.781     raeburn  3615: sub slot_reservations_link {
                   3616:     my ($linktext,$sname,$sdom,$target) = @_;
                   3617:     my $link ="/adm/slotrequest?command=showresv&amp;origin=aboutme";
                   3618:     my $title = 'View slot reservation history';
                   3619:     if (defined($sname) && $sname !~ /^\s*$/ &&
                   3620:         defined($sdom)  && $sdom  !~ /^\s*$/) {
                   3621:         $link .= "&amp;uname=$sname&amp;udom=$sdom";
                   3622:         $title .= ' of this student';
                   3623:     }
                   3624:     if (defined($target) && $target !~ /^\s*$/) {
                   3625:         $target = qq{target="$target"};
                   3626:     } else {
                   3627:         $target = '';
                   3628:     }
                   3629:     $title = &mt($title);
                   3630:     $linktext = &mt($linktext);
                   3631:     return qq{<a href="$link" title="$title" $target>$linktext</a>};
                   3632: # FIXME uncomment when help item created: &help_open_topic('Slot_Reservation_History');
                   3633: 
                   3634: }
                   3635: 
1.508     www      3636: # ===================================================== Display a student photo
                   3637: 
                   3638: 
1.509     albertel 3639: sub student_image_tag {
1.508     www      3640:     my ($domain,$user)=@_;
                   3641:     my $imgsrc=&Apache::lonnet::studentphoto($domain,$user,'jpg');
                   3642:     if (($imgsrc) && ($imgsrc ne '/adm/lonKaputt/lonlogo_broken.gif')) {
                   3643: 	return '<img src="'.$imgsrc.'" align="right" />';
                   3644:     } else {
                   3645: 	return '';
                   3646:     }
                   3647: }
                   3648: 
1.112     bowersj2 3649: =pod
                   3650: 
                   3651: =back
                   3652: 
                   3653: =head1 Access .tab File Data
                   3654: 
                   3655: =over 4
                   3656: 
1.648     raeburn  3657: =item * &languageids() 
1.112     bowersj2 3658: 
                   3659: returns list of all language ids
                   3660: 
                   3661: =cut
                   3662: 
1.14      harris41 3663: sub languageids {
1.16      harris41 3664:     return sort(keys(%language));
1.14      harris41 3665: }
                   3666: 
1.112     bowersj2 3667: =pod
                   3668: 
1.648     raeburn  3669: =item * &languagedescription() 
1.112     bowersj2 3670: 
                   3671: returns description of a specified language id
                   3672: 
                   3673: =cut
                   3674: 
1.14      harris41 3675: sub languagedescription {
1.125     www      3676:     my $code=shift;
                   3677:     return  ($supported_language{$code}?'* ':'').
                   3678:             $language{$code}.
1.126     www      3679: 	    ($supported_language{$code}?' ('.&mt('interface available').')':'');
1.145     www      3680: }
                   3681: 
1.1048    foxr     3682: =pod
                   3683: 
                   3684: =item * &plainlanguagedescription
                   3685: 
                   3686: Returns both the plain language description (e.g. 'Creoles and Pidgins, English-based (Other)')
                   3687: and the language character encoding (e.g. ISO) separated by a ' - ' string.
                   3688: 
                   3689: =cut
                   3690: 
1.145     www      3691: sub plainlanguagedescription {
                   3692:     my $code=shift;
                   3693:     return $language{$code};
                   3694: }
                   3695: 
1.1048    foxr     3696: =pod
                   3697: 
                   3698: =item * &supportedlanguagecode
                   3699: 
                   3700: Returns the supported language code (e.g. sptutf maps to pt) given a language
                   3701: code.
                   3702: 
                   3703: =cut
                   3704: 
1.145     www      3705: sub supportedlanguagecode {
                   3706:     my $code=shift;
                   3707:     return $supported_language{$code};
1.97      www      3708: }
                   3709: 
1.112     bowersj2 3710: =pod
                   3711: 
1.1048    foxr     3712: =item * &latexlanguage()
                   3713: 
                   3714: Given a language key code returns the correspondnig language to use
                   3715: to select the correct hyphenation on LaTeX printouts.  This is undef if there
                   3716: is no supported hyphenation for the language code.
                   3717: 
                   3718: =cut
                   3719: 
                   3720: sub latexlanguage {
                   3721:     my $code = shift;
                   3722:     return $latex_language{$code};
                   3723: }
                   3724: 
                   3725: =pod
                   3726: 
                   3727: =item * &latexhyphenation()
                   3728: 
                   3729: Same as above but what's supplied is the language as it might be stored
                   3730: in the metadata.
                   3731: 
                   3732: =cut
                   3733: 
                   3734: sub latexhyphenation {
                   3735:     my $key = shift;
                   3736:     return $latex_language_bykey{$key};
                   3737: }
                   3738: 
                   3739: =pod
                   3740: 
1.648     raeburn  3741: =item * &copyrightids() 
1.112     bowersj2 3742: 
                   3743: returns list of all copyrights
                   3744: 
                   3745: =cut
                   3746: 
                   3747: sub copyrightids {
                   3748:     return sort(keys(%cprtag));
                   3749: }
                   3750: 
                   3751: =pod
                   3752: 
1.648     raeburn  3753: =item * &copyrightdescription() 
1.112     bowersj2 3754: 
                   3755: returns description of a specified copyright id
                   3756: 
                   3757: =cut
                   3758: 
                   3759: sub copyrightdescription {
1.166     www      3760:     return &mt($cprtag{shift(@_)});
1.112     bowersj2 3761: }
1.197     matthew  3762: 
                   3763: =pod
                   3764: 
1.648     raeburn  3765: =item * &source_copyrightids() 
1.192     taceyjo1 3766: 
                   3767: returns list of all source copyrights
                   3768: 
                   3769: =cut
                   3770: 
                   3771: sub source_copyrightids {
                   3772:     return sort(keys(%scprtag));
                   3773: }
                   3774: 
                   3775: =pod
                   3776: 
1.648     raeburn  3777: =item * &source_copyrightdescription() 
1.192     taceyjo1 3778: 
                   3779: returns description of a specified source copyright id
                   3780: 
                   3781: =cut
                   3782: 
                   3783: sub source_copyrightdescription {
                   3784:     return &mt($scprtag{shift(@_)});
                   3785: }
1.112     bowersj2 3786: 
                   3787: =pod
                   3788: 
1.648     raeburn  3789: =item * &filecategories() 
1.112     bowersj2 3790: 
                   3791: returns list of all file categories
                   3792: 
                   3793: =cut
                   3794: 
                   3795: sub filecategories {
                   3796:     return sort(keys(%category_extensions));
                   3797: }
                   3798: 
                   3799: =pod
                   3800: 
1.648     raeburn  3801: =item * &filecategorytypes() 
1.112     bowersj2 3802: 
                   3803: returns list of file types belonging to a given file
                   3804: category
                   3805: 
                   3806: =cut
                   3807: 
                   3808: sub filecategorytypes {
1.356     albertel 3809:     my ($cat) = @_;
                   3810:     return @{$category_extensions{lc($cat)}};
1.112     bowersj2 3811: }
                   3812: 
                   3813: =pod
                   3814: 
1.648     raeburn  3815: =item * &fileembstyle() 
1.112     bowersj2 3816: 
                   3817: returns embedding style for a specified file type
                   3818: 
                   3819: =cut
                   3820: 
                   3821: sub fileembstyle {
                   3822:     return $fe{lc(shift(@_))};
1.169     www      3823: }
                   3824: 
1.351     www      3825: sub filemimetype {
                   3826:     return $fm{lc(shift(@_))};
                   3827: }
                   3828: 
1.169     www      3829: 
                   3830: sub filecategoryselect {
                   3831:     my ($name,$value)=@_;
1.189     matthew  3832:     return &select_form($value,$name,
1.970     raeburn  3833:                         {'' => &mt('Any category'), map { $_,$_ } sort(keys(%category_extensions))});
1.112     bowersj2 3834: }
                   3835: 
                   3836: =pod
                   3837: 
1.648     raeburn  3838: =item * &filedescription() 
1.112     bowersj2 3839: 
                   3840: returns description for a specified file type
                   3841: 
                   3842: =cut
                   3843: 
                   3844: sub filedescription {
1.188     matthew  3845:     my $file_description = $fd{lc(shift())};
                   3846:     $file_description =~ s:([\[\]]):~$1:g;
                   3847:     return &mt($file_description);
1.112     bowersj2 3848: }
                   3849: 
                   3850: =pod
                   3851: 
1.648     raeburn  3852: =item * &filedescriptionex() 
1.112     bowersj2 3853: 
                   3854: returns description for a specified file type with
                   3855: extra formatting
                   3856: 
                   3857: =cut
                   3858: 
                   3859: sub filedescriptionex {
                   3860:     my $ex=shift;
1.188     matthew  3861:     my $file_description = $fd{lc($ex)};
                   3862:     $file_description =~ s:([\[\]]):~$1:g;
                   3863:     return '.'.$ex.' '.&mt($file_description);
1.112     bowersj2 3864: }
                   3865: 
                   3866: # End of .tab access
                   3867: =pod
                   3868: 
                   3869: =back
                   3870: 
                   3871: =cut
                   3872: 
                   3873: # ------------------------------------------------------------------ File Types
                   3874: sub fileextensions {
                   3875:     return sort(keys(%fe));
                   3876: }
                   3877: 
1.97      www      3878: # ----------------------------------------------------------- Display Languages
                   3879: # returns a hash with all desired display languages
                   3880: #
                   3881: 
                   3882: sub display_languages {
                   3883:     my %languages=();
1.695     raeburn  3884:     foreach my $lang (&Apache::lonlocal::preferred_languages()) {
1.356     albertel 3885: 	$languages{$lang}=1;
1.97      www      3886:     }
                   3887:     &get_unprocessed_cgi($ENV{'QUERY_STRING'},['displaylanguage']);
1.258     albertel 3888:     if ($env{'form.displaylanguage'}) {
1.356     albertel 3889: 	foreach my $lang (split(/\s*(\,|\;|\:)\s*/,$env{'form.displaylanguage'})) {
                   3890: 	    $languages{$lang}=1;
1.97      www      3891:         }
                   3892:     }
                   3893:     return %languages;
1.14      harris41 3894: }
                   3895: 
1.582     albertel 3896: sub languages {
                   3897:     my ($possible_langs) = @_;
1.695     raeburn  3898:     my @preferred_langs = &Apache::lonlocal::preferred_languages();
1.582     albertel 3899:     if (!ref($possible_langs)) {
                   3900: 	if( wantarray ) {
                   3901: 	    return @preferred_langs;
                   3902: 	} else {
                   3903: 	    return $preferred_langs[0];
                   3904: 	}
                   3905:     }
                   3906:     my %possibilities = map { $_ => 1 } (@$possible_langs);
                   3907:     my @preferred_possibilities;
                   3908:     foreach my $preferred_lang (@preferred_langs) {
                   3909: 	if (exists($possibilities{$preferred_lang})) {
                   3910: 	    push(@preferred_possibilities, $preferred_lang);
                   3911: 	}
                   3912:     }
                   3913:     if( wantarray ) {
                   3914: 	return @preferred_possibilities;
                   3915:     }
                   3916:     return $preferred_possibilities[0];
                   3917: }
                   3918: 
1.742     raeburn  3919: sub user_lang {
                   3920:     my ($touname,$toudom,$fromcid) = @_;
                   3921:     my @userlangs;
                   3922:     if (($fromcid ne '') && ($env{'course.'.$fromcid.'.languages'} ne '')) {
                   3923:         @userlangs=(@userlangs,split(/\s*(\,|\;|\:)\s*/,
                   3924:                     $env{'course.'.$fromcid.'.languages'}));
                   3925:     } else {
                   3926:         my %langhash = &getlangs($touname,$toudom);
                   3927:         if ($langhash{'languages'} ne '') {
                   3928:             @userlangs = split(/\s*(\,|\;|\:)\s*/,$langhash{'languages'});
                   3929:         } else {
                   3930:             my %domdefs = &Apache::lonnet::get_domain_defaults($toudom);
                   3931:             if ($domdefs{'lang_def'} ne '') {
                   3932:                 @userlangs = ($domdefs{'lang_def'});
                   3933:             }
                   3934:         }
                   3935:     }
                   3936:     my @languages=&Apache::lonlocal::get_genlanguages(@userlangs);
                   3937:     my $user_lh = Apache::localize->get_handle(@languages);
                   3938:     return $user_lh;
                   3939: }
                   3940: 
                   3941: 
1.112     bowersj2 3942: ###############################################################
                   3943: ##               Student Answer Attempts                     ##
                   3944: ###############################################################
                   3945: 
                   3946: =pod
                   3947: 
                   3948: =head1 Alternate Problem Views
                   3949: 
                   3950: =over 4
                   3951: 
1.648     raeburn  3952: =item * &get_previous_attempt($symb, $username, $domain, $course,
1.1075.2.86  raeburn  3953:     $getattempt, $regexp, $gradesub, $usec, $identifier)
1.112     bowersj2 3954: 
                   3955: Return string with previous attempt on problem. Arguments:
                   3956: 
                   3957: =over 4
                   3958: 
                   3959: =item * $symb: Problem, including path
                   3960: 
                   3961: =item * $username: username of the desired student
                   3962: 
                   3963: =item * $domain: domain of the desired student
1.14      harris41 3964: 
1.112     bowersj2 3965: =item * $course: Course ID
1.14      harris41 3966: 
1.112     bowersj2 3967: =item * $getattempt: Leave blank for all attempts, otherwise put
                   3968:     something
1.14      harris41 3969: 
1.112     bowersj2 3970: =item * $regexp: if string matches this regexp, the string will be
                   3971:     sent to $gradesub
1.14      harris41 3972: 
1.112     bowersj2 3973: =item * $gradesub: routine that processes the string if it matches $regexp
1.14      harris41 3974: 
1.1075.2.86  raeburn  3975: =item * $usec: section of the desired student
                   3976: 
                   3977: =item * $identifier: counter for student (multiple students one problem) or
                   3978:     problem (one student; whole sequence).
                   3979: 
1.112     bowersj2 3980: =back
1.14      harris41 3981: 
1.112     bowersj2 3982: The output string is a table containing all desired attempts, if any.
1.16      harris41 3983: 
1.112     bowersj2 3984: =cut
1.1       albertel 3985: 
                   3986: sub get_previous_attempt {
1.1075.2.86  raeburn  3987:   my ($symb,$username,$domain,$course,$getattempt,$regexp,$gradesub,$usec,$identifier)=@_;
1.1       albertel 3988:   my $prevattempts='';
1.43      ng       3989:   no strict 'refs';
1.1       albertel 3990:   if ($symb) {
1.3       albertel 3991:     my (%returnhash)=
                   3992:       &Apache::lonnet::restore($symb,$course,$domain,$username);
1.1       albertel 3993:     if ($returnhash{'version'}) {
                   3994:       my %lasthash=();
                   3995:       my $version;
                   3996:       for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.91  raeburn  3997:         foreach my $key (reverse(sort(split(/\:/,$returnhash{$version.':keys'})))) {
                   3998:             if ($key =~ /\.rawrndseed$/) {
                   3999:                 my ($id) = ($key =~ /^(.+)\.rawrndseed$/);
                   4000:                 $lasthash{$id.'.rndseed'} = $returnhash{$version.':'.$key};
                   4001:             } else {
                   4002:                 $lasthash{$key}=$returnhash{$version.':'.$key};
                   4003:             }
1.19      harris41 4004:         }
1.1       albertel 4005:       }
1.596     albertel 4006:       $prevattempts=&start_data_table().&start_data_table_header_row();
                   4007:       $prevattempts.='<th>'.&mt('History').'</th>';
1.1075.2.86  raeburn  4008:       my (%typeparts,%lasthidden,%regraded,%hidestatus);
1.945     raeburn  4009:       my $showsurv=&Apache::lonnet::allowed('vas',$env{'request.course.id'});
1.356     albertel 4010:       foreach my $key (sort(keys(%lasthash))) {
                   4011: 	my ($ign,@parts) = split(/\./,$key);
1.41      ng       4012: 	if ($#parts > 0) {
1.31      albertel 4013: 	  my $data=$parts[-1];
1.989     raeburn  4014:           next if ($data eq 'foilorder');
1.31      albertel 4015: 	  pop(@parts);
1.1010    www      4016:           $prevattempts.='<th>'.&mt('Part ').join('.',@parts).'<br />'.$data.'&nbsp;</th>';
1.945     raeburn  4017:           if ($data eq 'type') {
                   4018:               unless ($showsurv) {
                   4019:                   my $id = join(',',@parts);
                   4020:                   $typeparts{$ign.'.'.$id} = $lasthash{$key};
1.978     raeburn  4021:                   if (($lasthash{$key} eq 'anonsurvey') || ($lasthash{$key} eq 'anonsurveycred')) {
                   4022:                       $lasthidden{$ign.'.'.$id} = 1;
                   4023:                   }
1.945     raeburn  4024:               }
1.1075.2.86  raeburn  4025:               if ($identifier ne '') {
                   4026:                   my $id = join(',',@parts);
                   4027:                   if (&Apache::lonnet::EXT("resource.$id.problemstatus",$symb,
                   4028:                                                $domain,$username,$usec,undef,$course) =~ /^no/) {
                   4029:                       $hidestatus{$ign.'.'.$id} = 1;
                   4030:                   }
                   4031:               }
                   4032:           } elsif ($data eq 'regrader') {
                   4033:               if (($identifier ne '') && (@parts)) {
                   4034:                   my $id = join(',',@parts);
                   4035:                   $regraded{$ign.'.'.$id} = 1;
                   4036:               }
1.1010    www      4037:           } 
1.31      albertel 4038: 	} else {
1.41      ng       4039: 	  if ($#parts == 0) {
                   4040: 	    $prevattempts.='<th>'.$parts[0].'</th>';
                   4041: 	  } else {
                   4042: 	    $prevattempts.='<th>'.$ign.'</th>';
                   4043: 	  }
1.31      albertel 4044: 	}
1.16      harris41 4045:       }
1.596     albertel 4046:       $prevattempts.=&end_data_table_header_row();
1.40      ng       4047:       if ($getattempt eq '') {
1.1075.2.86  raeburn  4048:         my (%solved,%resets,%probstatus);
                   4049:         if (($identifier ne '') && (keys(%regraded) > 0)) {
                   4050:             for ($version=1;$version<=$returnhash{'version'};$version++) {
                   4051:                 foreach my $id (keys(%regraded)) {
                   4052:                     if (($returnhash{$version.':'.$id.'.regrader'}) &&
                   4053:                         ($returnhash{$version.':'.$id.'.tries'} eq '') &&
                   4054:                         ($returnhash{$version.':'.$id.'.award'} eq '')) {
                   4055:                         push(@{$resets{$id}},$version);
                   4056:                     }
                   4057:                 }
                   4058:             }
                   4059:         }
1.40      ng       4060: 	for ($version=1;$version<=$returnhash{'version'};$version++) {
1.1075.2.86  raeburn  4061:             my (@hidden,@unsolved);
1.945     raeburn  4062:             if (%typeparts) {
                   4063:                 foreach my $id (keys(%typeparts)) {
1.1075.2.86  raeburn  4064:                     if (($returnhash{$version.':'.$id.'.type'} eq 'anonsurvey') ||
                   4065:                         ($returnhash{$version.':'.$id.'.type'} eq 'anonsurveycred')) {
1.945     raeburn  4066:                         push(@hidden,$id);
1.1075.2.86  raeburn  4067:                     } elsif ($identifier ne '') {
                   4068:                         unless (($returnhash{$version.':'.$id.'.type'} eq 'survey') ||
                   4069:                                 ($returnhash{$version.':'.$id.'.type'} eq 'surveycred') ||
                   4070:                                 ($hidestatus{$id})) {
                   4071:                             next if ((ref($resets{$id}) eq 'ARRAY') && grep(/^\Q$version\E$/,@{$resets{$id}}));
                   4072:                             if ($returnhash{$version.':'.$id.'.solved'} eq 'correct_by_student') {
                   4073:                                 push(@{$solved{$id}},$version);
                   4074:                             } elsif (($returnhash{$version.':'.$id.'.solved'} ne '') &&
                   4075:                                      (ref($solved{$id}) eq 'ARRAY')) {
                   4076:                                 my $skip;
                   4077:                                 if (ref($resets{$id}) eq 'ARRAY') {
                   4078:                                     foreach my $reset (@{$resets{$id}}) {
                   4079:                                         if ($reset > $solved{$id}[-1]) {
                   4080:                                             $skip=1;
                   4081:                                             last;
                   4082:                                         }
                   4083:                                     }
                   4084:                                 }
                   4085:                                 unless ($skip) {
                   4086:                                     my ($ign,$partslist) = split(/\./,$id,2);
                   4087:                                     push(@unsolved,$partslist);
                   4088:                                 }
                   4089:                             }
                   4090:                         }
1.945     raeburn  4091:                     }
                   4092:                 }
                   4093:             }
                   4094:             $prevattempts.=&start_data_table_row().
1.1075.2.86  raeburn  4095:                            '<td>'.&mt('Transaction [_1]',$version);
                   4096:             if (@unsolved) {
                   4097:                 $prevattempts .= '<span class="LC_nobreak"><label>'.
                   4098:                                  '<input type="checkbox" name="HIDE'.$identifier.'" value="'.$version.':'.join('_',@unsolved).'" />'.
                   4099:                                  &mt('Hide').'</label></span>';
                   4100:             }
                   4101:             $prevattempts .= '</td>';
1.945     raeburn  4102:             if (@hidden) {
                   4103:                 foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4104:                     next if ($key =~ /\.foilorder$/);
1.945     raeburn  4105:                     my $hide;
                   4106:                     foreach my $id (@hidden) {
                   4107:                         if ($key =~ /^\Q$id\E/) {
                   4108:                             $hide = 1;
                   4109:                             last;
                   4110:                         }
                   4111:                     }
                   4112:                     if ($hide) {
                   4113:                         my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4114:                         if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4115:                             my $value = &format_previous_attempt_value($key,
                   4116:                                              $returnhash{$version.':'.$key});
                   4117:                             $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4118:                         } else {
                   4119:                             $prevattempts.='<td>&nbsp;</td>';
                   4120:                         }
                   4121:                     } else {
                   4122:                         if ($key =~ /\./) {
1.1075.2.91  raeburn  4123:                             my $value = $returnhash{$version.':'.$key};
                   4124:                             if ($key =~ /\.rndseed$/) {
                   4125:                                 my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4126:                                 if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4127:                                     $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4128:                                 }
                   4129:                             }
                   4130:                             $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4131:                                            '&nbsp;</td>';
1.945     raeburn  4132:                         } else {
                   4133:                             $prevattempts.='<td>&nbsp;</td>';
                   4134:                         }
                   4135:                     }
                   4136:                 }
                   4137:             } else {
                   4138: 	        foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4139:                     next if ($key =~ /\.foilorder$/);
1.1075.2.91  raeburn  4140:                     my $value = $returnhash{$version.':'.$key};
                   4141:                     if ($key =~ /\.rndseed$/) {
                   4142:                         my ($id) = ($key =~ /^(.+)\.rndseed$/);
                   4143:                         if (exists($returnhash{$version.':'.$id.'.rawrndseed'})) {
                   4144:                             $value = $returnhash{$version.':'.$id.'.rawrndseed'};
                   4145:                         }
                   4146:                     }
                   4147:                     $prevattempts.='<td>'.&format_previous_attempt_value($key,$value).
                   4148:                                    '&nbsp;</td>';
1.945     raeburn  4149: 	        }
                   4150:             }
                   4151: 	    $prevattempts.=&end_data_table_row();
1.40      ng       4152: 	 }
1.1       albertel 4153:       }
1.945     raeburn  4154:       my @currhidden = keys(%lasthidden);
1.596     albertel 4155:       $prevattempts.=&start_data_table_row().'<td>'.&mt('Current').'</td>';
1.356     albertel 4156:       foreach my $key (sort(keys(%lasthash))) {
1.989     raeburn  4157:           next if ($key =~ /\.foilorder$/);
1.945     raeburn  4158:           if (%typeparts) {
                   4159:               my $hidden;
                   4160:               foreach my $id (@currhidden) {
                   4161:                   if ($key =~ /^\Q$id\E/) {
                   4162:                       $hidden = 1;
                   4163:                       last;
                   4164:                   }
                   4165:               }
                   4166:               if ($hidden) {
                   4167:                   my ($id,$data) = ($key =~ /^(.+)\.([^.]+)$/);
                   4168:                   if (($data eq 'award') || ($data eq 'awarddetail')) {
                   4169:                       my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4170:                       if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4171:                           $value = &$gradesub($value);
                   4172:                       }
                   4173:                       $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4174:                   } else {
                   4175:                       $prevattempts.='<td>&nbsp;</td>';
                   4176:                   }
                   4177:               } else {
                   4178:                   my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4179:                   if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4180:                       $value = &$gradesub($value);
                   4181:                   }
                   4182:                   $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4183:               }
                   4184:           } else {
                   4185: 	      my $value = &format_previous_attempt_value($key,$lasthash{$key});
                   4186: 	      if ($key =~/$regexp$/ && (defined &$gradesub)) {
                   4187:                   $value = &$gradesub($value);
                   4188:               }
                   4189: 	      $prevattempts.='<td>'.$value.'&nbsp;</td>';
                   4190:           }
1.16      harris41 4191:       }
1.596     albertel 4192:       $prevattempts.= &end_data_table_row().&end_data_table();
1.1       albertel 4193:     } else {
1.596     albertel 4194:       $prevattempts=
                   4195: 	  &start_data_table().&start_data_table_row().
                   4196: 	  '<td>'.&mt('Nothing submitted - no attempts.').'</td>'.
                   4197: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4198:     }
                   4199:   } else {
1.596     albertel 4200:     $prevattempts=
                   4201: 	  &start_data_table().&start_data_table_row().
                   4202: 	  '<td>'.&mt('No data.').'</td>'.
                   4203: 	  &end_data_table_row().&end_data_table();
1.1       albertel 4204:   }
1.10      albertel 4205: }
                   4206: 
1.581     albertel 4207: sub format_previous_attempt_value {
                   4208:     my ($key,$value) = @_;
1.1011    www      4209:     if (($key =~ /timestamp/) || ($key=~/duedate/)) {
1.581     albertel 4210: 	$value = &Apache::lonlocal::locallocaltime($value);
                   4211:     } elsif (ref($value) eq 'ARRAY') {
                   4212: 	$value = '('.join(', ', @{ $value }).')';
1.988     raeburn  4213:     } elsif ($key =~ /answerstring$/) {
                   4214:         my %answers = &Apache::lonnet::str2hash($value);
                   4215:         my @anskeys = sort(keys(%answers));
                   4216:         if (@anskeys == 1) {
                   4217:             my $answer = $answers{$anskeys[0]};
1.1001    raeburn  4218:             if ($answer =~ m{\0}) {
                   4219:                 $answer =~ s{\0}{,}g;
1.988     raeburn  4220:             }
                   4221:             my $tag_internal_answer_name = 'INTERNAL';
                   4222:             if ($anskeys[0] eq $tag_internal_answer_name) {
                   4223:                 $value = $answer; 
                   4224:             } else {
                   4225:                 $value = $anskeys[0].'='.$answer;
                   4226:             }
                   4227:         } else {
                   4228:             foreach my $ans (@anskeys) {
                   4229:                 my $answer = $answers{$ans};
1.1001    raeburn  4230:                 if ($answer =~ m{\0}) {
                   4231:                     $answer =~ s{\0}{,}g;
1.988     raeburn  4232:                 }
                   4233:                 $value .=  $ans.'='.$answer.'<br />';;
                   4234:             } 
                   4235:         }
1.581     albertel 4236:     } else {
                   4237: 	$value = &unescape($value);
                   4238:     }
                   4239:     return $value;
                   4240: }
                   4241: 
                   4242: 
1.107     albertel 4243: sub relative_to_absolute {
                   4244:     my ($url,$output)=@_;
                   4245:     my $parser=HTML::TokeParser->new(\$output);
                   4246:     my $token;
                   4247:     my $thisdir=$url;
                   4248:     my @rlinks=();
                   4249:     while ($token=$parser->get_token) {
                   4250: 	if ($token->[0] eq 'S') {
                   4251: 	    if ($token->[1] eq 'a') {
                   4252: 		if ($token->[2]->{'href'}) {
                   4253: 		    $rlinks[$#rlinks+1]=$token->[2]->{'href'};
                   4254: 		}
                   4255: 	    } elsif ($token->[1] eq 'img' || $token->[1] eq 'embed' ) {
                   4256: 		$rlinks[$#rlinks+1]=$token->[2]->{'src'};
                   4257: 	    } elsif ($token->[1] eq 'base') {
                   4258: 		$thisdir=$token->[2]->{'href'};
                   4259: 	    }
                   4260: 	}
                   4261:     }
                   4262:     $thisdir=~s-/[^/]*$--;
1.356     albertel 4263:     foreach my $link (@rlinks) {
1.726     raeburn  4264: 	unless (($link=~/^https?\:\/\//i) ||
1.356     albertel 4265: 		($link=~/^\//) ||
                   4266: 		($link=~/^javascript:/i) ||
                   4267: 		($link=~/^mailto:/i) ||
                   4268: 		($link=~/^\#/)) {
                   4269: 	    my $newlocation=&Apache::lonnet::hreflocation($thisdir,$link);
                   4270: 	    $output=~s/(\"|\'|\=\s*)\Q$link\E(\"|\'|\s|\>)/$1$newlocation$2/;
1.107     albertel 4271: 	}
                   4272:     }
                   4273: # -------------------------------------------------- Deal with Applet codebases
                   4274:     $output=~s/(\<applet[^\>]+)(codebase\=[^\S\>]+)*([^\>]*)\>/$1.($2?$2:' codebase="'.$thisdir.'"').$3.'>'/gei;
                   4275:     return $output;
                   4276: }
                   4277: 
1.112     bowersj2 4278: =pod
                   4279: 
1.648     raeburn  4280: =item * &get_student_view()
1.112     bowersj2 4281: 
                   4282: show a snapshot of what student was looking at
                   4283: 
                   4284: =cut
                   4285: 
1.10      albertel 4286: sub get_student_view {
1.186     albertel 4287:   my ($symb,$username,$domain,$courseid,$target,$moreenv) = @_;
1.114     www      4288:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4289:   my (%form);
1.10      albertel 4290:   my @elements=('symb','courseid','domain','username');
                   4291:   foreach my $element (@elements) {
1.186     albertel 4292:       $form{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4293:   }
1.186     albertel 4294:   if (defined($moreenv)) {
                   4295:       %form=(%form,%{$moreenv});
                   4296:   }
1.236     albertel 4297:   if (defined($target)) { $form{'grade_target'} = $target; }
1.107     albertel 4298:   $feedurl=&Apache::lonnet::clutter($feedurl);
1.650     www      4299:   my ($userview,$response)=&Apache::lonnet::ssi_body($feedurl,%form);
1.11      albertel 4300:   $userview=~s/\<body[^\>]*\>//gi;
                   4301:   $userview=~s/\<\/body\>//gi;
                   4302:   $userview=~s/\<html\>//gi;
                   4303:   $userview=~s/\<\/html\>//gi;
                   4304:   $userview=~s/\<head\>//gi;
                   4305:   $userview=~s/\<\/head\>//gi;
                   4306:   $userview=~s/action\s*\=/would_be_action\=/gi;
1.107     albertel 4307:   $userview=&relative_to_absolute($feedurl,$userview);
1.650     www      4308:   if (wantarray) {
                   4309:      return ($userview,$response);
                   4310:   } else {
                   4311:      return $userview;
                   4312:   }
                   4313: }
                   4314: 
                   4315: sub get_student_view_with_retries {
                   4316:   my ($symb,$retries,$username,$domain,$courseid,$target,$moreenv) = @_;
                   4317: 
                   4318:     my $ok = 0;                 # True if we got a good response.
                   4319:     my $content;
                   4320:     my $response;
                   4321: 
                   4322:     # Try to get the student_view done. within the retries count:
                   4323:     
                   4324:     do {
                   4325:          ($content, $response) = &get_student_view($symb,$username,$domain,$courseid,$target,$moreenv);
                   4326:          $ok      = $response->is_success;
                   4327:          if (!$ok) {
                   4328:             &Apache::lonnet::logthis("Failed get_student_view_with_retries on $symb: ".$response->is_success.', '.$response->code.', '.$response->message);
                   4329:          }
                   4330:          $retries--;
                   4331:     } while (!$ok && ($retries > 0));
                   4332:     
                   4333:     if (!$ok) {
                   4334:        $content = '';          # On error return an empty content.
                   4335:     }
1.651     www      4336:     if (wantarray) {
                   4337:        return ($content, $response);
                   4338:     } else {
                   4339:        return $content;
                   4340:     }
1.11      albertel 4341: }
                   4342: 
1.112     bowersj2 4343: =pod
                   4344: 
1.648     raeburn  4345: =item * &get_student_answers() 
1.112     bowersj2 4346: 
                   4347: show a snapshot of how student was answering problem
                   4348: 
                   4349: =cut
                   4350: 
1.11      albertel 4351: sub get_student_answers {
1.100     sakharuk 4352:   my ($symb,$username,$domain,$courseid,%form) = @_;
1.114     www      4353:   my ($map,$id,$feedurl) = &Apache::lonnet::decode_symb($symb);
1.186     albertel 4354:   my (%moreenv);
1.11      albertel 4355:   my @elements=('symb','courseid','domain','username');
                   4356:   foreach my $element (@elements) {
1.186     albertel 4357:     $moreenv{'grade_'.$element}=eval '$'.$element #'
1.10      albertel 4358:   }
1.186     albertel 4359:   $moreenv{'grade_target'}='answer';
                   4360:   %moreenv=(%form,%moreenv);
1.497     raeburn  4361:   $feedurl = &Apache::lonnet::clutter($feedurl);
                   4362:   my $userview=&Apache::lonnet::ssi($feedurl,%moreenv);
1.10      albertel 4363:   return $userview;
1.1       albertel 4364: }
1.116     albertel 4365: 
                   4366: =pod
                   4367: 
                   4368: =item * &submlink()
                   4369: 
1.242     albertel 4370: Inputs: $text $uname $udom $symb $target
1.116     albertel 4371: 
                   4372: Returns: A link to grades.pm such as to see the SUBM view of a student
                   4373: 
                   4374: =cut
                   4375: 
                   4376: ###############################################
                   4377: sub submlink {
1.242     albertel 4378:     my ($text,$uname,$udom,$symb,$target)=@_;
1.116     albertel 4379:     if (!($uname && $udom)) {
                   4380: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4381: 	    &Apache::lonnet::whichuser($symb);
1.116     albertel 4382: 	if (!$symb) { $symb=$cursymb; }
                   4383:     }
1.254     matthew  4384:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4385:     $symb=&escape($symb);
1.960     bisitz   4386:     if ($target) { $target=" target=\"$target\""; }
                   4387:     return
                   4388:         '<a href="/adm/grades?command=submission'.
                   4389:         '&amp;symb='.$symb.
                   4390:         '&amp;student='.$uname.
                   4391:         '&amp;userdom='.$udom.'"'.
                   4392:         $target.'>'.$text.'</a>';
1.242     albertel 4393: }
                   4394: ##############################################
                   4395: 
                   4396: =pod
                   4397: 
                   4398: =item * &pgrdlink()
                   4399: 
                   4400: Inputs: $text $uname $udom $symb $target
                   4401: 
                   4402: Returns: A link to grades.pm such as to see the PGRD view of a student
                   4403: 
                   4404: =cut
                   4405: 
                   4406: ###############################################
                   4407: sub pgrdlink {
                   4408:     my $link=&submlink(@_);
                   4409:     $link=~s/(&command=submission)/$1&showgrading=yes/;
                   4410:     return $link;
                   4411: }
                   4412: ##############################################
                   4413: 
                   4414: =pod
                   4415: 
                   4416: =item * &pprmlink()
                   4417: 
                   4418: Inputs: $text $uname $udom $symb $target
                   4419: 
                   4420: Returns: A link to parmset.pm such as to see the PPRM view of a
1.283     albertel 4421: student and a specific resource
1.242     albertel 4422: 
                   4423: =cut
                   4424: 
                   4425: ###############################################
                   4426: sub pprmlink {
                   4427:     my ($text,$uname,$udom,$symb,$target)=@_;
                   4428:     if (!($uname && $udom)) {
                   4429: 	(my $cursymb, my $courseid,$udom,$uname)=
1.463     albertel 4430: 	    &Apache::lonnet::whichuser($symb);
1.242     albertel 4431: 	if (!$symb) { $symb=$cursymb; }
                   4432:     }
1.254     matthew  4433:     if (!$symb) { $symb=&Apache::lonnet::symbread(); }
1.369     www      4434:     $symb=&escape($symb);
1.242     albertel 4435:     if ($target) { $target="target=\"$target\""; }
1.595     albertel 4436:     return '<a href="/adm/parmset?command=set&amp;'.
                   4437: 	'symb='.$symb.'&amp;uname='.$uname.
                   4438: 	'&amp;udom='.$udom.'" '.$target.'>'.$text.'</a>';
1.116     albertel 4439: }
                   4440: ##############################################
1.37      matthew  4441: 
1.112     bowersj2 4442: =pod
                   4443: 
                   4444: =back
                   4445: 
                   4446: =cut
                   4447: 
1.37      matthew  4448: ###############################################
1.51      www      4449: 
                   4450: 
                   4451: sub timehash {
1.687     raeburn  4452:     my ($thistime) = @_;
                   4453:     my $timezone = &Apache::lonlocal::gettimezone();
                   4454:     my $dt = DateTime->from_epoch(epoch => $thistime)
                   4455:                      ->set_time_zone($timezone);
                   4456:     my $wday = $dt->day_of_week();
                   4457:     if ($wday == 7) { $wday = 0; }
                   4458:     return ( 'second' => $dt->second(),
                   4459:              'minute' => $dt->minute(),
                   4460:              'hour'   => $dt->hour(),
                   4461:              'day'     => $dt->day_of_month(),
                   4462:              'month'   => $dt->month(),
                   4463:              'year'    => $dt->year(),
                   4464:              'weekday' => $wday,
                   4465:              'dayyear' => $dt->day_of_year(),
                   4466:              'dlsav'   => $dt->is_dst() );
1.51      www      4467: }
                   4468: 
1.370     www      4469: sub utc_string {
                   4470:     my ($date)=@_;
1.371     www      4471:     return strftime("%Y%m%dT%H%M%SZ",gmtime($date));
1.370     www      4472: }
                   4473: 
1.51      www      4474: sub maketime {
                   4475:     my %th=@_;
1.687     raeburn  4476:     my ($epoch_time,$timezone,$dt);
                   4477:     $timezone = &Apache::lonlocal::gettimezone();
                   4478:     eval {
                   4479:         $dt = DateTime->new( year   => $th{'year'},
                   4480:                              month  => $th{'month'},
                   4481:                              day    => $th{'day'},
                   4482:                              hour   => $th{'hour'},
                   4483:                              minute => $th{'minute'},
                   4484:                              second => $th{'second'},
                   4485:                              time_zone => $timezone,
                   4486:                          );
                   4487:     };
                   4488:     if (!$@) {
                   4489:         $epoch_time = $dt->epoch;
                   4490:         if ($epoch_time) {
                   4491:             return $epoch_time;
                   4492:         }
                   4493:     }
1.51      www      4494:     return POSIX::mktime(
                   4495:         ($th{'seconds'},$th{'minutes'},$th{'hours'},
1.210     www      4496:          $th{'day'},$th{'month'}-1,$th{'year'}-1900,0,0,-1));
1.70      www      4497: }
                   4498: 
                   4499: #########################################
1.51      www      4500: 
                   4501: sub findallcourses {
1.482     raeburn  4502:     my ($roles,$uname,$udom) = @_;
1.355     albertel 4503:     my %roles;
                   4504:     if (ref($roles)) { %roles = map { $_ => 1 } @{$roles}; }
1.348     albertel 4505:     my %courses;
1.51      www      4506:     my $now=time;
1.482     raeburn  4507:     if (!defined($uname)) {
                   4508:         $uname = $env{'user.name'};
                   4509:     }
                   4510:     if (!defined($udom)) {
                   4511:         $udom = $env{'user.domain'};
                   4512:     }
                   4513:     if (($uname ne $env{'user.name'}) || ($udom ne $env{'user.domain'})) {
1.1073    raeburn  4514:         my %roleshash = &Apache::lonnet::dump('roles',$udom,$uname);
1.482     raeburn  4515:         if (!%roles) {
                   4516:             %roles = (
                   4517:                        cc => 1,
1.907     raeburn  4518:                        co => 1,
1.482     raeburn  4519:                        in => 1,
                   4520:                        ep => 1,
                   4521:                        ta => 1,
                   4522:                        cr => 1,
                   4523:                        st => 1,
                   4524:              );
                   4525:         }
                   4526:         foreach my $entry (keys(%roleshash)) {
                   4527:             my ($trole,$tend,$tstart) = split(/_/,$roleshash{$entry});
                   4528:             if ($trole =~ /^cr/) { 
                   4529:                 next if (!exists($roles{$trole}) && !exists($roles{'cr'}));
                   4530:             } else {
                   4531:                 next if (!exists($roles{$trole}));
                   4532:             }
                   4533:             if ($tend) {
                   4534:                 next if ($tend < $now);
                   4535:             }
                   4536:             if ($tstart) {
                   4537:                 next if ($tstart > $now);
                   4538:             }
1.1058    raeburn  4539:             my ($cdom,$cnum,$sec,$cnumpart,$secpart,$role);
1.482     raeburn  4540:             (undef,$cdom,$cnumpart,$secpart) = split(/\//,$entry);
1.1058    raeburn  4541:             my $value = $trole.'/'.$cdom.'/';
1.482     raeburn  4542:             if ($secpart eq '') {
                   4543:                 ($cnum,$role) = split(/_/,$cnumpart); 
                   4544:                 $sec = 'none';
1.1058    raeburn  4545:                 $value .= $cnum.'/';
1.482     raeburn  4546:             } else {
                   4547:                 $cnum = $cnumpart;
                   4548:                 ($sec,$role) = split(/_/,$secpart);
1.1058    raeburn  4549:                 $value .= $cnum.'/'.$sec;
                   4550:             }
                   4551:             if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4552:                 unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4553:                     push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4554:                 }
                   4555:             } else {
                   4556:                 @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.490     raeburn  4557:             }
1.482     raeburn  4558:         }
                   4559:     } else {
                   4560:         foreach my $key (keys(%env)) {
1.483     albertel 4561: 	    if ( $key=~m{^user\.role\.(\w+)\./($match_domain)/($match_courseid)/?(\w*)$} ||
                   4562:                  $key=~m{^user\.role\.(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_courseid)/?(\w*)$}) {
1.482     raeburn  4563: 	        my ($role,$cdom,$cnum,$sec) = ($1,$2,$3,$4);
                   4564: 	        next if ($role eq 'ca' || $role eq 'aa');
                   4565: 	        next if (%roles && !exists($roles{$role}));
                   4566: 	        my ($starttime,$endtime)=split(/\./,$env{$key});
                   4567:                 my $active=1;
                   4568:                 if ($starttime) {
                   4569: 		    if ($now<$starttime) { $active=0; }
                   4570:                 }
                   4571:                 if ($endtime) {
                   4572:                     if ($now>$endtime) { $active=0; }
                   4573:                 }
                   4574:                 if ($active) {
1.1058    raeburn  4575:                     my $value = $role.'/'.$cdom.'/'.$cnum.'/';
1.482     raeburn  4576:                     if ($sec eq '') {
                   4577:                         $sec = 'none';
1.1058    raeburn  4578:                     } else {
                   4579:                         $value .= $sec;
                   4580:                     }
                   4581:                     if (ref($courses{$cdom.'_'.$cnum}{$sec}) eq 'ARRAY') {
                   4582:                         unless (grep(/^\Q$value\E$/,@{$courses{$cdom.'_'.$cnum}{$sec}})) {
                   4583:                             push(@{$courses{$cdom.'_'.$cnum}{$sec}},$value);
                   4584:                         }
                   4585:                     } else {
                   4586:                         @{$courses{$cdom.'_'.$cnum}{$sec}} = ($value);
1.482     raeburn  4587:                     }
1.474     raeburn  4588:                 }
                   4589:             }
1.51      www      4590:         }
                   4591:     }
1.474     raeburn  4592:     return %courses;
1.51      www      4593: }
1.37      matthew  4594: 
1.54      www      4595: ###############################################
1.474     raeburn  4596: 
                   4597: sub blockcheck {
1.1075.2.73  raeburn  4598:     my ($setters,$activity,$uname,$udom,$url,$is_course) = @_;
1.490     raeburn  4599: 
1.1075.2.73  raeburn  4600:     if (defined($udom) && defined($uname)) {
                   4601:         # If uname and udom are for a course, check for blocks in the course.
                   4602:         if (($is_course) || (&Apache::lonnet::is_course($udom,$uname))) {
                   4603:             my ($startblock,$endblock,$triggerblock) =
                   4604:                 &get_blocks($setters,$activity,$udom,$uname,$url);
                   4605:             return ($startblock,$endblock,$triggerblock);
                   4606:         }
                   4607:     } else {
1.490     raeburn  4608:         $udom = $env{'user.domain'};
                   4609:         $uname = $env{'user.name'};
                   4610:     }
                   4611: 
1.502     raeburn  4612:     my $startblock = 0;
                   4613:     my $endblock = 0;
1.1062    raeburn  4614:     my $triggerblock = '';
1.482     raeburn  4615:     my %live_courses = &findallcourses(undef,$uname,$udom);
1.474     raeburn  4616: 
1.490     raeburn  4617:     # If uname is for a user, and activity is course-specific, i.e.,
                   4618:     # boards, chat or groups, check for blocking in current course only.
1.474     raeburn  4619: 
1.490     raeburn  4620:     if (($activity eq 'boards' || $activity eq 'chat' ||
1.1075.2.73  raeburn  4621:          $activity eq 'groups' || $activity eq 'printout') &&
                   4622:         ($env{'request.course.id'})) {
1.490     raeburn  4623:         foreach my $key (keys(%live_courses)) {
                   4624:             if ($key ne $env{'request.course.id'}) {
                   4625:                 delete($live_courses{$key});
                   4626:             }
                   4627:         }
                   4628:     }
                   4629: 
                   4630:     my $otheruser = 0;
                   4631:     my %own_courses;
                   4632:     if ((($uname ne $env{'user.name'})) || ($udom ne $env{'user.domain'})) {
                   4633:         # Resource belongs to user other than current user.
                   4634:         $otheruser = 1;
                   4635:         # Gather courses for current user
                   4636:         %own_courses = 
                   4637:             &findallcourses(undef,$env{'user.name'},$env{'user.domain'});
                   4638:     }
                   4639: 
                   4640:     # Gather active course roles - course coordinator, instructor, 
                   4641:     # exam proctor, ta, student, or custom role.
1.474     raeburn  4642: 
                   4643:     foreach my $course (keys(%live_courses)) {
1.482     raeburn  4644:         my ($cdom,$cnum);
                   4645:         if ((defined($env{'course.'.$course.'.domain'})) && (defined($env{'course.'.$course.'.num'}))) {
                   4646:             $cdom = $env{'course.'.$course.'.domain'};
                   4647:             $cnum = $env{'course.'.$course.'.num'};
                   4648:         } else {
1.490     raeburn  4649:             ($cdom,$cnum) = split(/_/,$course); 
1.482     raeburn  4650:         }
                   4651:         my $no_ownblock = 0;
                   4652:         my $no_userblock = 0;
1.533     raeburn  4653:         if ($otheruser && $activity ne 'com') {
1.490     raeburn  4654:             # Check if current user has 'evb' priv for this
                   4655:             if (defined($own_courses{$course})) {
                   4656:                 foreach my $sec (keys(%{$own_courses{$course}})) {
                   4657:                     my $checkrole = 'cm./'.$cdom.'/'.$cnum;
                   4658:                     if ($sec ne 'none') {
                   4659:                         $checkrole .= '/'.$sec;
                   4660:                     }
                   4661:                     if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4662:                         $no_ownblock = 1;
                   4663:                         last;
                   4664:                     }
                   4665:                 }
                   4666:             }
                   4667:             # if they have 'evb' priv and are currently not playing student
                   4668:             next if (($no_ownblock) &&
                   4669:                  ($env{'request.role'} !~ m{^st\./$cdom/$cnum}));
                   4670:         }
1.474     raeburn  4671:         foreach my $sec (keys(%{$live_courses{$course}})) {
1.482     raeburn  4672:             my $checkrole = 'cm./'.$cdom.'/'.$cnum;
1.474     raeburn  4673:             if ($sec ne 'none') {
1.482     raeburn  4674:                 $checkrole .= '/'.$sec;
1.474     raeburn  4675:             }
1.490     raeburn  4676:             if ($otheruser) {
                   4677:                 # Resource belongs to user other than current user.
                   4678:                 # Assemble privs for that user, and check for 'evb' priv.
1.1058    raeburn  4679:                 my (%allroles,%userroles);
                   4680:                 if (ref($live_courses{$course}{$sec}) eq 'ARRAY') {
                   4681:                     foreach my $entry (@{$live_courses{$course}{$sec}}) { 
                   4682:                         my ($trole,$tdom,$tnum,$tsec);
                   4683:                         if ($entry =~ /^cr/) {
                   4684:                             ($trole,$tdom,$tnum,$tsec) = 
                   4685:                                 ($entry =~ m|^(cr/$match_domain/$match_username/\w+)\./($match_domain)/($match_username)/?(\w*)$|);
                   4686:                         } else {
                   4687:                            ($trole,$tdom,$tnum,$tsec) = split(/\//,$entry);
                   4688:                         }
                   4689:                         my ($spec,$area,$trest);
                   4690:                         $area = '/'.$tdom.'/'.$tnum;
                   4691:                         $trest = $tnum;
                   4692:                         if ($tsec ne '') {
                   4693:                             $area .= '/'.$tsec;
                   4694:                             $trest .= '/'.$tsec;
                   4695:                         }
                   4696:                         $spec = $trole.'.'.$area;
                   4697:                         if ($trole =~ /^cr/) {
                   4698:                             &Apache::lonnet::custom_roleprivs(\%allroles,$trole,
                   4699:                                                               $tdom,$spec,$trest,$area);
                   4700:                         } else {
                   4701:                             &Apache::lonnet::standard_roleprivs(\%allroles,$trole,
                   4702:                                                                 $tdom,$spec,$trest,$area);
                   4703:                         }
                   4704:                     }
1.1075.2.124  raeburn  4705:                     my ($author,$adv,$rar) = &Apache::lonnet::set_userprivs(\%userroles,\%allroles);
1.1058    raeburn  4706:                     if ($userroles{'user.priv.'.$checkrole} =~ /evb\&([^\:]*)/) {
                   4707:                         if ($1) {
                   4708:                             $no_userblock = 1;
                   4709:                             last;
                   4710:                         }
1.486     raeburn  4711:                     }
                   4712:                 }
1.490     raeburn  4713:             } else {
                   4714:                 # Resource belongs to current user
                   4715:                 # Check for 'evb' priv via lonnet::allowed().
1.482     raeburn  4716:                 if (&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) {
                   4717:                     $no_ownblock = 1;
                   4718:                     last;
                   4719:                 }
1.474     raeburn  4720:             }
                   4721:         }
                   4722:         # if they have the evb priv and are currently not playing student
1.482     raeburn  4723:         next if (($no_ownblock) &&
1.491     albertel 4724:                  ($env{'request.role'} !~ m{^st\./\Q$cdom\E/\Q$cnum\E}));
1.482     raeburn  4725:         next if ($no_userblock);
1.474     raeburn  4726: 
1.1075.2.128  raeburn  4727:         # Retrieve blocking times and identity of blocker for course
1.490     raeburn  4728:         # of specified user, unless user has 'evb' privilege.
1.502     raeburn  4729:         
1.1062    raeburn  4730:         my ($start,$end,$trigger) = 
                   4731:             &get_blocks($setters,$activity,$cdom,$cnum,$url);
1.502     raeburn  4732:         if (($start != 0) && 
                   4733:             (($startblock == 0) || ($startblock > $start))) {
                   4734:             $startblock = $start;
1.1062    raeburn  4735:             if ($trigger ne '') {
                   4736:                 $triggerblock = $trigger;
                   4737:             }
1.502     raeburn  4738:         }
                   4739:         if (($end != 0)  &&
                   4740:             (($endblock == 0) || ($endblock < $end))) {
                   4741:             $endblock = $end;
1.1062    raeburn  4742:             if ($trigger ne '') {
                   4743:                 $triggerblock = $trigger;
                   4744:             }
1.502     raeburn  4745:         }
1.490     raeburn  4746:     }
1.1062    raeburn  4747:     return ($startblock,$endblock,$triggerblock);
1.490     raeburn  4748: }
                   4749: 
                   4750: sub get_blocks {
1.1062    raeburn  4751:     my ($setters,$activity,$cdom,$cnum,$url) = @_;
1.490     raeburn  4752:     my $startblock = 0;
                   4753:     my $endblock = 0;
1.1062    raeburn  4754:     my $triggerblock = '';
1.490     raeburn  4755:     my $course = $cdom.'_'.$cnum;
                   4756:     $setters->{$course} = {};
                   4757:     $setters->{$course}{'staff'} = [];
                   4758:     $setters->{$course}{'times'} = [];
1.1062    raeburn  4759:     $setters->{$course}{'triggers'} = [];
                   4760:     my (@blockers,%triggered);
                   4761:     my $now = time;
                   4762:     my %commblocks = &Apache::lonnet::get_comm_blocks($cdom,$cnum);
                   4763:     if ($activity eq 'docs') {
                   4764:         @blockers = &Apache::lonnet::has_comm_blocking('bre',undef,$url,\%commblocks);
                   4765:         foreach my $block (@blockers) {
                   4766:             if ($block =~ /^firstaccess____(.+)$/) {
                   4767:                 my $item = $1;
                   4768:                 my $type = 'map';
                   4769:                 my $timersymb = $item;
                   4770:                 if ($item eq 'course') {
                   4771:                     $type = 'course';
                   4772:                 } elsif ($item =~ /___\d+___/) {
                   4773:                     $type = 'resource';
                   4774:                 } else {
                   4775:                     $timersymb = &Apache::lonnet::symbread($item);
                   4776:                 }
                   4777:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4778:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb};
                   4779:                 $triggered{$block} = {
                   4780:                                        start => $start,
                   4781:                                        end   => $end,
                   4782:                                        type  => $type,
                   4783:                                      };
                   4784:             }
                   4785:         }
                   4786:     } else {
                   4787:         foreach my $block (keys(%commblocks)) {
                   4788:             if ($block =~ m/^(\d+)____(\d+)$/) { 
                   4789:                 my ($start,$end) = ($1,$2);
                   4790:                 if ($start <= time && $end >= time) {
                   4791:                     if (ref($commblocks{$block}) eq 'HASH') {
                   4792:                         if (ref($commblocks{$block}{'blocks'}) eq 'HASH') {
                   4793:                             if ($commblocks{$block}{'blocks'}{$activity} eq 'on') {
                   4794:                                 unless(grep(/^\Q$block\E$/,@blockers)) {
                   4795:                                     push(@blockers,$block);
                   4796:                                 }
                   4797:                             }
                   4798:                         }
                   4799:                     }
                   4800:                 }
                   4801:             } elsif ($block =~ /^firstaccess____(.+)$/) {
                   4802:                 my $item = $1;
                   4803:                 my $timersymb = $item; 
                   4804:                 my $type = 'map';
                   4805:                 if ($item eq 'course') {
                   4806:                     $type = 'course';
                   4807:                 } elsif ($item =~ /___\d+___/) {
                   4808:                     $type = 'resource';
                   4809:                 } else {
                   4810:                     $timersymb = &Apache::lonnet::symbread($item);
                   4811:                 }
                   4812:                 my $start = $env{'course.'.$cdom.'_'.$cnum.'.firstaccess.'.$timersymb};
                   4813:                 my $end = $start + $env{'course.'.$cdom.'_'.$cnum.'.timerinterval.'.$timersymb}; 
                   4814:                 if ($start && $end) {
                   4815:                     if (($start <= time) && ($end >= time)) {
                   4816:                         unless (grep(/^\Q$block\E$/,@blockers)) {
                   4817:                             push(@blockers,$block);
                   4818:                             $triggered{$block} = {
                   4819:                                                    start => $start,
                   4820:                                                    end   => $end,
                   4821:                                                    type  => $type,
                   4822:                                                  };
                   4823:                         }
                   4824:                     }
1.490     raeburn  4825:                 }
1.1062    raeburn  4826:             }
                   4827:         }
                   4828:     }
                   4829:     foreach my $blocker (@blockers) {
                   4830:         my ($staff_name,$staff_dom,$title,$blocks) =
                   4831:             &parse_block_record($commblocks{$blocker});
                   4832:         push(@{$$setters{$course}{'staff'}},[$staff_name,$staff_dom]);
                   4833:         my ($start,$end,$triggertype);
                   4834:         if ($blocker =~ m/^(\d+)____(\d+)$/) {
                   4835:             ($start,$end) = ($1,$2);
                   4836:         } elsif (ref($triggered{$blocker}) eq 'HASH') {
                   4837:             $start = $triggered{$blocker}{'start'};
                   4838:             $end = $triggered{$blocker}{'end'};
                   4839:             $triggertype = $triggered{$blocker}{'type'};
                   4840:         }
                   4841:         if ($start) {
                   4842:             push(@{$$setters{$course}{'times'}}, [$start,$end]);
                   4843:             if ($triggertype) {
                   4844:                 push(@{$$setters{$course}{'triggers'}},$triggertype);
                   4845:             } else {
                   4846:                 push(@{$$setters{$course}{'triggers'}},0);
                   4847:             }
                   4848:             if ( ($startblock == 0) || ($startblock > $start) ) {
                   4849:                 $startblock = $start;
                   4850:                 if ($triggertype) {
                   4851:                     $triggerblock = $blocker;
1.474     raeburn  4852:                 }
                   4853:             }
1.1062    raeburn  4854:             if ( ($endblock == 0) || ($endblock < $end) ) {
                   4855:                $endblock = $end;
                   4856:                if ($triggertype) {
                   4857:                    $triggerblock = $blocker;
                   4858:                }
                   4859:             }
1.474     raeburn  4860:         }
                   4861:     }
1.1062    raeburn  4862:     return ($startblock,$endblock,$triggerblock);
1.474     raeburn  4863: }
                   4864: 
                   4865: sub parse_block_record {
                   4866:     my ($record) = @_;
                   4867:     my ($setuname,$setudom,$title,$blocks);
                   4868:     if (ref($record) eq 'HASH') {
                   4869:         ($setuname,$setudom) = split(/:/,$record->{'setter'});
                   4870:         $title = &unescape($record->{'event'});
                   4871:         $blocks = $record->{'blocks'};
                   4872:     } else {
                   4873:         my @data = split(/:/,$record,3);
                   4874:         if (scalar(@data) eq 2) {
                   4875:             $title = $data[1];
                   4876:             ($setuname,$setudom) = split(/@/,$data[0]);
                   4877:         } else {
                   4878:             ($setuname,$setudom,$title) = @data;
                   4879:         }
                   4880:         $blocks = { 'com' => 'on' };
                   4881:     }
                   4882:     return ($setuname,$setudom,$title,$blocks);
                   4883: }
                   4884: 
1.854     kalberla 4885: sub blocking_status {
1.1075.2.73  raeburn  4886:     my ($activity,$uname,$udom,$url,$is_course) = @_;
1.1061    raeburn  4887:     my %setters;
1.890     droeschl 4888: 
1.1061    raeburn  4889: # check for active blocking
1.1062    raeburn  4890:     my ($startblock,$endblock,$triggerblock) = 
1.1075.2.73  raeburn  4891:         &blockcheck(\%setters,$activity,$uname,$udom,$url,$is_course);
1.1062    raeburn  4892:     my $blocked = 0;
                   4893:     if ($startblock && $endblock) {
                   4894:         $blocked = 1;
                   4895:     }
1.890     droeschl 4896: 
1.1061    raeburn  4897: # caller just wants to know whether a block is active
                   4898:     if (!wantarray) { return $blocked; }
                   4899: 
                   4900: # build a link to a popup window containing the details
                   4901:     my $querystring  = "?activity=$activity";
                   4902: # $uname and $udom decide whose portfolio the user is trying to look at
1.1075.2.97  raeburn  4903:     if (($activity eq 'port') || ($activity eq 'passwd')) {
                   4904:         $querystring .= "&amp;udom=$udom"      if ($udom =~ /^$match_domain$/);
                   4905:         $querystring .= "&amp;uname=$uname"    if ($uname =~ /^$match_username$/);
1.1062    raeburn  4906:     } elsif ($activity eq 'docs') {
                   4907:         $querystring .= '&amp;url='.&HTML::Entities::encode($url,'&"');
                   4908:     }
1.1061    raeburn  4909: 
                   4910:     my $output .= <<'END_MYBLOCK';
                   4911: function openWindow(url, wdwName, w, h, toolbar,scrollbar) {
                   4912:     var options = "width=" + w + ",height=" + h + ",";
                   4913:     options += "resizable=yes,scrollbars="+scrollbar+",status=no,";
                   4914:     options += "menubar=no,toolbar="+toolbar+",location=no,directories=no";
                   4915:     var newWin = window.open(url, wdwName, options);
                   4916:     newWin.focus();
                   4917: }
1.890     droeschl 4918: END_MYBLOCK
1.854     kalberla 4919: 
1.1061    raeburn  4920:     $output = Apache::lonhtmlcommon::scripttag($output);
1.890     droeschl 4921:   
1.1061    raeburn  4922:     my $popupUrl = "/adm/blockingstatus/$querystring";
1.1062    raeburn  4923:     my $text = &mt('Communication Blocked');
1.1075.2.93  raeburn  4924:     my $class = 'LC_comblock';
1.1062    raeburn  4925:     if ($activity eq 'docs') {
                   4926:         $text = &mt('Content Access Blocked');
1.1075.2.93  raeburn  4927:         $class = '';
1.1063    raeburn  4928:     } elsif ($activity eq 'printout') {
                   4929:         $text = &mt('Printing Blocked');
1.1075.2.97  raeburn  4930:     } elsif ($activity eq 'passwd') {
                   4931:         $text = &mt('Password Changing Blocked');
1.1062    raeburn  4932:     }
1.1061    raeburn  4933:     $output .= <<"END_BLOCK";
1.1075.2.93  raeburn  4934: <div class='$class'>
1.869     kalberla 4935:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring'
1.890     droeschl 4936:   title='$text'>
                   4937:   <img class='LC_noBorder LC_middle' title='$text' src='/res/adm/pages/comblock.png' alt='$text'/></a>
1.869     kalberla 4938:   <a onclick='openWindow("$popupUrl","Blocking Table",600,300,"no","no");return false;' href='/adm/blockingstatus/$querystring' 
1.890     droeschl 4939:   title='$text'>$text</a>
1.867     kalberla 4940: </div>
                   4941: 
                   4942: END_BLOCK
1.474     raeburn  4943: 
1.1061    raeburn  4944:     return ($blocked, $output);
1.854     kalberla 4945: }
1.490     raeburn  4946: 
1.60      matthew  4947: ###############################################
                   4948: 
1.682     raeburn  4949: sub check_ip_acc {
1.1075.2.105  raeburn  4950:     my ($acc,$clientip)=@_;
1.682     raeburn  4951:     &Apache::lonxml::debug("acc is $acc");
                   4952:     if (!defined($acc) || $acc =~ /^\s*$/ || $acc =~/^\s*no\s*$/i) {
                   4953:         return 1;
                   4954:     }
                   4955:     my $allowed=0;
1.1075.2.111  raeburn  4956:     my $ip=$ENV{'REMOTE_ADDR'} || $clientip || $env{'request.host'};
1.682     raeburn  4957: 
                   4958:     my $name;
                   4959:     foreach my $pattern (split(',',$acc)) {
                   4960:         $pattern =~ s/^\s*//;
                   4961:         $pattern =~ s/\s*$//;
                   4962:         if ($pattern =~ /\*$/) {
                   4963:             #35.8.*
                   4964:             $pattern=~s/\*//;
                   4965:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4966:         } elsif ($pattern =~ /(\d+\.\d+\.\d+)\.\[(\d+)-(\d+)\]$/) {
                   4967:             #35.8.3.[34-56]
                   4968:             my $low=$2;
                   4969:             my $high=$3;
                   4970:             $pattern=$1;
                   4971:             if ($ip =~ /^\Q$pattern\E/) {
                   4972:                 my $last=(split(/\./,$ip))[3];
                   4973:                 if ($last <=$high && $last >=$low) { $allowed=1; }
                   4974:             }
                   4975:         } elsif ($pattern =~ /^\*/) {
                   4976:             #*.msu.edu
                   4977:             $pattern=~s/\*//;
                   4978:             if (!defined($name)) {
                   4979:                 use Socket;
                   4980:                 my $netaddr=inet_aton($ip);
                   4981:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4982:             }
                   4983:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4984:         } elsif ($pattern =~ /\d+\.\d+\.\d+\.\d+/) {
                   4985:             #127.0.0.1
                   4986:             if ($ip =~ /^\Q$pattern\E/) { $allowed=1; }
                   4987:         } else {
                   4988:             #some.name.com
                   4989:             if (!defined($name)) {
                   4990:                 use Socket;
                   4991:                 my $netaddr=inet_aton($ip);
                   4992:                 ($name)=gethostbyaddr($netaddr,AF_INET);
                   4993:             }
                   4994:             if ($name =~ /\Q$pattern\E$/i) { $allowed=1; }
                   4995:         }
                   4996:         if ($allowed) { last; }
                   4997:     }
                   4998:     return $allowed;
                   4999: }
                   5000: 
                   5001: ###############################################
                   5002: 
1.60      matthew  5003: =pod
                   5004: 
1.112     bowersj2 5005: =head1 Domain Template Functions
                   5006: 
                   5007: =over 4
                   5008: 
                   5009: =item * &determinedomain()
1.60      matthew  5010: 
                   5011: Inputs: $domain (usually will be undef)
                   5012: 
1.63      www      5013: Returns: Determines which domain should be used for designs
1.60      matthew  5014: 
                   5015: =cut
1.54      www      5016: 
1.60      matthew  5017: ###############################################
1.63      www      5018: sub determinedomain {
                   5019:     my $domain=shift;
1.531     albertel 5020:     if (! $domain) {
1.60      matthew  5021:         # Determine domain if we have not been given one
1.893     raeburn  5022:         $domain = &Apache::lonnet::default_login_domain();
1.258     albertel 5023:         if ($env{'user.domain'}) { $domain=$env{'user.domain'}; }
                   5024:         if ($env{'request.role.domain'}) { 
                   5025:             $domain=$env{'request.role.domain'}; 
1.60      matthew  5026:         }
                   5027:     }
1.63      www      5028:     return $domain;
                   5029: }
                   5030: ###############################################
1.517     raeburn  5031: 
1.518     albertel 5032: sub devalidate_domconfig_cache {
                   5033:     my ($udom)=@_;
                   5034:     &Apache::lonnet::devalidate_cache_new('domainconfig',$udom);
                   5035: }
                   5036: 
                   5037: # ---------------------- Get domain configuration for a domain
                   5038: sub get_domainconf {
                   5039:     my ($udom) = @_;
                   5040:     my $cachetime=1800;
                   5041:     my ($result,$cached)=&Apache::lonnet::is_cached_new('domainconfig',$udom);
                   5042:     if (defined($cached)) { return %{$result}; }
                   5043: 
                   5044:     my %domconfig = &Apache::lonnet::get_dom('configuration',
1.948     raeburn  5045: 					     ['login','rolecolors','autoenroll'],$udom);
1.632     raeburn  5046:     my (%designhash,%legacy);
1.518     albertel 5047:     if (keys(%domconfig) > 0) {
                   5048:         if (ref($domconfig{'login'}) eq 'HASH') {
1.632     raeburn  5049:             if (keys(%{$domconfig{'login'}})) {
                   5050:                 foreach my $key (keys(%{$domconfig{'login'}})) {
1.699     raeburn  5051:                     if (ref($domconfig{'login'}{$key}) eq 'HASH') {
1.1075.2.87  raeburn  5052:                         if (($key eq 'loginvia') || ($key eq 'headtag')) {
                   5053:                             if (ref($domconfig{'login'}{$key}) eq 'HASH') {
                   5054:                                 foreach my $hostname (keys(%{$domconfig{'login'}{$key}})) {
                   5055:                                     if (ref($domconfig{'login'}{$key}{$hostname}) eq 'HASH') {
                   5056:                                         if ($key eq 'loginvia') {
                   5057:                                             if ($domconfig{'login'}{'loginvia'}{$hostname}{'server'}) {
                   5058:                                                 my $server = $domconfig{'login'}{'loginvia'}{$hostname}{'server'};
                   5059:                                                 $designhash{$udom.'.login.loginvia'} = $server;
                   5060:                                                 if ($domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'} eq 'custom') {
                   5061:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'custompath'};
                   5062:                                                 } else {
                   5063:                                                     $designhash{$udom.'.login.loginvia_'.$hostname} = $server.':'.$domconfig{'login'}{'loginvia'}{$hostname}{'serverpath'};
                   5064:                                                 }
1.948     raeburn  5065:                                             }
1.1075.2.87  raeburn  5066:                                         } elsif ($key eq 'headtag') {
                   5067:                                             if ($domconfig{'login'}{'headtag'}{$hostname}{'url'}) {
                   5068:                                                 $designhash{$udom.'.login.headtag_'.$hostname} = $domconfig{'login'}{'headtag'}{$hostname}{'url'};
1.948     raeburn  5069:                                             }
1.946     raeburn  5070:                                         }
1.1075.2.87  raeburn  5071:                                         if ($domconfig{'login'}{$key}{$hostname}{'exempt'}) {
                   5072:                                             $designhash{$udom.'.login.'.$key.'_exempt_'.$hostname} = $domconfig{'login'}{$key}{$hostname}{'exempt'};
                   5073:                                         }
1.946     raeburn  5074:                                     }
                   5075:                                 }
                   5076:                             }
                   5077:                         } else {
                   5078:                             foreach my $img (keys(%{$domconfig{'login'}{$key}})) {
                   5079:                                 $designhash{$udom.'.login.'.$key.'_'.$img} = 
                   5080:                                     $domconfig{'login'}{$key}{$img};
                   5081:                             }
1.699     raeburn  5082:                         }
                   5083:                     } else {
                   5084:                         $designhash{$udom.'.login.'.$key}=$domconfig{'login'}{$key};
                   5085:                     }
1.632     raeburn  5086:                 }
                   5087:             } else {
                   5088:                 $legacy{'login'} = 1;
1.518     albertel 5089:             }
1.632     raeburn  5090:         } else {
                   5091:             $legacy{'login'} = 1;
1.518     albertel 5092:         }
                   5093:         if (ref($domconfig{'rolecolors'}) eq 'HASH') {
1.632     raeburn  5094:             if (keys(%{$domconfig{'rolecolors'}})) {
                   5095:                 foreach my $role (keys(%{$domconfig{'rolecolors'}})) {
                   5096:                     if (ref($domconfig{'rolecolors'}{$role}) eq 'HASH') {
                   5097:                         foreach my $item (keys(%{$domconfig{'rolecolors'}{$role}})) {
                   5098:                             $designhash{$udom.'.'.$role.'.'.$item}=$domconfig{'rolecolors'}{$role}{$item};
                   5099:                         }
1.518     albertel 5100:                     }
                   5101:                 }
1.632     raeburn  5102:             } else {
                   5103:                 $legacy{'rolecolors'} = 1;
1.518     albertel 5104:             }
1.632     raeburn  5105:         } else {
                   5106:             $legacy{'rolecolors'} = 1;
1.518     albertel 5107:         }
1.948     raeburn  5108:         if (ref($domconfig{'autoenroll'}) eq 'HASH') {
                   5109:             if ($domconfig{'autoenroll'}{'co-owners'}) {
                   5110:                 $designhash{$udom.'.autoassign.co-owners'}=$domconfig{'autoenroll'}{'co-owners'};
                   5111:             }
                   5112:         }
1.632     raeburn  5113:         if (keys(%legacy) > 0) {
                   5114:             my %legacyhash = &get_legacy_domconf($udom);
                   5115:             foreach my $item (keys(%legacyhash)) {
                   5116:                 if ($item =~ /^\Q$udom\E\.login/) {
                   5117:                     if ($legacy{'login'}) { 
                   5118:                         $designhash{$item} = $legacyhash{$item};
                   5119:                     }
                   5120:                 } else {
                   5121:                     if ($legacy{'rolecolors'}) {
                   5122:                         $designhash{$item} = $legacyhash{$item};
                   5123:                     }
1.518     albertel 5124:                 }
                   5125:             }
                   5126:         }
1.632     raeburn  5127:     } else {
                   5128:         %designhash = &get_legacy_domconf($udom); 
1.518     albertel 5129:     }
                   5130:     &Apache::lonnet::do_cache_new('domainconfig',$udom,\%designhash,
                   5131: 				  $cachetime);
                   5132:     return %designhash;
                   5133: }
                   5134: 
1.632     raeburn  5135: sub get_legacy_domconf {
                   5136:     my ($udom) = @_;
                   5137:     my %legacyhash;
                   5138:     my $designdir=$Apache::lonnet::perlvar{'lonTabDir'}.'/lonDomColors';
                   5139:     my $designfile =  $designdir.'/'.$udom.'.tab';
                   5140:     if (-e $designfile) {
1.1075.2.128  raeburn  5141:         if ( open (my $fh,'<',$designfile) ) {
1.632     raeburn  5142:             while (my $line = <$fh>) {
                   5143:                 next if ($line =~ /^\#/);
                   5144:                 chomp($line);
                   5145:                 my ($key,$val)=(split(/\=/,$line));
                   5146:                 if ($val) { $legacyhash{$udom.'.'.$key}=$val; }
                   5147:             }
                   5148:             close($fh);
                   5149:         }
                   5150:     }
1.1026    raeburn  5151:     if (-e $Apache::lonnet::perlvar{'lonDocRoot'}.'/adm/lonDomLogos/'.$udom.'.gif') {
1.632     raeburn  5152:         $legacyhash{$udom.'.login.domlogo'} = "/adm/lonDomLogos/$udom.gif";
                   5153:     }
                   5154:     return %legacyhash;
                   5155: }
                   5156: 
1.63      www      5157: =pod
                   5158: 
1.112     bowersj2 5159: =item * &domainlogo()
1.63      www      5160: 
                   5161: Inputs: $domain (usually will be undef)
                   5162: 
                   5163: Returns: A link to a domain logo, if the domain logo exists.
                   5164: If the domain logo does not exist, a description of the domain.
                   5165: 
                   5166: =cut
1.112     bowersj2 5167: 
1.63      www      5168: ###############################################
                   5169: sub domainlogo {
1.517     raeburn  5170:     my $domain = &determinedomain(shift);
1.518     albertel 5171:     my %designhash = &get_domainconf($domain);    
1.517     raeburn  5172:     # See if there is a logo
                   5173:     if ($designhash{$domain.'.login.domlogo'} ne '') {
1.519     raeburn  5174:         my $imgsrc = $designhash{$domain.'.login.domlogo'};
1.538     albertel 5175:         if ($imgsrc =~ m{^/(adm|res)/}) {
                   5176: 	    if ($imgsrc =~ m{^/res/}) {
                   5177: 		my $local_name = &Apache::lonnet::filelocation('',$imgsrc);
                   5178: 		&Apache::lonnet::repcopy($local_name);
                   5179: 	    }
                   5180: 	   $imgsrc = &lonhttpdurl($imgsrc);
1.519     raeburn  5181:         } 
                   5182:         return '<img src="'.$imgsrc.'" alt="'.$domain.'" />';
1.514     albertel 5183:     } elsif (defined(&Apache::lonnet::domain($domain,'description'))) {
                   5184:         return &Apache::lonnet::domain($domain,'description');
1.59      www      5185:     } else {
1.60      matthew  5186:         return '';
1.59      www      5187:     }
                   5188: }
1.63      www      5189: ##############################################
                   5190: 
                   5191: =pod
                   5192: 
1.112     bowersj2 5193: =item * &designparm()
1.63      www      5194: 
                   5195: Inputs: $which parameter; $domain (usually will be undef)
                   5196: 
                   5197: Returns: value of designparamter $which
                   5198: 
                   5199: =cut
1.112     bowersj2 5200: 
1.397     albertel 5201: 
1.400     albertel 5202: ##############################################
1.397     albertel 5203: sub designparm {
                   5204:     my ($which,$domain)=@_;
                   5205:     if (exists($env{'environment.color.'.$which})) {
1.817     bisitz   5206:         return $env{'environment.color.'.$which};
1.96      www      5207:     }
1.63      www      5208:     $domain=&determinedomain($domain);
1.1016    raeburn  5209:     my %domdesign;
                   5210:     unless ($domain eq 'public') {
                   5211:         %domdesign = &get_domainconf($domain);
                   5212:     }
1.520     raeburn  5213:     my $output;
1.517     raeburn  5214:     if ($domdesign{$domain.'.'.$which} ne '') {
1.817     bisitz   5215:         $output = $domdesign{$domain.'.'.$which};
1.63      www      5216:     } else {
1.520     raeburn  5217:         $output = $defaultdesign{$which};
                   5218:     }
                   5219:     if (($which =~ /^(student|coordinator|author|admin)\.img$/) ||
1.635     raeburn  5220:         ($which =~ /login\.(img|logo|domlogo|login)/)) {
1.538     albertel 5221:         if ($output =~ m{^/(adm|res)/}) {
1.817     bisitz   5222:             if ($output =~ m{^/res/}) {
                   5223:                 my $local_name = &Apache::lonnet::filelocation('',$output);
                   5224:                 &Apache::lonnet::repcopy($local_name);
                   5225:             }
1.520     raeburn  5226:             $output = &lonhttpdurl($output);
                   5227:         }
1.63      www      5228:     }
1.520     raeburn  5229:     return $output;
1.63      www      5230: }
1.59      www      5231: 
1.822     bisitz   5232: ##############################################
                   5233: =pod
                   5234: 
1.832     bisitz   5235: =item * &authorspace()
                   5236: 
1.1028    raeburn  5237: Inputs: $url (usually will be undef).
1.832     bisitz   5238: 
1.1075.2.40  raeburn  5239: Returns: Path to Authoring Space containing the resource or 
1.1028    raeburn  5240:          directory being viewed (or for which action is being taken). 
                   5241:          If $url is provided, and begins /priv/<domain>/<uname>
                   5242:          the path will be that portion of the $context argument.
                   5243:          Otherwise the path will be for the author space of the current
                   5244:          user when the current role is author, or for that of the 
                   5245:          co-author/assistant co-author space when the current role 
                   5246:          is co-author or assistant co-author.
1.832     bisitz   5247: 
                   5248: =cut
                   5249: 
                   5250: sub authorspace {
1.1028    raeburn  5251:     my ($url) = @_;
                   5252:     if ($url ne '') {
                   5253:         if ($url =~ m{^(/priv/$match_domain/$match_username/)}) {
                   5254:            return $1;
                   5255:         }
                   5256:     }
1.832     bisitz   5257:     my $caname = '';
1.1024    www      5258:     my $cadom = '';
1.1028    raeburn  5259:     if ($env{'request.role'} =~ /^(?:ca|aa)/) {
1.1024    www      5260:         ($cadom,$caname) =
1.832     bisitz   5261:             ($env{'request.role'}=~/($match_domain)\/($match_username)$/);
1.1028    raeburn  5262:     } elsif ($env{'request.role'} =~ m{^au\./($match_domain)/}) {
1.832     bisitz   5263:         $caname = $env{'user.name'};
1.1024    www      5264:         $cadom = $env{'user.domain'};
1.832     bisitz   5265:     }
1.1028    raeburn  5266:     if (($caname ne '') && ($cadom ne '')) {
                   5267:         return "/priv/$cadom/$caname/";
                   5268:     }
                   5269:     return;
1.832     bisitz   5270: }
                   5271: 
                   5272: ##############################################
                   5273: =pod
                   5274: 
1.822     bisitz   5275: =item * &head_subbox()
                   5276: 
                   5277: Inputs: $content (contains HTML code with page functions, etc.)
                   5278: 
                   5279: Returns: HTML div with $content
                   5280:          To be included in page header
                   5281: 
                   5282: =cut
                   5283: 
                   5284: sub head_subbox {
                   5285:     my ($content)=@_;
                   5286:     my $output =
1.993     raeburn  5287:         '<div class="LC_head_subbox">'
1.822     bisitz   5288:        .$content
                   5289:        .'</div>'
                   5290: }
                   5291: 
                   5292: ##############################################
                   5293: =pod
                   5294: 
                   5295: =item * &CSTR_pageheader()
                   5296: 
1.1026    raeburn  5297: Input: (optional) filename from which breadcrumb trail is built.
                   5298:        In most cases no input as needed, as $env{'request.filename'}
                   5299:        is appropriate for use in building the breadcrumb trail.
1.822     bisitz   5300: 
                   5301: Returns: HTML div with CSTR path and recent box
1.1075.2.40  raeburn  5302:          To be included on Authoring Space pages
1.822     bisitz   5303: 
                   5304: =cut
                   5305: 
                   5306: sub CSTR_pageheader {
1.1026    raeburn  5307:     my ($trailfile) = @_;
                   5308:     if ($trailfile eq '') {
                   5309:         $trailfile = $env{'request.filename'};
                   5310:     }
                   5311: 
                   5312: # this is for resources; directories have customtitle, and crumbs
                   5313: # and select recent are created in lonpubdir.pm
                   5314: 
                   5315:     my $londocroot = $Apache::lonnet::perlvar{'lonDocRoot'};
1.1022    www      5316:     my ($udom,$uname,$thisdisfn)=
1.1075.2.29  raeburn  5317:         ($trailfile =~ m{^\Q$londocroot\E/priv/([^/]+)/([^/]+)(?:|/(.*))$});
1.1026    raeburn  5318:     my $formaction = "/priv/$udom/$uname/$thisdisfn";
                   5319:     $formaction =~ s{/+}{/}g;
1.822     bisitz   5320: 
                   5321:     my $parentpath = '';
                   5322:     my $lastitem = '';
                   5323:     if ($thisdisfn =~ m-(.+/)([^/]*)$-) {
                   5324:         $parentpath = $1;
                   5325:         $lastitem = $2;
                   5326:     } else {
                   5327:         $lastitem = $thisdisfn;
                   5328:     }
1.921     bisitz   5329: 
                   5330:     my $output =
1.822     bisitz   5331:          '<div>'
                   5332:         .&Apache::loncommon::help_open_menu('','',3,'Authoring') #FIXME: Broken? Where is it?
1.1075.2.40  raeburn  5333:         .'<b>'.&mt('Authoring Space:').'</b> '
1.822     bisitz   5334:         .'<form name="dirs" method="post" action="'.$formaction
1.921     bisitz   5335:         .'" target="_top">' #FIXME lonpubdir: target="_parent"
1.1024    www      5336:         .&Apache::lonhtmlcommon::crumbs($uname.'/'.$parentpath,'_top','/priv/'.$udom,undef,undef);
1.921     bisitz   5337: 
                   5338:     if ($lastitem) {
                   5339:         $output .=
                   5340:              '<span class="LC_filename">'
                   5341:             .$lastitem
                   5342:             .'</span>';
                   5343:     }
                   5344:     $output .=
                   5345:          '<br />'
1.822     bisitz   5346:         #FIXME lonpubdir: &Apache::lonhtmlcommon::crumbs($uname.$thisdisfn.'/','_top','/priv','','+1',1)."</b></tt><br />"
                   5347:         .&Apache::lonhtmlcommon::select_recent('construct','recent','this.form.action=this.form.recent.value;this.form.submit()')
                   5348:         .'</form>'
                   5349:         .&Apache::lonmenu::constspaceform()
                   5350:         .'</div>';
1.921     bisitz   5351: 
                   5352:     return $output;
1.822     bisitz   5353: }
                   5354: 
1.60      matthew  5355: ###############################################
                   5356: ###############################################
                   5357: 
                   5358: =pod
                   5359: 
1.112     bowersj2 5360: =back
                   5361: 
1.549     albertel 5362: =head1 HTML Helpers
1.112     bowersj2 5363: 
                   5364: =over 4
                   5365: 
                   5366: =item * &bodytag()
1.60      matthew  5367: 
                   5368: Returns a uniform header for LON-CAPA web pages.
                   5369: 
                   5370: Inputs: 
                   5371: 
1.112     bowersj2 5372: =over 4
                   5373: 
                   5374: =item * $title, A title to be displayed on the page.
                   5375: 
                   5376: =item * $function, the current role (can be undef).
                   5377: 
                   5378: =item * $addentries, extra parameters for the <body> tag.
                   5379: 
                   5380: =item * $bodyonly, if defined, only return the <body> tag.
                   5381: 
                   5382: =item * $domain, if defined, force a given domain.
                   5383: 
                   5384: =item * $forcereg, if page should register as content page (relevant for 
1.86      www      5385:             text interface only)
1.60      matthew  5386: 
1.814     bisitz   5387: =item * $no_nav_bar, if true, keep the 'what is this' info but remove the
                   5388:                      navigational links
1.317     albertel 5389: 
1.338     albertel 5390: =item * $bgcolor, used to override the bgcolor on a webpage to a specific value
                   5391: 
1.1075.2.12  raeburn  5392: =item * $no_inline_link, if true and in remote mode, don't show the
                   5393:          'Switch To Inline Menu' link
                   5394: 
1.460     albertel 5395: =item * $args, optional argument valid values are
                   5396:             no_auto_mt_title -> prevents &mt()ing the title arg
1.1075.2.133! raeburn  5397:             use_absolute     -> for external resource or syllabus, this will
        !          5398:                                 contain https://<hostname> if server uses
        !          5399:                                 https (as per hosts.tab), but request is for http
        !          5400:             hostname         -> hostname, from $r->hostname().
1.460     albertel 5401: 
1.1075.2.15  raeburn  5402: =item * $advtoolsref, optional argument, ref to an array containing
                   5403:             inlineremote items to be added in "Functions" menu below
                   5404:             breadcrumbs.
                   5405: 
1.112     bowersj2 5406: =back
                   5407: 
1.60      matthew  5408: Returns: A uniform header for LON-CAPA web pages.  
                   5409: If $bodyonly is nonzero, a string containing a <body> tag will be returned.
                   5410: If $bodyonly is undef or zero, an html string containing a <body> tag and 
                   5411: other decorations will be returned.
                   5412: 
                   5413: =cut
                   5414: 
1.54      www      5415: sub bodytag {
1.831     bisitz   5416:     my ($title,$function,$addentries,$bodyonly,$domain,$forcereg,
1.1075.2.15  raeburn  5417:         $no_nav_bar,$bgcolor,$no_inline_link,$args,$advtoolsref)=@_;
1.339     albertel 5418: 
1.954     raeburn  5419:     my $public;
                   5420:     if ((($env{'user.name'} eq 'public') && ($env{'user.domain'} eq 'public'))
                   5421:         || ($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   5422:         $public = 1;
                   5423:     }
1.460     albertel 5424:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
1.1075.2.52  raeburn  5425:     my $httphost = $args->{'use_absolute'};
1.1075.2.133! raeburn  5426:     my $hostname = $args->{'hostname'};
1.339     albertel 5427: 
1.183     matthew  5428:     $function = &get_users_function() if (!$function);
1.339     albertel 5429:     my $img =    &designparm($function.'.img',$domain);
                   5430:     my $font =   &designparm($function.'.font',$domain);
                   5431:     my $pgbg   = $bgcolor || &designparm($function.'.pgbg',$domain);
                   5432: 
1.803     bisitz   5433:     my %design = ( 'style'   => 'margin-top: 0',
1.535     albertel 5434: 		   'bgcolor' => $pgbg,
1.339     albertel 5435: 		   'text'    => $font,
                   5436:                    'alink'   => &designparm($function.'.alink',$domain),
                   5437: 		   'vlink'   => &designparm($function.'.vlink',$domain),
                   5438: 		   'link'    => &designparm($function.'.link',$domain),);
1.438     albertel 5439:     @design{keys(%$addentries)} = @$addentries{keys(%$addentries)}; 
1.339     albertel 5440: 
1.63      www      5441:  # role and realm
1.1075.2.68  raeburn  5442:     my ($role,$realm) = split(m{\./},$env{'request.role'},2);
                   5443:     if ($realm) {
                   5444:         $realm = '/'.$realm;
                   5445:     }
1.378     raeburn  5446:     if ($role  eq 'ca') {
1.479     albertel 5447:         my ($rdom,$rname) = ($realm =~ m{^/($match_domain)/($match_username)$});
1.500     albertel 5448:         $realm = &plainname($rname,$rdom);
1.378     raeburn  5449:     } 
1.55      www      5450: # realm
1.258     albertel 5451:     if ($env{'request.course.id'}) {
1.378     raeburn  5452:         if ($env{'request.role'} !~ /^cr/) {
                   5453:             $role = &Apache::lonnet::plaintext($role,&course_type());
1.1075.2.115  raeburn  5454:         } elsif ($role =~ m{^cr/($match_domain)/\1-domainconfig/(\w+)$}) {
1.1075.2.121  raeburn  5455:             if ($env{'request.role.desc'}) {
                   5456:                 $role = $env{'request.role.desc'};
                   5457:             } else {
                   5458:                 $role = &mt('Helpdesk[_1]','&nbsp;'.$2);
                   5459:             }
1.1075.2.115  raeburn  5460:         } else {
                   5461:             $role = (split(/\//,$role,4))[-1];
1.378     raeburn  5462:         }
1.898     raeburn  5463:         if ($env{'request.course.sec'}) {
                   5464:             $role .= ('&nbsp;'x2).'-&nbsp;'.&mt('section:').'&nbsp;'.$env{'request.course.sec'};
                   5465:         }   
1.359     albertel 5466: 	$realm = $env{'course.'.$env{'request.course.id'}.'.description'};
1.378     raeburn  5467:     } else {
                   5468:         $role = &Apache::lonnet::plaintext($role);
1.54      www      5469:     }
1.433     albertel 5470: 
1.359     albertel 5471:     if (!$realm) { $realm='&nbsp;'; }
1.330     albertel 5472: 
1.438     albertel 5473:     my $extra_body_attr = &make_attr_string($forcereg,\%design);
1.329     albertel 5474: 
1.101     www      5475: # construct main body tag
1.359     albertel 5476:     my $bodytag = "<body $extra_body_attr>".
1.1075.2.100  raeburn  5477: 	&Apache::lontexconvert::init_math_support();
1.252     albertel 5478: 
1.1075.2.38  raeburn  5479:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   5480: 
                   5481:     if (($bodyonly) || ($no_nav_bar) || ($env{'form.inhibitmenu'} eq 'yes')) {
1.60      matthew  5482:         return $bodytag;
1.1075.2.38  raeburn  5483:     }
1.359     albertel 5484: 
1.954     raeburn  5485:     if ($public) {
1.433     albertel 5486: 	undef($role);
                   5487:     }
1.359     albertel 5488:     
1.762     bisitz   5489:     my $titleinfo = '<h1>'.$title.'</h1>';
1.359     albertel 5490:     #
                   5491:     # Extra info if you are the DC
                   5492:     my $dc_info = '';
                   5493:     if ($env{'user.adv'} && exists($env{'user.role.dc./'.
                   5494:                         $env{'course.'.$env{'request.course.id'}.
                   5495:                                  '.domain'}.'/'})) {
                   5496:         my $cid = $env{'request.course.id'};
1.917     raeburn  5497:         $dc_info = $cid.' '.$env{'course.'.$cid.'.internal.coursecode'};
1.380     www      5498:         $dc_info =~ s/\s+$//;
1.359     albertel 5499:     }
                   5500: 
1.1075.2.108  raeburn  5501:     $role = '<span class="LC_nobreak">('.$role.')</span>' if ($role && !$env{'browser.mobile'});
1.903     droeschl 5502: 
1.1075.2.13  raeburn  5503:     if ($env{'request.state'} eq 'construct') { $forcereg=1; }
                   5504: 
1.1075.2.38  raeburn  5505: 
                   5506: 
1.1075.2.21  raeburn  5507:     my $funclist;
                   5508:     if (($env{'environment.remote'} eq 'on') && ($env{'request.state'} ne 'construct')) {
1.1075.2.52  raeburn  5509:         $bodytag .= Apache::lonhtmlcommon::scripttag(Apache::lonmenu::utilityfunctions($httphost), 'start')."\n".
1.1075.2.21  raeburn  5510:                     Apache::lonmenu::serverform();
                   5511:         my $forbodytag;
                   5512:         &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5513:                                             $forcereg,$args->{'group'},
                   5514:                                             $args->{'bread_crumbs'},
1.1075.2.133! raeburn  5515:                                             $advtoolsref,'','',\$forbodytag);
1.1075.2.21  raeburn  5516:         unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5517:             $funclist = $forbodytag;
                   5518:         }
                   5519:     } else {
1.903     droeschl 5520: 
                   5521:         #    if ($env{'request.state'} eq 'construct') {
                   5522:         #        $titleinfo = &CSTR_pageheader(); #FIXME: Will be removed once all scripts have their own calls
                   5523:         #    }
                   5524: 
1.1075.2.38  raeburn  5525:         $bodytag .= Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5526:             Apache::lonmenu::utilityfunctions($httphost), 'start');
1.359     albertel 5527: 
1.1075.2.38  raeburn  5528:         my ($left,$right) = Apache::lonmenu::primary_menu();
1.1075.2.2  raeburn  5529: 
1.916     droeschl 5530:         if ($env{'request.noversionuri'} =~ m{^/res/adm/pages/}) {
1.1075.2.22  raeburn  5531:             if ($dc_info) {
                   5532:                  $dc_info = qq|<span class="LC_cusr_subheading">$dc_info</span>|;
1.1075.2.1  raeburn  5533:             }
1.1075.2.38  raeburn  5534:             $bodytag .= qq|<div id="LC_nav_bar">$left $role<br />
1.1075.2.22  raeburn  5535:                            <em>$realm</em> $dc_info</div>|;
1.903     droeschl 5536:             return $bodytag;
                   5537:         }
1.894     droeschl 5538: 
1.927     raeburn  5539:         unless ($env{'request.symb'} =~ m/\.page___\d+___/) {
1.1075.2.38  raeburn  5540:             $bodytag .= qq|<div id="LC_nav_bar">$left $role</div>|;
1.927     raeburn  5541:         }
1.916     droeschl 5542: 
1.1075.2.38  raeburn  5543:         $bodytag .= $right;
1.852     droeschl 5544: 
1.917     raeburn  5545:         if ($dc_info) {
                   5546:             $dc_info = &dc_courseid_toggle($dc_info);
                   5547:         }
                   5548:         $bodytag .= qq|<div id="LC_realm">$realm $dc_info</div>|;
1.916     droeschl 5549: 
1.1075.2.61  raeburn  5550:         #if directed to not display the secondary menu, don't.
                   5551:         if ($args->{'no_secondary_menu'}) {
                   5552:             return $bodytag;
                   5553:         }
1.903     droeschl 5554:         #don't show menus for public users
1.954     raeburn  5555:         if (!$public){
1.1075.2.52  raeburn  5556:             $bodytag .= Apache::lonmenu::secondary_menu($httphost);
1.903     droeschl 5557:             $bodytag .= Apache::lonmenu::serverform();
1.920     raeburn  5558:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end');
                   5559:             if ($env{'request.state'} eq 'construct') {
1.962     droeschl 5560:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,
1.1075.2.133! raeburn  5561:                                 $args->{'bread_crumbs'},'','',$hostname);
1.1075.2.116  raeburn  5562:             } elsif ($forcereg) {
1.1075.2.22  raeburn  5563:                 $bodytag .= &Apache::lonmenu::innerregister($forcereg,undef,
1.1075.2.116  raeburn  5564:                                                             $args->{'group'},
1.1075.2.133! raeburn  5565:                                                             $args->{'hide_buttons',
        !          5566:                                                             $hostname});
1.1075.2.15  raeburn  5567:             } else {
1.1075.2.21  raeburn  5568:                 my $forbodytag;
                   5569:                 &Apache::lonmenu::prepare_functions($env{'request.noversionuri'},
                   5570:                                                     $forcereg,$args->{'group'},
                   5571:                                                     $args->{'bread_crumbs'},
1.1075.2.133! raeburn  5572:                                                     $advtoolsref,'',$hostname,
        !          5573:                                                     \$forbodytag);
1.1075.2.21  raeburn  5574:                 unless (ref($args->{'bread_crumbs'}) eq 'ARRAY') {
                   5575:                     $bodytag .= $forbodytag;
                   5576:                 }
1.920     raeburn  5577:             }
1.903     droeschl 5578:         }else{
                   5579:             # this is to seperate menu from content when there's no secondary
                   5580:             # menu. Especially needed for public accessible ressources.
                   5581:             $bodytag .= '<hr style="clear:both" />';
                   5582:             $bodytag .= Apache::lonhtmlcommon::scripttag('', 'end'); 
1.235     raeburn  5583:         }
1.903     droeschl 5584: 
1.235     raeburn  5585:         return $bodytag;
1.1075.2.12  raeburn  5586:     }
                   5587: 
                   5588: #
                   5589: # Top frame rendering, Remote is up
                   5590: #
                   5591: 
                   5592:     my $imgsrc = $img;
                   5593:     if ($img =~ /^\/adm/) {
                   5594:         $imgsrc = &lonhttpdurl($img);
                   5595:     }
                   5596:     my $upperleft='<img src="'.$imgsrc.'" alt="'.$function.'" />';
                   5597: 
1.1075.2.60  raeburn  5598:     my $help=($no_inline_link?''
                   5599:               :&Apache::loncommon::top_nav_help('Help'));
                   5600: 
1.1075.2.12  raeburn  5601:     # Explicit link to get inline menu
                   5602:     my $menu= ($no_inline_link?''
                   5603:                :'<a href="/adm/remote?action=collapse" target="_top">'.&mt('Switch to Inline Menu Mode').'</a>');
                   5604: 
                   5605:     if ($dc_info) {
                   5606:         $dc_info = qq|<span class="LC_cusr_subheading">($dc_info)</span>|;
                   5607:     }
                   5608: 
1.1075.2.38  raeburn  5609:     my $name = &plainname($env{'user.name'},$env{'user.domain'});
                   5610:     unless ($public) {
                   5611:         $name = &aboutmewrapper($name,$env{'user.name'},$env{'user.domain'},
                   5612:                                 undef,'LC_menubuttons_link');
                   5613:     }
                   5614: 
1.1075.2.12  raeburn  5615:     unless ($env{'form.inhibitmenu'}) {
                   5616:         $bodytag .= qq|<div id="LC_nav_bar">$name $role</div>
1.1075.2.38  raeburn  5617:                        <ol class="LC_primary_menu LC_floatright LC_right">
1.1075.2.60  raeburn  5618:                        <li>$help</li>
1.1075.2.12  raeburn  5619:                        <li>$menu</li>
                   5620:                        </ol><div id="LC_realm"> $realm $dc_info</div>|;
                   5621:     }
1.1075.2.13  raeburn  5622:     if ($env{'request.state'} eq 'construct') {
                   5623:         if (!$public){
                   5624:             if ($env{'request.state'} eq 'construct') {
                   5625:                 $funclist = &Apache::lonhtmlcommon::scripttag(
1.1075.2.52  raeburn  5626:                                 &Apache::lonmenu::utilityfunctions($httphost), 'start').
1.1075.2.13  raeburn  5627:                             &Apache::lonhtmlcommon::scripttag('','end').
                   5628:                             &Apache::lonmenu::innerregister($forcereg,
                   5629:                                                             $args->{'bread_crumbs'});
                   5630:             }
                   5631:         }
                   5632:     }
1.1075.2.21  raeburn  5633:     return $bodytag."\n".$funclist;
1.182     matthew  5634: }
                   5635: 
1.917     raeburn  5636: sub dc_courseid_toggle {
                   5637:     my ($dc_info) = @_;
1.980     raeburn  5638:     return ' <span id="dccidtext" class="LC_cusr_subheading LC_nobreak">'.
1.1069    raeburn  5639:            '<a href="javascript:showCourseID();" class="LC_menubuttons_link">'.
1.917     raeburn  5640:            &mt('(More ...)').'</a></span>'.
                   5641:            '<div id="dccid" class="LC_dccid">'.$dc_info.'</div>';
                   5642: }
                   5643: 
1.330     albertel 5644: sub make_attr_string {
                   5645:     my ($register,$attr_ref) = @_;
                   5646: 
                   5647:     if ($attr_ref && !ref($attr_ref)) {
                   5648: 	die("addentries Must be a hash ref ".
                   5649: 	    join(':',caller(1))." ".
                   5650: 	    join(':',caller(0))." ");
                   5651:     }
                   5652: 
                   5653:     if ($register) {
1.339     albertel 5654: 	my ($on_load,$on_unload);
                   5655: 	foreach my $key (keys(%{$attr_ref})) {
                   5656: 	    if      (lc($key) eq 'onload') {
                   5657: 		$on_load.=$attr_ref->{$key}.';';
                   5658: 		delete($attr_ref->{$key});
                   5659: 
                   5660: 	    } elsif (lc($key) eq 'onunload') {
                   5661: 		$on_unload.=$attr_ref->{$key}.';';
                   5662: 		delete($attr_ref->{$key});
                   5663: 	    }
                   5664: 	}
1.1075.2.12  raeburn  5665:         if ($env{'environment.remote'} eq 'on') {
                   5666:             $attr_ref->{'onload'}  =
                   5667:                 &Apache::lonmenu::loadevents().  $on_load;
                   5668:             $attr_ref->{'onunload'}=
                   5669:                 &Apache::lonmenu::unloadevents().$on_unload;
                   5670:         } else {  
                   5671: 	    $attr_ref->{'onload'}  = $on_load;
                   5672: 	    $attr_ref->{'onunload'}= $on_unload;
                   5673:         }
1.330     albertel 5674:     }
1.339     albertel 5675: 
1.330     albertel 5676:     my $attr_string;
1.1075.2.56  raeburn  5677:     foreach my $attr (sort(keys(%$attr_ref))) {
1.330     albertel 5678: 	$attr_string .= " $attr=\"".$attr_ref->{$attr}.'" ';
                   5679:     }
                   5680:     return $attr_string;
                   5681: }
                   5682: 
                   5683: 
1.182     matthew  5684: ###############################################
1.251     albertel 5685: ###############################################
                   5686: 
                   5687: =pod
                   5688: 
                   5689: =item * &endbodytag()
                   5690: 
                   5691: Returns a uniform footer for LON-CAPA web pages.
                   5692: 
1.635     raeburn  5693: Inputs: 1 - optional reference to an args hash
                   5694: If in the hash, key for noredirectlink has a value which evaluates to true,
                   5695: a 'Continue' link is not displayed if the page contains an
                   5696: internal redirect in the <head></head> section,
                   5697: i.e., $env{'internal.head.redirect'} exists   
1.251     albertel 5698: 
                   5699: =cut
                   5700: 
                   5701: sub endbodytag {
1.635     raeburn  5702:     my ($args) = @_;
1.1075.2.6  raeburn  5703:     my $endbodytag;
                   5704:     unless ((ref($args) eq 'HASH') && ($args->{'notbody'})) {
                   5705:         $endbodytag='</body>';
                   5706:     }
1.315     albertel 5707:     if ( exists( $env{'internal.head.redirect'} ) ) {
1.635     raeburn  5708:         if (!(ref($args) eq 'HASH' && $args->{'noredirectlink'})) {
                   5709: 	    $endbodytag=
                   5710: 	        "<br /><a href=\"$env{'internal.head.redirect'}\">".
                   5711: 	        &mt('Continue').'</a>'.
                   5712: 	        $endbodytag;
                   5713:         }
1.315     albertel 5714:     }
1.251     albertel 5715:     return $endbodytag;
                   5716: }
                   5717: 
1.352     albertel 5718: =pod
                   5719: 
                   5720: =item * &standard_css()
                   5721: 
                   5722: Returns a style sheet
                   5723: 
                   5724: Inputs: (all optional)
                   5725:             domain         -> force to color decorate a page for a specific
                   5726:                                domain
                   5727:             function       -> force usage of a specific rolish color scheme
                   5728:             bgcolor        -> override the default page bgcolor
                   5729: 
                   5730: =cut
                   5731: 
1.343     albertel 5732: sub standard_css {
1.345     albertel 5733:     my ($function,$domain,$bgcolor) = @_;
1.352     albertel 5734:     $function  = &get_users_function() if (!$function);
                   5735:     my $img    = &designparm($function.'.img',   $domain);
                   5736:     my $tabbg  = &designparm($function.'.tabbg', $domain);
                   5737:     my $font   = &designparm($function.'.font',  $domain);
1.801     tempelho 5738:     my $fontmenu = &designparm($function.'.fontmenu', $domain);
1.791     tempelho 5739: #second colour for later usage
1.345     albertel 5740:     my $sidebg = &designparm($function.'.sidebg',$domain);
1.382     albertel 5741:     my $pgbg_or_bgcolor =
                   5742: 	         $bgcolor ||
1.352     albertel 5743: 	         &designparm($function.'.pgbg',  $domain);
1.382     albertel 5744:     my $pgbg   = &designparm($function.'.pgbg',  $domain);
1.352     albertel 5745:     my $alink  = &designparm($function.'.alink', $domain);
                   5746:     my $vlink  = &designparm($function.'.vlink', $domain);
                   5747:     my $link   = &designparm($function.'.link',  $domain);
                   5748: 
1.602     albertel 5749:     my $sans                 = 'Verdana,Arial,Helvetica,sans-serif';
1.395     albertel 5750:     my $mono                 = 'monospace';
1.850     bisitz   5751:     my $data_table_head      = $sidebg;
                   5752:     my $data_table_light     = '#FAFAFA';
1.1060    bisitz   5753:     my $data_table_dark      = '#E0E0E0';
1.470     banghart 5754:     my $data_table_darker    = '#CCCCCC';
1.349     albertel 5755:     my $data_table_highlight = '#FFFF00';
1.352     albertel 5756:     my $mail_new             = '#FFBB77';
                   5757:     my $mail_new_hover       = '#DD9955';
                   5758:     my $mail_read            = '#BBBB77';
                   5759:     my $mail_read_hover      = '#999944';
                   5760:     my $mail_replied         = '#AAAA88';
                   5761:     my $mail_replied_hover   = '#888855';
                   5762:     my $mail_other           = '#99BBBB';
                   5763:     my $mail_other_hover     = '#669999';
1.391     albertel 5764:     my $table_header         = '#DDDDDD';
1.489     raeburn  5765:     my $feedback_link_bg     = '#BBBBBB';
1.911     bisitz   5766:     my $lg_border_color      = '#C8C8C8';
1.952     onken    5767:     my $button_hover         = '#BF2317';
1.392     albertel 5768: 
1.608     albertel 5769:     my $border = ($env{'browser.type'} eq 'explorer' ||
1.911     bisitz   5770:       $env{'browser.type'} eq 'safari'     ) ? '0 2px 0 2px'
                   5771:                                              : '0 3px 0 4px';
1.448     albertel 5772: 
1.523     albertel 5773: 
1.343     albertel 5774:     return <<END;
1.947     droeschl 5775: 
                   5776: /* needed for iframe to allow 100% height in FF */
                   5777: body, html { 
                   5778:     margin: 0;
                   5779:     padding: 0 0.5%;
                   5780:     height: 99%; /* to avoid scrollbars */
                   5781: }
                   5782: 
1.795     www      5783: body {
1.911     bisitz   5784:   font-family: $sans;
                   5785:   line-height:130%;
                   5786:   font-size:0.83em;
                   5787:   color:$font;
1.795     www      5788: }
                   5789: 
1.959     onken    5790: a:focus,
                   5791: a:focus img {
1.795     www      5792:   color: red;
                   5793: }
1.698     harmsja  5794: 
1.911     bisitz   5795: form, .inline {
                   5796:   display: inline;
1.795     www      5797: }
1.721     harmsja  5798: 
1.795     www      5799: .LC_right {
1.911     bisitz   5800:   text-align:right;
1.795     www      5801: }
                   5802: 
                   5803: .LC_middle {
1.911     bisitz   5804:   vertical-align:middle;
1.795     www      5805: }
1.721     harmsja  5806: 
1.1075.2.38  raeburn  5807: .LC_floatleft {
                   5808:   float: left;
                   5809: }
                   5810: 
                   5811: .LC_floatright {
                   5812:   float: right;
                   5813: }
                   5814: 
1.911     bisitz   5815: .LC_400Box {
                   5816:   width:400px;
                   5817: }
1.721     harmsja  5818: 
1.947     droeschl 5819: .LC_iframecontainer {
                   5820:     width: 98%;
                   5821:     margin: 0;
                   5822:     position: fixed;
                   5823:     top: 8.5em;
                   5824:     bottom: 0;
                   5825: }
                   5826: 
                   5827: .LC_iframecontainer iframe{
                   5828:     border: none;
                   5829:     width: 100%;
                   5830:     height: 100%;
                   5831: }
                   5832: 
1.778     bisitz   5833: .LC_filename {
                   5834:   font-family: $mono;
                   5835:   white-space:pre;
1.921     bisitz   5836:   font-size: 120%;
1.778     bisitz   5837: }
                   5838: 
                   5839: .LC_fileicon {
                   5840:   border: none;
                   5841:   height: 1.3em;
                   5842:   vertical-align: text-bottom;
                   5843:   margin-right: 0.3em;
                   5844:   text-decoration:none;
                   5845: }
                   5846: 
1.1008    www      5847: .LC_setting {
                   5848:   text-decoration:underline;
                   5849: }
                   5850: 
1.350     albertel 5851: .LC_error {
                   5852:   color: red;
                   5853: }
1.795     www      5854: 
1.1075.2.15  raeburn  5855: .LC_warning {
                   5856:   color: darkorange;
                   5857: }
                   5858: 
1.457     albertel 5859: .LC_diff_removed {
1.733     bisitz   5860:   color: red;
1.394     albertel 5861: }
1.532     albertel 5862: 
                   5863: .LC_info,
1.457     albertel 5864: .LC_success,
                   5865: .LC_diff_added {
1.350     albertel 5866:   color: green;
                   5867: }
1.795     www      5868: 
1.802     bisitz   5869: div.LC_confirm_box {
                   5870:   background-color: #FAFAFA;
                   5871:   border: 1px solid $lg_border_color;
                   5872:   margin-right: 0;
                   5873:   padding: 5px;
                   5874: }
                   5875: 
                   5876: div.LC_confirm_box .LC_error img,
                   5877: div.LC_confirm_box .LC_success img {
                   5878:   vertical-align: middle;
                   5879: }
                   5880: 
1.1075.2.108  raeburn  5881: .LC_maxwidth {
                   5882:   max-width: 100%;
                   5883:   height: auto;
                   5884: }
                   5885: 
                   5886: .LC_textsize_mobile {
                   5887:   \@media only screen and (max-device-width: 480px) {
                   5888:       -webkit-text-size-adjust:100%; -moz-text-size-adjust:100%; -ms-text-size-adjust:100%;
                   5889:   }
                   5890: }
                   5891: 
1.440     albertel 5892: .LC_icon {
1.771     droeschl 5893:   border: none;
1.790     droeschl 5894:   vertical-align: middle;
1.771     droeschl 5895: }
                   5896: 
1.543     albertel 5897: .LC_docs_spacer {
                   5898:   width: 25px;
                   5899:   height: 1px;
1.771     droeschl 5900:   border: none;
1.543     albertel 5901: }
1.346     albertel 5902: 
1.532     albertel 5903: .LC_internal_info {
1.735     bisitz   5904:   color: #999999;
1.532     albertel 5905: }
                   5906: 
1.794     www      5907: .LC_discussion {
1.1050    www      5908:   background: $data_table_dark;
1.911     bisitz   5909:   border: 1px solid black;
                   5910:   margin: 2px;
1.794     www      5911: }
                   5912: 
                   5913: .LC_disc_action_left {
1.1050    www      5914:   background: $sidebg;
1.911     bisitz   5915:   text-align: left;
1.1050    www      5916:   padding: 4px;
                   5917:   margin: 2px;
1.794     www      5918: }
                   5919: 
                   5920: .LC_disc_action_right {
1.1050    www      5921:   background: $sidebg;
1.911     bisitz   5922:   text-align: right;
1.1050    www      5923:   padding: 4px;
                   5924:   margin: 2px;
1.794     www      5925: }
                   5926: 
                   5927: .LC_disc_new_item {
1.911     bisitz   5928:   background: white;
                   5929:   border: 2px solid red;
1.1050    www      5930:   margin: 4px;
                   5931:   padding: 4px;
1.794     www      5932: }
                   5933: 
                   5934: .LC_disc_old_item {
1.911     bisitz   5935:   background: white;
1.1050    www      5936:   margin: 4px;
                   5937:   padding: 4px;
1.794     www      5938: }
                   5939: 
1.458     albertel 5940: table.LC_pastsubmission {
                   5941:   border: 1px solid black;
                   5942:   margin: 2px;
                   5943: }
                   5944: 
1.924     bisitz   5945: table#LC_menubuttons {
1.345     albertel 5946:   width: 100%;
                   5947:   background: $pgbg;
1.392     albertel 5948:   border: 2px;
1.402     albertel 5949:   border-collapse: separate;
1.803     bisitz   5950:   padding: 0;
1.345     albertel 5951: }
1.392     albertel 5952: 
1.801     tempelho 5953: table#LC_title_bar a {
                   5954:   color: $fontmenu;
                   5955: }
1.836     bisitz   5956: 
1.807     droeschl 5957: table#LC_title_bar {
1.819     tempelho 5958:   clear: both;
1.836     bisitz   5959:   display: none;
1.807     droeschl 5960: }
                   5961: 
1.795     www      5962: table#LC_title_bar,
1.933     droeschl 5963: table.LC_breadcrumbs, /* obsolete? */
1.393     albertel 5964: table#LC_title_bar.LC_with_remote {
1.359     albertel 5965:   width: 100%;
1.392     albertel 5966:   border-color: $pgbg;
                   5967:   border-style: solid;
                   5968:   border-width: $border;
1.379     albertel 5969:   background: $pgbg;
1.801     tempelho 5970:   color: $fontmenu;
1.392     albertel 5971:   border-collapse: collapse;
1.803     bisitz   5972:   padding: 0;
1.819     tempelho 5973:   margin: 0;
1.359     albertel 5974: }
1.795     www      5975: 
1.933     droeschl 5976: ul.LC_breadcrumb_tools_outerlist {
1.913     droeschl 5977:     margin: 0;
                   5978:     padding: 0;
1.933     droeschl 5979:     position: relative;
                   5980:     list-style: none;
1.913     droeschl 5981: }
1.933     droeschl 5982: ul.LC_breadcrumb_tools_outerlist li {
1.913     droeschl 5983:     display: inline;
                   5984: }
1.933     droeschl 5985: 
                   5986: .LC_breadcrumb_tools_navigation {
1.913     droeschl 5987:     padding: 0;
1.933     droeschl 5988:     margin: 0;
                   5989:     float: left;
1.913     droeschl 5990: }
1.933     droeschl 5991: .LC_breadcrumb_tools_tools {
                   5992:     padding: 0;
                   5993:     margin: 0;
1.913     droeschl 5994:     float: right;
                   5995: }
                   5996: 
1.359     albertel 5997: table#LC_title_bar td {
                   5998:   background: $tabbg;
                   5999: }
1.795     www      6000: 
1.911     bisitz   6001: table#LC_menubuttons img {
1.803     bisitz   6002:   border: none;
1.346     albertel 6003: }
1.795     www      6004: 
1.842     droeschl 6005: .LC_breadcrumbs_component {
1.911     bisitz   6006:   float: right;
                   6007:   margin: 0 1em;
1.357     albertel 6008: }
1.842     droeschl 6009: .LC_breadcrumbs_component img {
1.911     bisitz   6010:   vertical-align: middle;
1.777     tempelho 6011: }
1.795     www      6012: 
1.1075.2.108  raeburn  6013: .LC_breadcrumbs_hoverable {
                   6014:   background: $sidebg;
                   6015: }
                   6016: 
1.383     albertel 6017: td.LC_table_cell_checkbox {
                   6018:   text-align: center;
                   6019: }
1.795     www      6020: 
                   6021: .LC_fontsize_small {
1.911     bisitz   6022:   font-size: 70%;
1.705     tempelho 6023: }
                   6024: 
1.844     bisitz   6025: #LC_breadcrumbs {
1.911     bisitz   6026:   clear:both;
                   6027:   background: $sidebg;
                   6028:   border-bottom: 1px solid $lg_border_color;
                   6029:   line-height: 2.5em;
1.933     droeschl 6030:   overflow: hidden;
1.911     bisitz   6031:   margin: 0;
                   6032:   padding: 0;
1.995     raeburn  6033:   text-align: left;
1.819     tempelho 6034: }
1.862     bisitz   6035: 
1.1075.2.16  raeburn  6036: .LC_head_subbox, .LC_actionbox {
1.911     bisitz   6037:   clear:both;
                   6038:   background: #F8F8F8; /* $sidebg; */
1.915     droeschl 6039:   border: 1px solid $sidebg;
1.1075.2.16  raeburn  6040:   margin: 0 0 10px 0;
1.966     bisitz   6041:   padding: 3px;
1.995     raeburn  6042:   text-align: left;
1.822     bisitz   6043: }
                   6044: 
1.795     www      6045: .LC_fontsize_medium {
1.911     bisitz   6046:   font-size: 85%;
1.705     tempelho 6047: }
                   6048: 
1.795     www      6049: .LC_fontsize_large {
1.911     bisitz   6050:   font-size: 120%;
1.705     tempelho 6051: }
                   6052: 
1.346     albertel 6053: .LC_menubuttons_inline_text {
                   6054:   color: $font;
1.698     harmsja  6055:   font-size: 90%;
1.701     harmsja  6056:   padding-left:3px;
1.346     albertel 6057: }
                   6058: 
1.934     droeschl 6059: .LC_menubuttons_inline_text img{
                   6060:   vertical-align: middle;
                   6061: }
                   6062: 
1.1051    www      6063: li.LC_menubuttons_inline_text img {
1.951     onken    6064:   cursor:pointer;
1.1002    droeschl 6065:   text-decoration: none;
1.951     onken    6066: }
                   6067: 
1.526     www      6068: .LC_menubuttons_link {
                   6069:   text-decoration: none;
                   6070: }
1.795     www      6071: 
1.522     albertel 6072: .LC_menubuttons_category {
1.521     www      6073:   color: $font;
1.526     www      6074:   background: $pgbg;
1.521     www      6075:   font-size: larger;
                   6076:   font-weight: bold;
                   6077: }
                   6078: 
1.346     albertel 6079: td.LC_menubuttons_text {
1.911     bisitz   6080:   color: $font;
1.346     albertel 6081: }
1.706     harmsja  6082: 
1.346     albertel 6083: .LC_current_location {
                   6084:   background: $tabbg;
                   6085: }
1.795     www      6086: 
1.938     bisitz   6087: table.LC_data_table {
1.347     albertel 6088:   border: 1px solid #000000;
1.402     albertel 6089:   border-collapse: separate;
1.426     albertel 6090:   border-spacing: 1px;
1.610     albertel 6091:   background: $pgbg;
1.347     albertel 6092: }
1.795     www      6093: 
1.422     albertel 6094: .LC_data_table_dense {
                   6095:   font-size: small;
                   6096: }
1.795     www      6097: 
1.507     raeburn  6098: table.LC_nested_outer {
                   6099:   border: 1px solid #000000;
1.589     raeburn  6100:   border-collapse: collapse;
1.803     bisitz   6101:   border-spacing: 0;
1.507     raeburn  6102:   width: 100%;
                   6103: }
1.795     www      6104: 
1.879     raeburn  6105: table.LC_innerpickbox,
1.507     raeburn  6106: table.LC_nested {
1.803     bisitz   6107:   border: none;
1.589     raeburn  6108:   border-collapse: collapse;
1.803     bisitz   6109:   border-spacing: 0;
1.507     raeburn  6110:   width: 100%;
                   6111: }
1.795     www      6112: 
1.911     bisitz   6113: table.LC_data_table tr th,
                   6114: table.LC_calendar tr th,
1.879     raeburn  6115: table.LC_prior_tries tr th,
                   6116: table.LC_innerpickbox tr th {
1.349     albertel 6117:   font-weight: bold;
                   6118:   background-color: $data_table_head;
1.801     tempelho 6119:   color:$fontmenu;
1.701     harmsja  6120:   font-size:90%;
1.347     albertel 6121: }
1.795     www      6122: 
1.879     raeburn  6123: table.LC_innerpickbox tr th,
                   6124: table.LC_innerpickbox tr td {
                   6125:   vertical-align: top;
                   6126: }
                   6127: 
1.711     raeburn  6128: table.LC_data_table tr.LC_info_row > td {
1.735     bisitz   6129:   background-color: #CCCCCC;
1.711     raeburn  6130:   font-weight: bold;
                   6131:   text-align: left;
                   6132: }
1.795     www      6133: 
1.912     bisitz   6134: table.LC_data_table tr.LC_odd_row > td {
                   6135:   background-color: $data_table_light;
                   6136:   padding: 2px;
                   6137:   vertical-align: top;
                   6138: }
                   6139: 
1.809     bisitz   6140: table.LC_pick_box tr > td.LC_odd_row {
1.349     albertel 6141:   background-color: $data_table_light;
1.912     bisitz   6142:   vertical-align: top;
                   6143: }
                   6144: 
                   6145: table.LC_data_table tr.LC_even_row > td {
                   6146:   background-color: $data_table_dark;
1.425     albertel 6147:   padding: 2px;
1.900     bisitz   6148:   vertical-align: top;
1.347     albertel 6149: }
1.795     www      6150: 
1.809     bisitz   6151: table.LC_pick_box tr > td.LC_even_row {
1.349     albertel 6152:   background-color: $data_table_dark;
1.900     bisitz   6153:   vertical-align: top;
1.347     albertel 6154: }
1.795     www      6155: 
1.425     albertel 6156: table.LC_data_table tr.LC_data_table_highlight td {
                   6157:   background-color: $data_table_darker;
                   6158: }
1.795     www      6159: 
1.639     raeburn  6160: table.LC_data_table tr td.LC_leftcol_header {
                   6161:   background-color: $data_table_head;
                   6162:   font-weight: bold;
                   6163: }
1.795     www      6164: 
1.451     albertel 6165: table.LC_data_table tr.LC_empty_row td,
1.507     raeburn  6166: table.LC_nested tr.LC_empty_row td {
1.421     albertel 6167:   font-weight: bold;
                   6168:   font-style: italic;
                   6169:   text-align: center;
                   6170:   padding: 8px;
1.347     albertel 6171: }
1.795     www      6172: 
1.1075.2.30  raeburn  6173: table.LC_data_table tr.LC_empty_row td,
                   6174: table.LC_data_table tr.LC_footer_row td {
1.940     bisitz   6175:   background-color: $sidebg;
                   6176: }
                   6177: 
                   6178: table.LC_nested tr.LC_empty_row td {
                   6179:   background-color: #FFFFFF;
                   6180: }
                   6181: 
1.890     droeschl 6182: table.LC_caption {
                   6183: }
                   6184: 
1.507     raeburn  6185: table.LC_nested tr.LC_empty_row td {
1.465     albertel 6186:   padding: 4ex
                   6187: }
1.795     www      6188: 
1.507     raeburn  6189: table.LC_nested_outer tr th {
                   6190:   font-weight: bold;
1.801     tempelho 6191:   color:$fontmenu;
1.507     raeburn  6192:   background-color: $data_table_head;
1.701     harmsja  6193:   font-size: small;
1.507     raeburn  6194:   border-bottom: 1px solid #000000;
                   6195: }
1.795     www      6196: 
1.507     raeburn  6197: table.LC_nested_outer tr td.LC_subheader {
                   6198:   background-color: $data_table_head;
                   6199:   font-weight: bold;
                   6200:   font-size: small;
                   6201:   border-bottom: 1px solid #000000;
                   6202:   text-align: right;
1.451     albertel 6203: }
1.795     www      6204: 
1.507     raeburn  6205: table.LC_nested tr.LC_info_row td {
1.735     bisitz   6206:   background-color: #CCCCCC;
1.451     albertel 6207:   font-weight: bold;
                   6208:   font-size: small;
1.507     raeburn  6209:   text-align: center;
                   6210: }
1.795     www      6211: 
1.589     raeburn  6212: table.LC_nested tr.LC_info_row td.LC_left_item,
                   6213: table.LC_nested_outer tr th.LC_left_item {
1.507     raeburn  6214:   text-align: left;
1.451     albertel 6215: }
1.795     www      6216: 
1.507     raeburn  6217: table.LC_nested td {
1.735     bisitz   6218:   background-color: #FFFFFF;
1.451     albertel 6219:   font-size: small;
1.507     raeburn  6220: }
1.795     www      6221: 
1.507     raeburn  6222: table.LC_nested_outer tr th.LC_right_item,
                   6223: table.LC_nested tr.LC_info_row td.LC_right_item,
                   6224: table.LC_nested tr.LC_odd_row td.LC_right_item,
                   6225: table.LC_nested tr td.LC_right_item {
1.451     albertel 6226:   text-align: right;
                   6227: }
                   6228: 
1.507     raeburn  6229: table.LC_nested tr.LC_odd_row td {
1.735     bisitz   6230:   background-color: #EEEEEE;
1.451     albertel 6231: }
                   6232: 
1.473     raeburn  6233: table.LC_createuser {
                   6234: }
                   6235: 
                   6236: table.LC_createuser tr.LC_section_row td {
1.701     harmsja  6237:   font-size: small;
1.473     raeburn  6238: }
                   6239: 
                   6240: table.LC_createuser tr.LC_info_row td  {
1.735     bisitz   6241:   background-color: #CCCCCC;
1.473     raeburn  6242:   font-weight: bold;
                   6243:   text-align: center;
                   6244: }
                   6245: 
1.349     albertel 6246: table.LC_calendar {
                   6247:   border: 1px solid #000000;
                   6248:   border-collapse: collapse;
1.917     raeburn  6249:   width: 98%;
1.349     albertel 6250: }
1.795     www      6251: 
1.349     albertel 6252: table.LC_calendar_pickdate {
                   6253:   font-size: xx-small;
                   6254: }
1.795     www      6255: 
1.349     albertel 6256: table.LC_calendar tr td {
                   6257:   border: 1px solid #000000;
                   6258:   vertical-align: top;
1.917     raeburn  6259:   width: 14%;
1.349     albertel 6260: }
1.795     www      6261: 
1.349     albertel 6262: table.LC_calendar tr td.LC_calendar_day_empty {
                   6263:   background-color: $data_table_dark;
                   6264: }
1.795     www      6265: 
1.779     bisitz   6266: table.LC_calendar tr td.LC_calendar_day_current {
                   6267:   background-color: $data_table_highlight;
1.777     tempelho 6268: }
1.795     www      6269: 
1.938     bisitz   6270: table.LC_data_table tr td.LC_mail_new {
1.349     albertel 6271:   background-color: $mail_new;
                   6272: }
1.795     www      6273: 
1.938     bisitz   6274: table.LC_data_table tr.LC_mail_new:hover {
1.349     albertel 6275:   background-color: $mail_new_hover;
                   6276: }
1.795     www      6277: 
1.938     bisitz   6278: table.LC_data_table tr td.LC_mail_read {
1.349     albertel 6279:   background-color: $mail_read;
                   6280: }
1.795     www      6281: 
1.938     bisitz   6282: /*
                   6283: table.LC_data_table tr.LC_mail_read:hover {
1.349     albertel 6284:   background-color: $mail_read_hover;
                   6285: }
1.938     bisitz   6286: */
1.795     www      6287: 
1.938     bisitz   6288: table.LC_data_table tr td.LC_mail_replied {
1.349     albertel 6289:   background-color: $mail_replied;
                   6290: }
1.795     www      6291: 
1.938     bisitz   6292: /*
                   6293: table.LC_data_table tr.LC_mail_replied:hover {
1.349     albertel 6294:   background-color: $mail_replied_hover;
                   6295: }
1.938     bisitz   6296: */
1.795     www      6297: 
1.938     bisitz   6298: table.LC_data_table tr td.LC_mail_other {
1.349     albertel 6299:   background-color: $mail_other;
                   6300: }
1.795     www      6301: 
1.938     bisitz   6302: /*
                   6303: table.LC_data_table tr.LC_mail_other:hover {
1.349     albertel 6304:   background-color: $mail_other_hover;
                   6305: }
1.938     bisitz   6306: */
1.494     raeburn  6307: 
1.777     tempelho 6308: table.LC_data_table tr > td.LC_browser_file,
                   6309: table.LC_data_table tr > td.LC_browser_file_published {
1.899     bisitz   6310:   background: #AAEE77;
1.389     albertel 6311: }
1.795     www      6312: 
1.777     tempelho 6313: table.LC_data_table tr > td.LC_browser_file_locked,
                   6314: table.LC_data_table tr > td.LC_browser_file_unpublished {
1.389     albertel 6315:   background: #FFAA99;
1.387     albertel 6316: }
1.795     www      6317: 
1.777     tempelho 6318: table.LC_data_table tr > td.LC_browser_file_obsolete {
1.899     bisitz   6319:   background: #888888;
1.779     bisitz   6320: }
1.795     www      6321: 
1.777     tempelho 6322: table.LC_data_table tr > td.LC_browser_file_modified,
1.779     bisitz   6323: table.LC_data_table tr > td.LC_browser_file_metamodified {
1.899     bisitz   6324:   background: #F8F866;
1.777     tempelho 6325: }
1.795     www      6326: 
1.696     bisitz   6327: table.LC_data_table tr.LC_browser_folder > td {
1.899     bisitz   6328:   background: #E0E8FF;
1.387     albertel 6329: }
1.696     bisitz   6330: 
1.707     bisitz   6331: table.LC_data_table tr > td.LC_roles_is {
1.911     bisitz   6332:   /* background: #77FF77; */
1.707     bisitz   6333: }
1.795     www      6334: 
1.707     bisitz   6335: table.LC_data_table tr > td.LC_roles_future {
1.939     bisitz   6336:   border-right: 8px solid #FFFF77;
1.707     bisitz   6337: }
1.795     www      6338: 
1.707     bisitz   6339: table.LC_data_table tr > td.LC_roles_will {
1.939     bisitz   6340:   border-right: 8px solid #FFAA77;
1.707     bisitz   6341: }
1.795     www      6342: 
1.707     bisitz   6343: table.LC_data_table tr > td.LC_roles_expired {
1.939     bisitz   6344:   border-right: 8px solid #FF7777;
1.707     bisitz   6345: }
1.795     www      6346: 
1.707     bisitz   6347: table.LC_data_table tr > td.LC_roles_will_not {
1.939     bisitz   6348:   border-right: 8px solid #AAFF77;
1.707     bisitz   6349: }
1.795     www      6350: 
1.707     bisitz   6351: table.LC_data_table tr > td.LC_roles_selected {
1.939     bisitz   6352:   border-right: 8px solid #11CC55;
1.707     bisitz   6353: }
                   6354: 
1.388     albertel 6355: span.LC_current_location {
1.701     harmsja  6356:   font-size:larger;
1.388     albertel 6357:   background: $pgbg;
                   6358: }
1.387     albertel 6359: 
1.1029    www      6360: span.LC_current_nav_location {
                   6361:   font-weight:bold;
                   6362:   background: $sidebg;
                   6363: }
                   6364: 
1.395     albertel 6365: span.LC_parm_menu_item {
                   6366:   font-size: larger;
                   6367: }
1.795     www      6368: 
1.395     albertel 6369: span.LC_parm_scope_all {
                   6370:   color: red;
                   6371: }
1.795     www      6372: 
1.395     albertel 6373: span.LC_parm_scope_folder {
                   6374:   color: green;
                   6375: }
1.795     www      6376: 
1.395     albertel 6377: span.LC_parm_scope_resource {
                   6378:   color: orange;
                   6379: }
1.795     www      6380: 
1.395     albertel 6381: span.LC_parm_part {
                   6382:   color: blue;
                   6383: }
1.795     www      6384: 
1.911     bisitz   6385: span.LC_parm_folder,
                   6386: span.LC_parm_symb {
1.395     albertel 6387:   font-size: x-small;
                   6388:   font-family: $mono;
                   6389:   color: #AAAAAA;
                   6390: }
                   6391: 
1.977     bisitz   6392: ul.LC_parm_parmlist li {
                   6393:   display: inline-block;
                   6394:   padding: 0.3em 0.8em;
                   6395:   vertical-align: top;
                   6396:   width: 150px;
                   6397:   border-top:1px solid $lg_border_color;
                   6398: }
                   6399: 
1.795     www      6400: td.LC_parm_overview_level_menu,
                   6401: td.LC_parm_overview_map_menu,
                   6402: td.LC_parm_overview_parm_selectors,
                   6403: td.LC_parm_overview_restrictions  {
1.396     albertel 6404:   border: 1px solid black;
                   6405:   border-collapse: collapse;
                   6406: }
1.795     www      6407: 
1.396     albertel 6408: table.LC_parm_overview_restrictions td {
                   6409:   border-width: 1px 4px 1px 4px;
                   6410:   border-style: solid;
                   6411:   border-color: $pgbg;
                   6412:   text-align: center;
                   6413: }
1.795     www      6414: 
1.396     albertel 6415: table.LC_parm_overview_restrictions th {
                   6416:   background: $tabbg;
                   6417:   border-width: 1px 4px 1px 4px;
                   6418:   border-style: solid;
                   6419:   border-color: $pgbg;
                   6420: }
1.795     www      6421: 
1.398     albertel 6422: table#LC_helpmenu {
1.803     bisitz   6423:   border: none;
1.398     albertel 6424:   height: 55px;
1.803     bisitz   6425:   border-spacing: 0;
1.398     albertel 6426: }
                   6427: 
                   6428: table#LC_helpmenu fieldset legend {
                   6429:   font-size: larger;
                   6430: }
1.795     www      6431: 
1.397     albertel 6432: table#LC_helpmenu_links {
                   6433:   width: 100%;
                   6434:   border: 1px solid black;
                   6435:   background: $pgbg;
1.803     bisitz   6436:   padding: 0;
1.397     albertel 6437:   border-spacing: 1px;
                   6438: }
1.795     www      6439: 
1.397     albertel 6440: table#LC_helpmenu_links tr td {
                   6441:   padding: 1px;
                   6442:   background: $tabbg;
1.399     albertel 6443:   text-align: center;
                   6444:   font-weight: bold;
1.397     albertel 6445: }
1.396     albertel 6446: 
1.795     www      6447: table#LC_helpmenu_links a:link,
                   6448: table#LC_helpmenu_links a:visited,
1.397     albertel 6449: table#LC_helpmenu_links a:active {
                   6450:   text-decoration: none;
                   6451:   color: $font;
                   6452: }
1.795     www      6453: 
1.397     albertel 6454: table#LC_helpmenu_links a:hover {
                   6455:   text-decoration: underline;
                   6456:   color: $vlink;
                   6457: }
1.396     albertel 6458: 
1.417     albertel 6459: .LC_chrt_popup_exists {
                   6460:   border: 1px solid #339933;
                   6461:   margin: -1px;
                   6462: }
1.795     www      6463: 
1.417     albertel 6464: .LC_chrt_popup_up {
                   6465:   border: 1px solid yellow;
                   6466:   margin: -1px;
                   6467: }
1.795     www      6468: 
1.417     albertel 6469: .LC_chrt_popup {
                   6470:   border: 1px solid #8888FF;
                   6471:   background: #CCCCFF;
                   6472: }
1.795     www      6473: 
1.421     albertel 6474: table.LC_pick_box {
                   6475:   border-collapse: separate;
                   6476:   background: white;
                   6477:   border: 1px solid black;
                   6478:   border-spacing: 1px;
                   6479: }
1.795     www      6480: 
1.421     albertel 6481: table.LC_pick_box td.LC_pick_box_title {
1.850     bisitz   6482:   background: $sidebg;
1.421     albertel 6483:   font-weight: bold;
1.900     bisitz   6484:   text-align: left;
1.740     bisitz   6485:   vertical-align: top;
1.421     albertel 6486:   width: 184px;
                   6487:   padding: 8px;
                   6488: }
1.795     www      6489: 
1.579     raeburn  6490: table.LC_pick_box td.LC_pick_box_value {
                   6491:   text-align: left;
                   6492:   padding: 8px;
                   6493: }
1.795     www      6494: 
1.579     raeburn  6495: table.LC_pick_box td.LC_pick_box_select {
                   6496:   text-align: left;
                   6497:   padding: 8px;
                   6498: }
1.795     www      6499: 
1.424     albertel 6500: table.LC_pick_box td.LC_pick_box_separator {
1.803     bisitz   6501:   padding: 0;
1.421     albertel 6502:   height: 1px;
                   6503:   background: black;
                   6504: }
1.795     www      6505: 
1.421     albertel 6506: table.LC_pick_box td.LC_pick_box_submit {
                   6507:   text-align: right;
                   6508: }
1.795     www      6509: 
1.579     raeburn  6510: table.LC_pick_box td.LC_evenrow_value {
                   6511:   text-align: left;
                   6512:   padding: 8px;
                   6513:   background-color: $data_table_light;
                   6514: }
1.795     www      6515: 
1.579     raeburn  6516: table.LC_pick_box td.LC_oddrow_value {
                   6517:   text-align: left;
                   6518:   padding: 8px;
                   6519:   background-color: $data_table_light;
                   6520: }
1.795     www      6521: 
1.579     raeburn  6522: span.LC_helpform_receipt_cat {
                   6523:   font-weight: bold;
                   6524: }
1.795     www      6525: 
1.424     albertel 6526: table.LC_group_priv_box {
                   6527:   background: white;
                   6528:   border: 1px solid black;
                   6529:   border-spacing: 1px;
                   6530: }
1.795     www      6531: 
1.424     albertel 6532: table.LC_group_priv_box td.LC_pick_box_title {
                   6533:   background: $tabbg;
                   6534:   font-weight: bold;
                   6535:   text-align: right;
                   6536:   width: 184px;
                   6537: }
1.795     www      6538: 
1.424     albertel 6539: table.LC_group_priv_box td.LC_groups_fixed {
                   6540:   background: $data_table_light;
                   6541:   text-align: center;
                   6542: }
1.795     www      6543: 
1.424     albertel 6544: table.LC_group_priv_box td.LC_groups_optional {
                   6545:   background: $data_table_dark;
                   6546:   text-align: center;
                   6547: }
1.795     www      6548: 
1.424     albertel 6549: table.LC_group_priv_box td.LC_groups_functionality {
                   6550:   background: $data_table_darker;
                   6551:   text-align: center;
                   6552:   font-weight: bold;
                   6553: }
1.795     www      6554: 
1.424     albertel 6555: table.LC_group_priv td {
                   6556:   text-align: left;
1.803     bisitz   6557:   padding: 0;
1.424     albertel 6558: }
                   6559: 
                   6560: .LC_navbuttons {
                   6561:   margin: 2ex 0ex 2ex 0ex;
                   6562: }
1.795     www      6563: 
1.423     albertel 6564: .LC_topic_bar {
                   6565:   font-weight: bold;
                   6566:   background: $tabbg;
1.918     wenzelju 6567:   margin: 1em 0em 1em 2em;
1.805     bisitz   6568:   padding: 3px;
1.918     wenzelju 6569:   font-size: 1.2em;
1.423     albertel 6570: }
1.795     www      6571: 
1.423     albertel 6572: .LC_topic_bar span {
1.918     wenzelju 6573:   left: 0.5em;
                   6574:   position: absolute;
1.423     albertel 6575:   vertical-align: middle;
1.918     wenzelju 6576:   font-size: 1.2em;
1.423     albertel 6577: }
1.795     www      6578: 
1.423     albertel 6579: table.LC_course_group_status {
                   6580:   margin: 20px;
                   6581: }
1.795     www      6582: 
1.423     albertel 6583: table.LC_status_selector td {
                   6584:   vertical-align: top;
                   6585:   text-align: center;
1.424     albertel 6586:   padding: 4px;
                   6587: }
1.795     www      6588: 
1.599     albertel 6589: div.LC_feedback_link {
1.616     albertel 6590:   clear: both;
1.829     kalberla 6591:   background: $sidebg;
1.779     bisitz   6592:   width: 100%;
1.829     kalberla 6593:   padding-bottom: 10px;
                   6594:   border: 1px $tabbg solid;
1.833     kalberla 6595:   height: 22px;
                   6596:   line-height: 22px;
                   6597:   padding-top: 5px;
                   6598: }
                   6599: 
                   6600: div.LC_feedback_link img {
                   6601:   height: 22px;
1.867     kalberla 6602:   vertical-align:middle;
1.829     kalberla 6603: }
                   6604: 
1.911     bisitz   6605: div.LC_feedback_link a {
1.829     kalberla 6606:   text-decoration: none;
1.489     raeburn  6607: }
1.795     www      6608: 
1.867     kalberla 6609: div.LC_comblock {
1.911     bisitz   6610:   display:inline;
1.867     kalberla 6611:   color:$font;
                   6612:   font-size:90%;
                   6613: }
                   6614: 
                   6615: div.LC_feedback_link div.LC_comblock {
                   6616:   padding-left:5px;
                   6617: }
                   6618: 
                   6619: div.LC_feedback_link div.LC_comblock a {
                   6620:   color:$font;
                   6621: }
                   6622: 
1.489     raeburn  6623: span.LC_feedback_link {
1.858     bisitz   6624:   /* background: $feedback_link_bg; */
1.599     albertel 6625:   font-size: larger;
                   6626: }
1.795     www      6627: 
1.599     albertel 6628: span.LC_message_link {
1.858     bisitz   6629:   /* background: $feedback_link_bg; */
1.599     albertel 6630:   font-size: larger;
                   6631:   position: absolute;
                   6632:   right: 1em;
1.489     raeburn  6633: }
1.421     albertel 6634: 
1.515     albertel 6635: table.LC_prior_tries {
1.524     albertel 6636:   border: 1px solid #000000;
                   6637:   border-collapse: separate;
                   6638:   border-spacing: 1px;
1.515     albertel 6639: }
1.523     albertel 6640: 
1.515     albertel 6641: table.LC_prior_tries td {
1.524     albertel 6642:   padding: 2px;
1.515     albertel 6643: }
1.523     albertel 6644: 
                   6645: .LC_answer_correct {
1.795     www      6646:   background: lightgreen;
                   6647:   color: darkgreen;
                   6648:   padding: 6px;
1.523     albertel 6649: }
1.795     www      6650: 
1.523     albertel 6651: .LC_answer_charged_try {
1.797     www      6652:   background: #FFAAAA;
1.795     www      6653:   color: darkred;
                   6654:   padding: 6px;
1.523     albertel 6655: }
1.795     www      6656: 
1.779     bisitz   6657: .LC_answer_not_charged_try,
1.523     albertel 6658: .LC_answer_no_grade,
                   6659: .LC_answer_late {
1.795     www      6660:   background: lightyellow;
1.523     albertel 6661:   color: black;
1.795     www      6662:   padding: 6px;
1.523     albertel 6663: }
1.795     www      6664: 
1.523     albertel 6665: .LC_answer_previous {
1.795     www      6666:   background: lightblue;
                   6667:   color: darkblue;
                   6668:   padding: 6px;
1.523     albertel 6669: }
1.795     www      6670: 
1.779     bisitz   6671: .LC_answer_no_message {
1.777     tempelho 6672:   background: #FFFFFF;
                   6673:   color: black;
1.795     www      6674:   padding: 6px;
1.779     bisitz   6675: }
1.795     www      6676: 
1.779     bisitz   6677: .LC_answer_unknown {
                   6678:   background: orange;
                   6679:   color: black;
1.795     www      6680:   padding: 6px;
1.777     tempelho 6681: }
1.795     www      6682: 
1.529     albertel 6683: span.LC_prior_numerical,
                   6684: span.LC_prior_string,
                   6685: span.LC_prior_custom,
                   6686: span.LC_prior_reaction,
                   6687: span.LC_prior_math {
1.925     bisitz   6688:   font-family: $mono;
1.523     albertel 6689:   white-space: pre;
                   6690: }
                   6691: 
1.525     albertel 6692: span.LC_prior_string {
1.925     bisitz   6693:   font-family: $mono;
1.525     albertel 6694:   white-space: pre;
                   6695: }
                   6696: 
1.523     albertel 6697: table.LC_prior_option {
                   6698:   width: 100%;
                   6699:   border-collapse: collapse;
                   6700: }
1.795     www      6701: 
1.911     bisitz   6702: table.LC_prior_rank,
1.795     www      6703: table.LC_prior_match {
1.528     albertel 6704:   border-collapse: collapse;
                   6705: }
1.795     www      6706: 
1.528     albertel 6707: table.LC_prior_option tr td,
                   6708: table.LC_prior_rank tr td,
                   6709: table.LC_prior_match tr td {
1.524     albertel 6710:   border: 1px solid #000000;
1.515     albertel 6711: }
                   6712: 
1.855     bisitz   6713: .LC_nobreak {
1.544     albertel 6714:   white-space: nowrap;
1.519     raeburn  6715: }
                   6716: 
1.576     raeburn  6717: span.LC_cusr_emph {
                   6718:   font-style: italic;
                   6719: }
                   6720: 
1.633     raeburn  6721: span.LC_cusr_subheading {
                   6722:   font-weight: normal;
                   6723:   font-size: 85%;
                   6724: }
                   6725: 
1.861     bisitz   6726: div.LC_docs_entry_move {
1.859     bisitz   6727:   border: 1px solid #BBBBBB;
1.545     albertel 6728:   background: #DDDDDD;
1.861     bisitz   6729:   width: 22px;
1.859     bisitz   6730:   padding: 1px;
                   6731:   margin: 0;
1.545     albertel 6732: }
                   6733: 
1.861     bisitz   6734: table.LC_data_table tr > td.LC_docs_entry_commands,
                   6735: table.LC_data_table tr > td.LC_docs_entry_parameter {
1.545     albertel 6736:   font-size: x-small;
                   6737: }
1.795     www      6738: 
1.861     bisitz   6739: .LC_docs_entry_parameter {
                   6740:   white-space: nowrap;
                   6741: }
                   6742: 
1.544     albertel 6743: .LC_docs_copy {
1.545     albertel 6744:   color: #000099;
1.544     albertel 6745: }
1.795     www      6746: 
1.544     albertel 6747: .LC_docs_cut {
1.545     albertel 6748:   color: #550044;
1.544     albertel 6749: }
1.795     www      6750: 
1.544     albertel 6751: .LC_docs_rename {
1.545     albertel 6752:   color: #009900;
1.544     albertel 6753: }
1.795     www      6754: 
1.544     albertel 6755: .LC_docs_remove {
1.545     albertel 6756:   color: #990000;
                   6757: }
                   6758: 
1.547     albertel 6759: .LC_docs_reinit_warn,
                   6760: .LC_docs_ext_edit {
                   6761:   font-size: x-small;
                   6762: }
                   6763: 
1.545     albertel 6764: table.LC_docs_adddocs td,
                   6765: table.LC_docs_adddocs th {
                   6766:   border: 1px solid #BBBBBB;
                   6767:   padding: 4px;
                   6768:   background: #DDDDDD;
1.543     albertel 6769: }
                   6770: 
1.584     albertel 6771: table.LC_sty_begin {
                   6772:   background: #BBFFBB;
                   6773: }
1.795     www      6774: 
1.584     albertel 6775: table.LC_sty_end {
                   6776:   background: #FFBBBB;
                   6777: }
                   6778: 
1.589     raeburn  6779: table.LC_double_column {
1.803     bisitz   6780:   border-width: 0;
1.589     raeburn  6781:   border-collapse: collapse;
                   6782:   width: 100%;
                   6783:   padding: 2px;
                   6784: }
                   6785: 
                   6786: table.LC_double_column tr td.LC_left_col {
1.590     raeburn  6787:   top: 2px;
1.589     raeburn  6788:   left: 2px;
                   6789:   width: 47%;
                   6790:   vertical-align: top;
                   6791: }
                   6792: 
                   6793: table.LC_double_column tr td.LC_right_col {
                   6794:   top: 2px;
1.779     bisitz   6795:   right: 2px;
1.589     raeburn  6796:   width: 47%;
                   6797:   vertical-align: top;
                   6798: }
                   6799: 
1.591     raeburn  6800: div.LC_left_float {
                   6801:   float: left;
                   6802:   padding-right: 5%;
1.597     albertel 6803:   padding-bottom: 4px;
1.591     raeburn  6804: }
                   6805: 
                   6806: div.LC_clear_float_header {
1.597     albertel 6807:   padding-bottom: 2px;
1.591     raeburn  6808: }
                   6809: 
                   6810: div.LC_clear_float_footer {
1.597     albertel 6811:   padding-top: 10px;
1.591     raeburn  6812:   clear: both;
                   6813: }
                   6814: 
1.597     albertel 6815: div.LC_grade_show_user {
1.941     bisitz   6816: /*  border-left: 5px solid $sidebg; */
                   6817:   border-top: 5px solid #000000;
                   6818:   margin: 50px 0 0 0;
1.936     bisitz   6819:   padding: 15px 0 5px 10px;
1.597     albertel 6820: }
1.795     www      6821: 
1.936     bisitz   6822: div.LC_grade_show_user_odd_row {
1.941     bisitz   6823: /*  border-left: 5px solid #000000; */
                   6824: }
                   6825: 
                   6826: div.LC_grade_show_user div.LC_Box {
                   6827:   margin-right: 50px;
1.597     albertel 6828: }
                   6829: 
                   6830: div.LC_grade_submissions,
                   6831: div.LC_grade_message_center,
1.936     bisitz   6832: div.LC_grade_info_links {
1.597     albertel 6833:   margin: 5px;
                   6834:   width: 99%;
                   6835:   background: #FFFFFF;
                   6836: }
1.795     www      6837: 
1.597     albertel 6838: div.LC_grade_submissions_header,
1.936     bisitz   6839: div.LC_grade_message_center_header {
1.705     tempelho 6840:   font-weight: bold;
                   6841:   font-size: large;
1.597     albertel 6842: }
1.795     www      6843: 
1.597     albertel 6844: div.LC_grade_submissions_body,
1.936     bisitz   6845: div.LC_grade_message_center_body {
1.597     albertel 6846:   border: 1px solid black;
                   6847:   width: 99%;
                   6848:   background: #FFFFFF;
                   6849: }
1.795     www      6850: 
1.613     albertel 6851: table.LC_scantron_action {
                   6852:   width: 100%;
                   6853: }
1.795     www      6854: 
1.613     albertel 6855: table.LC_scantron_action tr th {
1.698     harmsja  6856:   font-weight:bold;
                   6857:   font-style:normal;
1.613     albertel 6858: }
1.795     www      6859: 
1.779     bisitz   6860: .LC_edit_problem_header,
1.614     albertel 6861: div.LC_edit_problem_footer {
1.705     tempelho 6862:   font-weight: normal;
                   6863:   font-size:  medium;
1.602     albertel 6864:   margin: 2px;
1.1060    bisitz   6865:   background-color: $sidebg;
1.600     albertel 6866: }
1.795     www      6867: 
1.600     albertel 6868: div.LC_edit_problem_header,
1.602     albertel 6869: div.LC_edit_problem_header div,
1.614     albertel 6870: div.LC_edit_problem_footer,
                   6871: div.LC_edit_problem_footer div,
1.602     albertel 6872: div.LC_edit_problem_editxml_header,
                   6873: div.LC_edit_problem_editxml_header div {
1.1075.2.112  raeburn  6874:   z-index: 100;
1.600     albertel 6875: }
1.795     www      6876: 
1.600     albertel 6877: div.LC_edit_problem_header_title {
1.705     tempelho 6878:   font-weight: bold;
                   6879:   font-size: larger;
1.602     albertel 6880:   background: $tabbg;
                   6881:   padding: 3px;
1.1060    bisitz   6882:   margin: 0 0 5px 0;
1.602     albertel 6883: }
1.795     www      6884: 
1.602     albertel 6885: table.LC_edit_problem_header_title {
                   6886:   width: 100%;
1.600     albertel 6887:   background: $tabbg;
1.602     albertel 6888: }
                   6889: 
1.1075.2.112  raeburn  6890: div.LC_edit_actionbar {
                   6891:     background-color: $sidebg;
                   6892:     margin: 0;
                   6893:     padding: 0;
                   6894:     line-height: 200%;
1.602     albertel 6895: }
1.795     www      6896: 
1.1075.2.112  raeburn  6897: div.LC_edit_actionbar div{
                   6898:     padding: 0;
                   6899:     margin: 0;
                   6900:     display: inline-block;
1.600     albertel 6901: }
1.795     www      6902: 
1.1075.2.34  raeburn  6903: .LC_edit_opt {
                   6904:   padding-left: 1em;
                   6905:   white-space: nowrap;
                   6906: }
                   6907: 
1.1075.2.57  raeburn  6908: .LC_edit_problem_latexhelper{
                   6909:     text-align: right;
                   6910: }
                   6911: 
                   6912: #LC_edit_problem_colorful div{
                   6913:     margin-left: 40px;
                   6914: }
                   6915: 
1.1075.2.112  raeburn  6916: #LC_edit_problem_codemirror div{
                   6917:     margin-left: 0px;
                   6918: }
                   6919: 
1.911     bisitz   6920: img.stift {
1.803     bisitz   6921:   border-width: 0;
                   6922:   vertical-align: middle;
1.677     riegler  6923: }
1.680     riegler  6924: 
1.923     bisitz   6925: table td.LC_mainmenu_col_fieldset {
1.680     riegler  6926:   vertical-align: top;
1.777     tempelho 6927: }
1.795     www      6928: 
1.716     raeburn  6929: div.LC_createcourse {
1.911     bisitz   6930:   margin: 10px 10px 10px 10px;
1.716     raeburn  6931: }
                   6932: 
1.917     raeburn  6933: .LC_dccid {
1.1075.2.38  raeburn  6934:   float: right;
1.917     raeburn  6935:   margin: 0.2em 0 0 0;
                   6936:   padding: 0;
                   6937:   font-size: 90%;
                   6938:   display:none;
                   6939: }
                   6940: 
1.897     wenzelju 6941: ol.LC_primary_menu a:hover,
1.721     harmsja  6942: ol#LC_MenuBreadcrumbs a:hover,
                   6943: ol#LC_PathBreadcrumbs a:hover,
1.897     wenzelju 6944: ul#LC_secondary_menu a:hover,
1.721     harmsja  6945: .LC_FormSectionClearButton input:hover
1.795     www      6946: ul.LC_TabContent   li:hover a {
1.952     onken    6947:   color:$button_hover;
1.911     bisitz   6948:   text-decoration:none;
1.693     droeschl 6949: }
                   6950: 
1.779     bisitz   6951: h1 {
1.911     bisitz   6952:   padding: 0;
                   6953:   line-height:130%;
1.693     droeschl 6954: }
1.698     harmsja  6955: 
1.911     bisitz   6956: h2,
                   6957: h3,
                   6958: h4,
                   6959: h5,
                   6960: h6 {
                   6961:   margin: 5px 0 5px 0;
                   6962:   padding: 0;
                   6963:   line-height:130%;
1.693     droeschl 6964: }
1.795     www      6965: 
                   6966: .LC_hcell {
1.911     bisitz   6967:   padding:3px 15px 3px 15px;
                   6968:   margin: 0;
                   6969:   background-color:$tabbg;
                   6970:   color:$fontmenu;
                   6971:   border-bottom:solid 1px $lg_border_color;
1.693     droeschl 6972: }
1.795     www      6973: 
1.840     bisitz   6974: .LC_Box > .LC_hcell {
1.911     bisitz   6975:   margin: 0 -10px 10px -10px;
1.835     bisitz   6976: }
                   6977: 
1.721     harmsja  6978: .LC_noBorder {
1.911     bisitz   6979:   border: 0;
1.698     harmsja  6980: }
1.693     droeschl 6981: 
1.721     harmsja  6982: .LC_FormSectionClearButton input {
1.911     bisitz   6983:   background-color:transparent;
                   6984:   border: none;
                   6985:   cursor:pointer;
                   6986:   text-decoration:underline;
1.693     droeschl 6987: }
1.763     bisitz   6988: 
                   6989: .LC_help_open_topic {
1.911     bisitz   6990:   color: #FFFFFF;
                   6991:   background-color: #EEEEFF;
                   6992:   margin: 1px;
                   6993:   padding: 4px;
                   6994:   border: 1px solid #000033;
                   6995:   white-space: nowrap;
                   6996:   /* vertical-align: middle; */
1.759     neumanie 6997: }
1.693     droeschl 6998: 
1.911     bisitz   6999: dl,
                   7000: ul,
                   7001: div,
                   7002: fieldset {
                   7003:   margin: 10px 10px 10px 0;
                   7004:   /* overflow: hidden; */
1.693     droeschl 7005: }
1.795     www      7006: 
1.1075.2.90  raeburn  7007: article.geogebraweb div {
                   7008:     margin: 0;
                   7009: }
                   7010: 
1.838     bisitz   7011: fieldset > legend {
1.911     bisitz   7012:   font-weight: bold;
                   7013:   padding: 0 5px 0 5px;
1.838     bisitz   7014: }
                   7015: 
1.813     bisitz   7016: #LC_nav_bar {
1.911     bisitz   7017:   float: left;
1.995     raeburn  7018:   background-color: $pgbg_or_bgcolor;
1.966     bisitz   7019:   margin: 0 0 2px 0;
1.807     droeschl 7020: }
                   7021: 
1.916     droeschl 7022: #LC_realm {
                   7023:   margin: 0.2em 0 0 0;
                   7024:   padding: 0;
                   7025:   font-weight: bold;
                   7026:   text-align: center;
1.995     raeburn  7027:   background-color: $pgbg_or_bgcolor;
1.916     droeschl 7028: }
                   7029: 
1.911     bisitz   7030: #LC_nav_bar em {
                   7031:   font-weight: bold;
                   7032:   font-style: normal;
1.807     droeschl 7033: }
                   7034: 
1.897     wenzelju 7035: ol.LC_primary_menu {
1.934     droeschl 7036:   margin: 0;
1.1075.2.2  raeburn  7037:   padding: 0;
1.807     droeschl 7038: }
                   7039: 
1.852     droeschl 7040: ol#LC_PathBreadcrumbs {
1.911     bisitz   7041:   margin: 0;
1.693     droeschl 7042: }
                   7043: 
1.897     wenzelju 7044: ol.LC_primary_menu li {
1.1075.2.2  raeburn  7045:   color: RGB(80, 80, 80);
                   7046:   vertical-align: middle;
                   7047:   text-align: left;
                   7048:   list-style: none;
1.1075.2.112  raeburn  7049:   position: relative;
1.1075.2.2  raeburn  7050:   float: left;
1.1075.2.112  raeburn  7051:   z-index: 100; /* will be displayed above codemirror and underneath the help-layer */
                   7052:   line-height: 1.5em;
1.1075.2.2  raeburn  7053: }
                   7054: 
1.1075.2.113  raeburn  7055: ol.LC_primary_menu li a, 
1.1075.2.112  raeburn  7056: ol.LC_primary_menu li p {
1.1075.2.2  raeburn  7057:   display: block;
                   7058:   margin: 0;
                   7059:   padding: 0 5px 0 10px;
                   7060:   text-decoration: none;
                   7061: }
                   7062: 
1.1075.2.112  raeburn  7063: ol.LC_primary_menu li p span.LC_primary_menu_innertitle {
                   7064:   display: inline-block;
                   7065:   width: 95%;
                   7066:   text-align: left;
                   7067: }
                   7068: 
                   7069: ol.LC_primary_menu li p span.LC_primary_menu_innerarrow {
                   7070:   display: inline-block;
                   7071:   width: 5%;
                   7072:   float: right;
                   7073:   text-align: right;
                   7074:   font-size: 70%;
                   7075: }
                   7076: 
                   7077: ol.LC_primary_menu ul {
1.1075.2.2  raeburn  7078:   display: none;
1.1075.2.112  raeburn  7079:   width: 15em;
1.1075.2.2  raeburn  7080:   background-color: $data_table_light;
1.1075.2.112  raeburn  7081:   position: absolute;
                   7082:   top: 100%;
                   7083: }
                   7084: 
                   7085: ol.LC_primary_menu ul ul {
                   7086:   left: 100%;
                   7087:   top: 0;
1.1075.2.2  raeburn  7088: }
                   7089: 
1.1075.2.112  raeburn  7090: ol.LC_primary_menu li:hover > ul, ol.LC_primary_menu li.hover > ul {
1.1075.2.2  raeburn  7091:   display: block;
                   7092:   position: absolute;
                   7093:   margin: 0;
                   7094:   padding: 0;
1.1075.2.5  raeburn  7095:   z-index: 2;
1.1075.2.2  raeburn  7096: }
                   7097: 
                   7098: ol.LC_primary_menu li:hover li, ol.LC_primary_menu li.hover li {
1.1075.2.112  raeburn  7099: /* First Submenu -> size should be smaller than the menu title of the whole menu */
1.1075.2.2  raeburn  7100:   font-size: 90%;
1.911     bisitz   7101:   vertical-align: top;
1.1075.2.2  raeburn  7102:   float: none;
1.1075.2.5  raeburn  7103:   border-left: 1px solid black;
                   7104:   border-right: 1px solid black;
1.1075.2.112  raeburn  7105: /* A dark bottom border to visualize different menu options;
                   7106: overwritten in the create_submenu routine for the last border-bottom of the menu */
                   7107:   border-bottom: 1px solid $data_table_dark;
1.1075.2.2  raeburn  7108: }
                   7109: 
1.1075.2.112  raeburn  7110: ol.LC_primary_menu li li p:hover {
                   7111:   color:$button_hover;
                   7112:   text-decoration:none;
                   7113:   background-color:$data_table_dark;
1.1075.2.2  raeburn  7114: }
                   7115: 
                   7116: ol.LC_primary_menu li li a:hover {
                   7117:    color:$button_hover;
                   7118:    background-color:$data_table_dark;
1.693     droeschl 7119: }
                   7120: 
1.1075.2.112  raeburn  7121: /* Font-size equal to the size of the predecessors*/
                   7122: ol.LC_primary_menu li:hover li li {
                   7123:   font-size: 100%;
                   7124: }
                   7125: 
1.897     wenzelju 7126: ol.LC_primary_menu li img {
1.911     bisitz   7127:   vertical-align: bottom;
1.934     droeschl 7128:   height: 1.1em;
1.1075.2.3  raeburn  7129:   margin: 0.2em 0 0 0;
1.693     droeschl 7130: }
                   7131: 
1.897     wenzelju 7132: ol.LC_primary_menu a {
1.911     bisitz   7133:   color: RGB(80, 80, 80);
                   7134:   text-decoration: none;
1.693     droeschl 7135: }
1.795     www      7136: 
1.949     droeschl 7137: ol.LC_primary_menu a.LC_new_message {
                   7138:   font-weight:bold;
                   7139:   color: darkred;
                   7140: }
                   7141: 
1.975     raeburn  7142: ol.LC_docs_parameters {
                   7143:   margin-left: 0;
                   7144:   padding: 0;
                   7145:   list-style: none;
                   7146: }
                   7147: 
                   7148: ol.LC_docs_parameters li {
                   7149:   margin: 0;
                   7150:   padding-right: 20px;
                   7151:   display: inline;
                   7152: }
                   7153: 
1.976     raeburn  7154: ol.LC_docs_parameters li:before {
                   7155:   content: "\\002022 \\0020";
                   7156: }
                   7157: 
                   7158: li.LC_docs_parameters_title {
                   7159:   font-weight: bold;
                   7160: }
                   7161: 
                   7162: ol.LC_docs_parameters li.LC_docs_parameters_title:before {
                   7163:   content: "";
                   7164: }
                   7165: 
1.897     wenzelju 7166: ul#LC_secondary_menu {
1.1075.2.23  raeburn  7167:   clear: right;
1.911     bisitz   7168:   color: $fontmenu;
                   7169:   background: $tabbg;
                   7170:   list-style: none;
                   7171:   padding: 0;
                   7172:   margin: 0;
                   7173:   width: 100%;
1.995     raeburn  7174:   text-align: left;
1.1075.2.4  raeburn  7175:   float: left;
1.808     droeschl 7176: }
                   7177: 
1.897     wenzelju 7178: ul#LC_secondary_menu li {
1.911     bisitz   7179:   font-weight: bold;
                   7180:   line-height: 1.8em;
                   7181:   border-right: 1px solid black;
1.1075.2.4  raeburn  7182:   float: left;
                   7183: }
                   7184: 
                   7185: ul#LC_secondary_menu li.LC_hoverable:hover, ul#LC_secondary_menu li.hover {
                   7186:   background-color: $data_table_light;
                   7187: }
                   7188: 
                   7189: ul#LC_secondary_menu li a {
                   7190:   padding: 0 0.8em;
                   7191: }
                   7192: 
                   7193: ul#LC_secondary_menu li ul {
                   7194:   display: none;
                   7195: }
                   7196: 
                   7197: ul#LC_secondary_menu li:hover ul, ul#LC_secondary_menu li.hover ul {
                   7198:   display: block;
                   7199:   position: absolute;
                   7200:   margin: 0;
                   7201:   padding: 0;
                   7202:   list-style:none;
                   7203:   float: none;
                   7204:   background-color: $data_table_light;
1.1075.2.5  raeburn  7205:   z-index: 2;
1.1075.2.10  raeburn  7206:   margin-left: -1px;
1.1075.2.4  raeburn  7207: }
                   7208: 
                   7209: ul#LC_secondary_menu li ul li {
                   7210:   font-size: 90%;
                   7211:   vertical-align: top;
                   7212:   border-left: 1px solid black;
                   7213:   border-right: 1px solid black;
1.1075.2.33  raeburn  7214:   background-color: $data_table_light;
1.1075.2.4  raeburn  7215:   list-style:none;
                   7216:   float: none;
                   7217: }
                   7218: 
                   7219: ul#LC_secondary_menu li ul li:hover, ul#LC_secondary_menu li ul li.hover {
                   7220:   background-color: $data_table_dark;
1.807     droeschl 7221: }
                   7222: 
1.847     tempelho 7223: ul.LC_TabContent {
1.911     bisitz   7224:   display:block;
                   7225:   background: $sidebg;
                   7226:   border-bottom: solid 1px $lg_border_color;
                   7227:   list-style:none;
1.1020    raeburn  7228:   margin: -1px -10px 0 -10px;
1.911     bisitz   7229:   padding: 0;
1.693     droeschl 7230: }
                   7231: 
1.795     www      7232: ul.LC_TabContent li,
                   7233: ul.LC_TabContentBigger li {
1.911     bisitz   7234:   float:left;
1.741     harmsja  7235: }
1.795     www      7236: 
1.897     wenzelju 7237: ul#LC_secondary_menu li a {
1.911     bisitz   7238:   color: $fontmenu;
                   7239:   text-decoration: none;
1.693     droeschl 7240: }
1.795     www      7241: 
1.721     harmsja  7242: ul.LC_TabContent {
1.952     onken    7243:   min-height:20px;
1.721     harmsja  7244: }
1.795     www      7245: 
                   7246: ul.LC_TabContent li {
1.911     bisitz   7247:   vertical-align:middle;
1.959     onken    7248:   padding: 0 16px 0 10px;
1.911     bisitz   7249:   background-color:$tabbg;
                   7250:   border-bottom:solid 1px $lg_border_color;
1.1020    raeburn  7251:   border-left: solid 1px $font;
1.721     harmsja  7252: }
1.795     www      7253: 
1.847     tempelho 7254: ul.LC_TabContent .right {
1.911     bisitz   7255:   float:right;
1.847     tempelho 7256: }
                   7257: 
1.911     bisitz   7258: ul.LC_TabContent li a,
                   7259: ul.LC_TabContent li {
                   7260:   color:rgb(47,47,47);
                   7261:   text-decoration:none;
                   7262:   font-size:95%;
                   7263:   font-weight:bold;
1.952     onken    7264:   min-height:20px;
                   7265: }
                   7266: 
1.959     onken    7267: ul.LC_TabContent li a:hover,
                   7268: ul.LC_TabContent li a:focus {
1.952     onken    7269:   color: $button_hover;
1.959     onken    7270:   background:none;
                   7271:   outline:none;
1.952     onken    7272: }
                   7273: 
                   7274: ul.LC_TabContent li:hover {
                   7275:   color: $button_hover;
                   7276:   cursor:pointer;
1.721     harmsja  7277: }
1.795     www      7278: 
1.911     bisitz   7279: ul.LC_TabContent li.active {
1.952     onken    7280:   color: $font;
1.911     bisitz   7281:   background:#FFFFFF url(/adm/lonIcons/open.gif) no-repeat scroll right center;
1.952     onken    7282:   border-bottom:solid 1px #FFFFFF;
                   7283:   cursor: default;
1.744     ehlerst  7284: }
1.795     www      7285: 
1.959     onken    7286: ul.LC_TabContent li.active a {
                   7287:   color:$font;
                   7288:   background:#FFFFFF;
                   7289:   outline: none;
                   7290: }
1.1047    raeburn  7291: 
                   7292: ul.LC_TabContent li.goback {
                   7293:   float: left;
                   7294:   border-left: none;
                   7295: }
                   7296: 
1.870     tempelho 7297: #maincoursedoc {
1.911     bisitz   7298:   clear:both;
1.870     tempelho 7299: }
                   7300: 
                   7301: ul.LC_TabContentBigger {
1.911     bisitz   7302:   display:block;
                   7303:   list-style:none;
                   7304:   padding: 0;
1.870     tempelho 7305: }
                   7306: 
1.795     www      7307: ul.LC_TabContentBigger li {
1.911     bisitz   7308:   vertical-align:bottom;
                   7309:   height: 30px;
                   7310:   font-size:110%;
                   7311:   font-weight:bold;
                   7312:   color: #737373;
1.841     tempelho 7313: }
                   7314: 
1.957     onken    7315: ul.LC_TabContentBigger li.active {
                   7316:   position: relative;
                   7317:   top: 1px;
                   7318: }
                   7319: 
1.870     tempelho 7320: ul.LC_TabContentBigger li a {
1.911     bisitz   7321:   background:url('/adm/lonIcons/tabbgleft.gif') left bottom no-repeat;
                   7322:   height: 30px;
                   7323:   line-height: 30px;
                   7324:   text-align: center;
                   7325:   display: block;
                   7326:   text-decoration: none;
1.958     onken    7327:   outline: none;  
1.741     harmsja  7328: }
1.795     www      7329: 
1.870     tempelho 7330: ul.LC_TabContentBigger li.active a {
1.911     bisitz   7331:   background:url('/adm/lonIcons/tabbgleft.gif') left top no-repeat;
                   7332:   color:$font;
1.744     ehlerst  7333: }
1.795     www      7334: 
1.870     tempelho 7335: ul.LC_TabContentBigger li b {
1.911     bisitz   7336:   background: url('/adm/lonIcons/tabbgright.gif') no-repeat right bottom;
                   7337:   display: block;
                   7338:   float: left;
                   7339:   padding: 0 30px;
1.957     onken    7340:   border-bottom: 1px solid $lg_border_color;
1.870     tempelho 7341: }
                   7342: 
1.956     onken    7343: ul.LC_TabContentBigger li:hover b {
                   7344:   color:$button_hover;
                   7345: }
                   7346: 
1.870     tempelho 7347: ul.LC_TabContentBigger li.active b {
1.911     bisitz   7348:   background:url('/adm/lonIcons/tabbgright.gif') right top no-repeat;
                   7349:   color:$font;
1.957     onken    7350:   border: 0;
1.741     harmsja  7351: }
1.693     droeschl 7352: 
1.870     tempelho 7353: 
1.862     bisitz   7354: ul.LC_CourseBreadcrumbs {
                   7355:   background: $sidebg;
1.1020    raeburn  7356:   height: 2em;
1.862     bisitz   7357:   padding-left: 10px;
1.1020    raeburn  7358:   margin: 0;
1.862     bisitz   7359:   list-style-position: inside;
                   7360: }
                   7361: 
1.911     bisitz   7362: ol#LC_MenuBreadcrumbs,
1.862     bisitz   7363: ol#LC_PathBreadcrumbs {
1.911     bisitz   7364:   padding-left: 10px;
                   7365:   margin: 0;
1.933     droeschl 7366:   height: 2.5em;  /* equal to #LC_breadcrumbs line-height */
1.693     droeschl 7367: }
                   7368: 
1.911     bisitz   7369: ol#LC_MenuBreadcrumbs li,
                   7370: ol#LC_PathBreadcrumbs li,
1.862     bisitz   7371: ul.LC_CourseBreadcrumbs li {
1.911     bisitz   7372:   display: inline;
1.933     droeschl 7373:   white-space: normal;  
1.693     droeschl 7374: }
                   7375: 
1.823     bisitz   7376: ol#LC_MenuBreadcrumbs li a,
1.862     bisitz   7377: ul.LC_CourseBreadcrumbs li a {
1.911     bisitz   7378:   text-decoration: none;
                   7379:   font-size:90%;
1.693     droeschl 7380: }
1.795     www      7381: 
1.969     droeschl 7382: ol#LC_MenuBreadcrumbs h1 {
                   7383:   display: inline;
                   7384:   font-size: 90%;
                   7385:   line-height: 2.5em;
                   7386:   margin: 0;
                   7387:   padding: 0;
                   7388: }
                   7389: 
1.795     www      7390: ol#LC_PathBreadcrumbs li a {
1.911     bisitz   7391:   text-decoration:none;
                   7392:   font-size:100%;
                   7393:   font-weight:bold;
1.693     droeschl 7394: }
1.795     www      7395: 
1.840     bisitz   7396: .LC_Box {
1.911     bisitz   7397:   border: solid 1px $lg_border_color;
                   7398:   padding: 0 10px 10px 10px;
1.746     neumanie 7399: }
1.795     www      7400: 
1.1020    raeburn  7401: .LC_DocsBox {
                   7402:   border: solid 1px $lg_border_color;
                   7403:   padding: 0 0 10px 10px;
                   7404: }
                   7405: 
1.795     www      7406: .LC_AboutMe_Image {
1.911     bisitz   7407:   float:left;
                   7408:   margin-right:10px;
1.747     neumanie 7409: }
1.795     www      7410: 
                   7411: .LC_Clear_AboutMe_Image {
1.911     bisitz   7412:   clear:left;
1.747     neumanie 7413: }
1.795     www      7414: 
1.721     harmsja  7415: dl.LC_ListStyleClean dt {
1.911     bisitz   7416:   padding-right: 5px;
                   7417:   display: table-header-group;
1.693     droeschl 7418: }
                   7419: 
1.721     harmsja  7420: dl.LC_ListStyleClean dd {
1.911     bisitz   7421:   display: table-row;
1.693     droeschl 7422: }
                   7423: 
1.721     harmsja  7424: .LC_ListStyleClean,
                   7425: .LC_ListStyleSimple,
                   7426: .LC_ListStyleNormal,
1.795     www      7427: .LC_ListStyleSpecial {
1.911     bisitz   7428:   /* display:block; */
                   7429:   list-style-position: inside;
                   7430:   list-style-type: none;
                   7431:   overflow: hidden;
                   7432:   padding: 0;
1.693     droeschl 7433: }
                   7434: 
1.721     harmsja  7435: .LC_ListStyleSimple li,
                   7436: .LC_ListStyleSimple dd,
                   7437: .LC_ListStyleNormal li,
                   7438: .LC_ListStyleNormal dd,
                   7439: .LC_ListStyleSpecial li,
1.795     www      7440: .LC_ListStyleSpecial dd {
1.911     bisitz   7441:   margin: 0;
                   7442:   padding: 5px 5px 5px 10px;
                   7443:   clear: both;
1.693     droeschl 7444: }
                   7445: 
1.721     harmsja  7446: .LC_ListStyleClean li,
                   7447: .LC_ListStyleClean dd {
1.911     bisitz   7448:   padding-top: 0;
                   7449:   padding-bottom: 0;
1.693     droeschl 7450: }
                   7451: 
1.721     harmsja  7452: .LC_ListStyleSimple dd,
1.795     www      7453: .LC_ListStyleSimple li {
1.911     bisitz   7454:   border-bottom: solid 1px $lg_border_color;
1.693     droeschl 7455: }
                   7456: 
1.721     harmsja  7457: .LC_ListStyleSpecial li,
                   7458: .LC_ListStyleSpecial dd {
1.911     bisitz   7459:   list-style-type: none;
                   7460:   background-color: RGB(220, 220, 220);
                   7461:   margin-bottom: 4px;
1.693     droeschl 7462: }
                   7463: 
1.721     harmsja  7464: table.LC_SimpleTable {
1.911     bisitz   7465:   margin:5px;
                   7466:   border:solid 1px $lg_border_color;
1.795     www      7467: }
1.693     droeschl 7468: 
1.721     harmsja  7469: table.LC_SimpleTable tr {
1.911     bisitz   7470:   padding: 0;
                   7471:   border:solid 1px $lg_border_color;
1.693     droeschl 7472: }
1.795     www      7473: 
                   7474: table.LC_SimpleTable thead {
1.911     bisitz   7475:   background:rgb(220,220,220);
1.693     droeschl 7476: }
                   7477: 
1.721     harmsja  7478: div.LC_columnSection {
1.911     bisitz   7479:   display: block;
                   7480:   clear: both;
                   7481:   overflow: hidden;
                   7482:   margin: 0;
1.693     droeschl 7483: }
                   7484: 
1.721     harmsja  7485: div.LC_columnSection>* {
1.911     bisitz   7486:   float: left;
                   7487:   margin: 10px 20px 10px 0;
                   7488:   overflow:hidden;
1.693     droeschl 7489: }
1.721     harmsja  7490: 
1.795     www      7491: table em {
1.911     bisitz   7492:   font-weight: bold;
                   7493:   font-style: normal;
1.748     schulted 7494: }
1.795     www      7495: 
1.779     bisitz   7496: table.LC_tableBrowseRes,
1.795     www      7497: table.LC_tableOfContent {
1.911     bisitz   7498:   border:none;
                   7499:   border-spacing: 1px;
                   7500:   padding: 3px;
                   7501:   background-color: #FFFFFF;
                   7502:   font-size: 90%;
1.753     droeschl 7503: }
1.789     droeschl 7504: 
1.911     bisitz   7505: table.LC_tableOfContent {
                   7506:   border-collapse: collapse;
1.789     droeschl 7507: }
                   7508: 
1.771     droeschl 7509: table.LC_tableBrowseRes a,
1.768     schulted 7510: table.LC_tableOfContent a {
1.911     bisitz   7511:   background-color: transparent;
                   7512:   text-decoration: none;
1.753     droeschl 7513: }
                   7514: 
1.795     www      7515: table.LC_tableOfContent img {
1.911     bisitz   7516:   border: none;
                   7517:   height: 1.3em;
                   7518:   vertical-align: text-bottom;
                   7519:   margin-right: 0.3em;
1.753     droeschl 7520: }
1.757     schulted 7521: 
1.795     www      7522: a#LC_content_toolbar_firsthomework {
1.911     bisitz   7523:   background-image:url(/res/adm/pages/open-first-problem.gif);
1.774     ehlerst  7524: }
                   7525: 
1.795     www      7526: a#LC_content_toolbar_everything {
1.911     bisitz   7527:   background-image:url(/res/adm/pages/show-all.gif);
1.774     ehlerst  7528: }
                   7529: 
1.795     www      7530: a#LC_content_toolbar_uncompleted {
1.911     bisitz   7531:   background-image:url(/res/adm/pages/show-incomplete-problems.gif);
1.774     ehlerst  7532: }
                   7533: 
1.795     www      7534: #LC_content_toolbar_clearbubbles {
1.911     bisitz   7535:   background-image:url(/res/adm/pages/mark-discussionentries-read.gif);
1.774     ehlerst  7536: }
                   7537: 
1.795     www      7538: a#LC_content_toolbar_changefolder {
1.911     bisitz   7539:   background : url(/res/adm/pages/close-all-folders.gif) top center ;
1.757     schulted 7540: }
                   7541: 
1.795     www      7542: a#LC_content_toolbar_changefolder_toggled {
1.911     bisitz   7543:   background-image:url(/res/adm/pages/open-all-folders.gif);
1.757     schulted 7544: }
                   7545: 
1.1043    raeburn  7546: a#LC_content_toolbar_edittoplevel {
                   7547:   background-image:url(/res/adm/pages/edittoplevel.gif);
                   7548: }
                   7549: 
1.795     www      7550: ul#LC_toolbar li a:hover {
1.911     bisitz   7551:   background-position: bottom center;
1.757     schulted 7552: }
                   7553: 
1.795     www      7554: ul#LC_toolbar {
1.911     bisitz   7555:   padding: 0;
                   7556:   margin: 2px;
                   7557:   list-style:none;
                   7558:   position:relative;
                   7559:   background-color:white;
1.1075.2.9  raeburn  7560:   overflow: auto;
1.757     schulted 7561: }
                   7562: 
1.795     www      7563: ul#LC_toolbar li {
1.911     bisitz   7564:   border:1px solid white;
                   7565:   padding: 0;
                   7566:   margin: 0;
                   7567:   float: left;
                   7568:   display:inline;
                   7569:   vertical-align:middle;
1.1075.2.9  raeburn  7570:   white-space: nowrap;
1.911     bisitz   7571: }
1.757     schulted 7572: 
1.783     amueller 7573: 
1.795     www      7574: a.LC_toolbarItem {
1.911     bisitz   7575:   display:block;
                   7576:   padding: 0;
                   7577:   margin: 0;
                   7578:   height: 32px;
                   7579:   width: 32px;
                   7580:   color:white;
                   7581:   border: none;
                   7582:   background-repeat:no-repeat;
                   7583:   background-color:transparent;
1.757     schulted 7584: }
                   7585: 
1.915     droeschl 7586: ul.LC_funclist {
                   7587:     margin: 0;
                   7588:     padding: 0.5em 1em 0.5em 0;
                   7589: }
                   7590: 
1.933     droeschl 7591: ul.LC_funclist > li:first-child {
                   7592:     font-weight:bold; 
                   7593:     margin-left:0.8em;
                   7594: }
                   7595: 
1.915     droeschl 7596: ul.LC_funclist + ul.LC_funclist {
                   7597:     /* 
                   7598:        left border as a seperator if we have more than
                   7599:        one list 
                   7600:     */
                   7601:     border-left: 1px solid $sidebg;
                   7602:     /* 
                   7603:        this hides the left border behind the border of the 
                   7604:        outer box if element is wrapped to the next 'line' 
                   7605:     */
                   7606:     margin-left: -1px;
                   7607: }
                   7608: 
1.843     bisitz   7609: ul.LC_funclist li {
1.915     droeschl 7610:   display: inline;
1.782     bisitz   7611:   white-space: nowrap;
1.915     droeschl 7612:   margin: 0 0 0 25px;
                   7613:   line-height: 150%;
1.782     bisitz   7614: }
                   7615: 
1.974     wenzelju 7616: .LC_hidden {
                   7617:   display: none;
                   7618: }
                   7619: 
1.1030    www      7620: .LCmodal-overlay {
                   7621: 		position:fixed;
                   7622: 		top:0;
                   7623: 		right:0;
                   7624: 		bottom:0;
                   7625: 		left:0;
                   7626: 		height:100%;
                   7627: 		width:100%;
                   7628: 		margin:0;
                   7629: 		padding:0;
                   7630: 		background:#999;
                   7631: 		opacity:.75;
                   7632: 		filter: alpha(opacity=75);
                   7633: 		-moz-opacity: 0.75;
                   7634: 		z-index:101;
                   7635: }
                   7636: 
                   7637: * html .LCmodal-overlay {   
                   7638: 		position: absolute;
                   7639: 		height: expression(document.body.scrollHeight > document.body.offsetHeight ? document.body.scrollHeight : document.body.offsetHeight + 'px');
                   7640: }
                   7641: 
                   7642: .LCmodal-window {
                   7643: 		position:fixed;
                   7644: 		top:50%;
                   7645: 		left:50%;
                   7646: 		margin:0;
                   7647: 		padding:0;
                   7648: 		z-index:102;
                   7649: 	}
                   7650: 
                   7651: * html .LCmodal-window {
                   7652: 		position:absolute;
                   7653: }
                   7654: 
                   7655: .LCclose-window {
                   7656: 		position:absolute;
                   7657: 		width:32px;
                   7658: 		height:32px;
                   7659: 		right:8px;
                   7660: 		top:8px;
                   7661: 		background:transparent url('/res/adm/pages/process-stop.png') no-repeat scroll right top;
                   7662: 		text-indent:-99999px;
                   7663: 		overflow:hidden;
                   7664: 		cursor:pointer;
                   7665: }
                   7666: 
1.1075.2.17  raeburn  7667: /*
                   7668:   styles used by TTH when "Default set of options to pass to tth/m
                   7669:   when converting TeX" in course settings has been set
                   7670: 
                   7671:   option passed: -t
                   7672: 
                   7673: */
                   7674: 
                   7675: td div.comp { margin-top: -0.6ex; margin-bottom: -1ex;}
                   7676: td div.comb { margin-top: -0.6ex; margin-bottom: -.6ex;}
                   7677: td div.hrcomp { line-height: 0.9; margin-top: -0.8ex; margin-bottom: -1ex;}
                   7678: td div.norm {line-height:normal;}
                   7679: 
                   7680: /*
                   7681:   option passed -y3
                   7682: */
                   7683: 
                   7684: span.roman {font-family: serif; font-style: normal; font-weight: normal;}
                   7685: span.overacc2 {position: relative;  left: .8em; top: -1.2ex;}
                   7686: span.overacc1 {position: relative;  left: .6em; top: -1.2ex;}
                   7687: 
1.1075.2.121  raeburn  7688: #LC_minitab_header {
                   7689:   float:left;
                   7690:   width:100%;
                   7691:   background:#DAE0D2 url("/res/adm/pages/minitabmenu_bg.gif") repeat-x bottom;
                   7692:   font-size:93%;
                   7693:   line-height:normal;
                   7694:   margin: 0.5em 0 0.5em 0;
                   7695: }
                   7696: #LC_minitab_header ul {
                   7697:   margin:0;
                   7698:   padding:10px 10px 0;
                   7699:   list-style:none;
                   7700: }
                   7701: #LC_minitab_header li {
                   7702:   float:left;
                   7703:   background:url("/res/adm/pages/minitabmenu_left.gif") no-repeat left top;
                   7704:   margin:0;
                   7705:   padding:0 0 0 9px;
                   7706: }
                   7707: #LC_minitab_header a {
                   7708:   display:block;
                   7709:   background:url("/res/adm/pages/minitabmenu_right.gif") no-repeat right top;
                   7710:   padding:5px 15px 4px 6px;
                   7711: }
                   7712: #LC_minitab_header #LC_current_minitab {
                   7713:   background-image:url("/res/adm/pages/minitabmenu_left_on.gif");
                   7714: }
                   7715: #LC_minitab_header #LC_current_minitab a {
                   7716:   background-image:url("/res/adm/pages/minitabmenu_right_on.gif");
                   7717:   padding-bottom:5px;
                   7718: }
                   7719: 
                   7720: 
1.343     albertel 7721: END
                   7722: }
                   7723: 
1.306     albertel 7724: =pod
                   7725: 
                   7726: =item * &headtag()
                   7727: 
                   7728: Returns a uniform footer for LON-CAPA web pages.
                   7729: 
1.307     albertel 7730: Inputs: $title - optional title for the head
                   7731:         $head_extra - optional extra HTML to put inside the <head>
1.315     albertel 7732:         $args - optional arguments
1.319     albertel 7733:             force_register - if is true call registerurl so the remote is 
                   7734:                              informed
1.415     albertel 7735:             redirect       -> array ref of
                   7736:                                    1- seconds before redirect occurs
                   7737:                                    2- url to redirect to
                   7738:                                    3- whether the side effect should occur
1.315     albertel 7739:                            (side effect of setting 
                   7740:                                $env{'internal.head.redirect'} to the url 
                   7741:                                redirected too)
1.352     albertel 7742:             domain         -> force to color decorate a page for a specific
                   7743:                                domain
                   7744:             function       -> force usage of a specific rolish color scheme
                   7745:             bgcolor        -> override the default page bgcolor
1.460     albertel 7746:             no_auto_mt_title
                   7747:                            -> prevent &mt()ing the title arg
1.464     albertel 7748: 
1.306     albertel 7749: =cut
                   7750: 
                   7751: sub headtag {
1.313     albertel 7752:     my ($title,$head_extra,$args) = @_;
1.306     albertel 7753:     
1.363     albertel 7754:     my $function = $args->{'function'} || &get_users_function();
                   7755:     my $domain   = $args->{'domain'}   || &determinedomain();
                   7756:     my $bgcolor  = $args->{'bgcolor'}  || &designparm($function.'.pgbg',$domain);
1.1075.2.52  raeburn  7757:     my $httphost = $args->{'use_absolute'};
1.418     albertel 7758:     my $url = join(':',$env{'user.name'},$env{'user.domain'},
1.458     albertel 7759: 		   $Apache::lonnet::perlvar{'lonVersion'},
1.531     albertel 7760: 		   #time(),
1.418     albertel 7761: 		   $env{'environment.color.timestamp'},
1.363     albertel 7762: 		   $function,$domain,$bgcolor);
                   7763: 
1.369     www      7764:     $url = '/adm/css/'.&escape($url).'.css';
1.363     albertel 7765: 
1.308     albertel 7766:     my $result =
                   7767: 	'<head>'.
1.1075.2.56  raeburn  7768: 	&font_settings($args);
1.319     albertel 7769: 
1.1075.2.72  raeburn  7770:     my $inhibitprint;
                   7771:     if ($args->{'print_suppress'}) {
                   7772:         $inhibitprint = &print_suppression();
                   7773:     }
1.1064    raeburn  7774: 
1.461     albertel 7775:     if (!$args->{'frameset'}) {
                   7776: 	$result .= &Apache::lonhtmlcommon::htmlareaheaders();
                   7777:     }
1.1075.2.12  raeburn  7778:     if ($args->{'force_register'}) {
                   7779:         $result .= &Apache::lonmenu::registerurl(1);
1.319     albertel 7780:     }
1.436     albertel 7781:     if (!$args->{'no_nav_bar'} 
                   7782: 	&& !$args->{'only_body'}
                   7783: 	&& !$args->{'frameset'}) {
1.1075.2.52  raeburn  7784: 	$result .= &help_menu_js($httphost);
1.1032    www      7785:         $result.=&modal_window();
1.1038    www      7786:         $result.=&togglebox_script();
1.1034    www      7787:         $result.=&wishlist_window();
1.1041    www      7788:         $result.=&LCprogressbarUpdate_script();
1.1034    www      7789:     } else {
                   7790:         if ($args->{'add_modal'}) {
                   7791:            $result.=&modal_window();
                   7792:         }
                   7793:         if ($args->{'add_wishlist'}) {
                   7794:            $result.=&wishlist_window();
                   7795:         }
1.1038    www      7796:         if ($args->{'add_togglebox'}) {
                   7797:            $result.=&togglebox_script();
                   7798:         }
1.1041    www      7799:         if ($args->{'add_progressbar'}) {
                   7800:            $result.=&LCprogressbarUpdate_script();
                   7801:         }
1.436     albertel 7802:     }
1.314     albertel 7803:     if (ref($args->{'redirect'})) {
1.414     albertel 7804: 	my ($time,$url,$inhibit_continue) = @{$args->{'redirect'}};
1.315     albertel 7805: 	$url = &Apache::lonenc::check_encrypt($url);
1.414     albertel 7806: 	if (!$inhibit_continue) {
                   7807: 	    $env{'internal.head.redirect'} = $url;
                   7808: 	}
1.313     albertel 7809: 	$result.=<<ADDMETA
                   7810: <meta http-equiv="pragma" content="no-cache" />
1.344     albertel 7811: <meta http-equiv="Refresh" content="$time; url=$url" />
1.313     albertel 7812: ADDMETA
1.1075.2.89  raeburn  7813:     } else {
                   7814:         unless (($args->{'frameset'}) || ($args->{'js_ready'}) || ($args->{'only_body'}) || ($args->{'no_nav_bar'})) {
                   7815:             my $requrl = $env{'request.uri'};
                   7816:             if ($requrl eq '') {
                   7817:                 $requrl = $ENV{'REQUEST_URI'};
                   7818:                 $requrl =~ s/\?.+$//;
                   7819:             }
                   7820:             unless (($requrl =~ m{^/adm/(?:switchserver|login|authenticate|logout|groupsort|cleanup|helper|slotrequest|grades)(\?|$)}) ||
                   7821:                     (($requrl =~ m{^/res/}) && (($env{'form.submitted'} eq 'scantron') ||
                   7822:                      ($env{'form.grade_symb'}) || ($Apache::lonhomework::scantronmode)))) {
                   7823:                 my $dom_in_use = $Apache::lonnet::perlvar{'lonDefDomain'};
                   7824:                 unless (&Apache::lonnet::allowed('mau',$dom_in_use)) {
                   7825:                     my %domdefs = &Apache::lonnet::get_domain_defaults($dom_in_use);
                   7826:                     if (ref($domdefs{'offloadnow'}) eq 'HASH') {
                   7827:                         my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   7828:                         if ($domdefs{'offloadnow'}{$lonhost}) {
                   7829:                             my $newserver = &Apache::lonnet::spareserver(30000,undef,1,$dom_in_use);
                   7830:                             if (($newserver) && ($newserver ne $lonhost)) {
                   7831:                                 my $numsec = 5;
                   7832:                                 my $timeout = $numsec * 1000;
                   7833:                                 my ($newurl,$locknum,%locks,$msg);
                   7834:                                 if ($env{'request.role.adv'}) {
                   7835:                                     ($locknum,%locks) = &Apache::lonnet::get_locks();
                   7836:                                 }
                   7837:                                 my $disable_submit = 0;
                   7838:                                 if ($requrl =~ /$LONCAPA::assess_re/) {
                   7839:                                     $disable_submit = 1;
                   7840:                                 }
                   7841:                                 if ($locknum) {
                   7842:                                     my @lockinfo = sort(values(%locks));
                   7843:                                     $msg = &mt('Once the following tasks are complete: ')."\\n".
                   7844:                                            join(", ",sort(values(%locks)))."\\n".
                   7845:                                            &mt('your session will be transferred to a different server, after you click "Roles".');
                   7846:                                 } else {
                   7847:                                     if (($requrl =~ m{^/res/}) && ($env{'form.submitted'} =~ /^part_/)) {
                   7848:                                         $msg = &mt('Your LON-CAPA submission has been recorded')."\\n";
                   7849:                                     }
                   7850:                                     $msg .= &mt('Your current LON-CAPA session will be transferred to a different server in [quant,_1,second].',$numsec);
                   7851:                                     $newurl = '/adm/switchserver?otherserver='.$newserver;
                   7852:                                     if (($env{'request.role'}) && ($env{'request.role'} ne 'cm')) {
                   7853:                                         $newurl .= '&role='.$env{'request.role'};
                   7854:                                     }
                   7855:                                     if ($env{'request.symb'}) {
                   7856:                                         $newurl .= '&symb='.$env{'request.symb'};
                   7857:                                     } else {
                   7858:                                         $newurl .= '&origurl='.$requrl;
                   7859:                                     }
                   7860:                                 }
1.1075.2.98  raeburn  7861:                                 &js_escape(\$msg);
1.1075.2.89  raeburn  7862:                                 $result.=<<OFFLOAD
                   7863: <meta http-equiv="pragma" content="no-cache" />
                   7864: <script type="text/javascript">
1.1075.2.92  raeburn  7865: // <![CDATA[
1.1075.2.89  raeburn  7866: function LC_Offload_Now() {
                   7867:     var dest = "$newurl";
                   7868:     if (dest != '') {
                   7869:         window.location.href="$newurl";
                   7870:     }
                   7871: }
1.1075.2.92  raeburn  7872: \$(document).ready(function () {
                   7873:     window.alert('$msg');
                   7874:     if ($disable_submit) {
1.1075.2.89  raeburn  7875:         \$(".LC_hwk_submit").prop("disabled", true);
                   7876:         \$( ".LC_textline" ).prop( "readonly", "readonly");
1.1075.2.92  raeburn  7877:     }
                   7878:     setTimeout('LC_Offload_Now()', $timeout);
                   7879: });
                   7880: // ]]>
1.1075.2.89  raeburn  7881: </script>
                   7882: OFFLOAD
                   7883:                             }
                   7884:                         }
                   7885:                     }
                   7886:                 }
                   7887:             }
                   7888:         }
1.313     albertel 7889:     }
1.306     albertel 7890:     if (!defined($title)) {
                   7891: 	$title = 'The LearningOnline Network with CAPA';
                   7892:     }
1.460     albertel 7893:     if (!$args->{'no_auto_mt_title'}) { $title = &mt($title); }
                   7894:     $result .= '<title> LON-CAPA '.$title.'</title>'
1.1075.2.61  raeburn  7895: 	.'<link rel="stylesheet" type="text/css" href="'.$url.'"';
                   7896:     if (!$args->{'frameset'}) {
                   7897:         $result .= ' /';
                   7898:     }
                   7899:     $result .= '>'
1.1064    raeburn  7900:         .$inhibitprint
1.414     albertel 7901: 	.$head_extra;
1.1075.2.108  raeburn  7902:     my $clientmobile;
                   7903:     if (($env{'user.name'} eq '') && ($env{'user.domain'} eq '')) {
                   7904:         (undef,undef,undef,undef,undef,undef,$clientmobile) = &decode_user_agent();
                   7905:     } else {
                   7906:         $clientmobile = $env{'browser.mobile'};
                   7907:     }
                   7908:     if ($clientmobile) {
1.1075.2.42  raeburn  7909:         $result .= '
                   7910: <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=0, minimum-scale=1.0, maximum-scale=1.0">
                   7911: <meta name="apple-mobile-web-app-capable" content="yes" />';
                   7912:     }
1.1075.2.126  raeburn  7913:     $result .= '<meta name="google" content="notranslate" />'."\n";
1.962     droeschl 7914:     return $result.'</head>';
1.306     albertel 7915: }
                   7916: 
                   7917: =pod
                   7918: 
1.340     albertel 7919: =item * &font_settings()
                   7920: 
                   7921: Returns neccessary <meta> to set the proper encoding
                   7922: 
1.1075.2.56  raeburn  7923: Inputs: optional reference to HASH -- $args passed to &headtag()
1.340     albertel 7924: 
                   7925: =cut
                   7926: 
                   7927: sub font_settings {
1.1075.2.56  raeburn  7928:     my ($args) = @_;
1.340     albertel 7929:     my $headerstring='';
1.1075.2.56  raeburn  7930:     if ((!$env{'browser.mathml'} && $env{'browser.unicode'}) ||
                   7931:         ((ref($args) eq 'HASH') && ($args->{'browser.unicode'}))) {
1.340     albertel 7932: 	$headerstring.=
1.1075.2.61  raeburn  7933: 	    '<meta http-equiv="Content-Type" content="text/html; charset=utf-8"';
                   7934:         if (!$args->{'frameset'}) {
                   7935:             $headerstring.= ' /';
                   7936:         }
                   7937:         $headerstring .= '>'."\n";
1.340     albertel 7938:     }
                   7939:     return $headerstring;
                   7940: }
                   7941: 
1.341     albertel 7942: =pod
                   7943: 
1.1064    raeburn  7944: =item * &print_suppression()
                   7945: 
                   7946: In course context returns css which causes the body to be blank when media="print",
                   7947: if printout generation is unavailable for the current resource.
                   7948: 
                   7949: This could be because:
                   7950: 
                   7951: (a) printstartdate is in the future
                   7952: 
                   7953: (b) printenddate is in the past
                   7954: 
                   7955: (c) there is an active exam block with "printout"
                   7956: functionality blocked
                   7957: 
                   7958: Users with pav, pfo or evb privileges are exempt.
                   7959: 
                   7960: Inputs: none
                   7961: 
                   7962: =cut
                   7963: 
                   7964: 
                   7965: sub print_suppression {
                   7966:     my $noprint;
                   7967:     if ($env{'request.course.id'}) {
                   7968:         my $scope = $env{'request.course.id'};
                   7969:         if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7970:             (&Apache::lonnet::allowed('pfo',$scope))) {
                   7971:             return;
                   7972:         }
                   7973:         if ($env{'request.course.sec'} ne '') {
                   7974:             $scope .= "/$env{'request.course.sec'}";
                   7975:             if ((&Apache::lonnet::allowed('pav',$scope)) ||
                   7976:                 (&Apache::lonnet::allowed('pfo',$scope))) {
1.1065    raeburn  7977:                 return;
1.1064    raeburn  7978:             }
                   7979:         }
                   7980:         my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   7981:         my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.73  raeburn  7982:         my $blocked = &blocking_status('printout',$cnum,$cdom,undef,1);
1.1064    raeburn  7983:         if ($blocked) {
                   7984:             my $checkrole = "cm./$cdom/$cnum";
                   7985:             if ($env{'request.course.sec'} ne '') {
                   7986:                 $checkrole .= "/$env{'request.course.sec'}";
                   7987:             }
                   7988:             unless ((&Apache::lonnet::allowed('evb',undef,undef,$checkrole)) &&
                   7989:                     ($env{'request.role'} !~ m{^st\./$cdom/$cnum})) {
                   7990:                 $noprint = 1;
                   7991:             }
                   7992:         }
                   7993:         unless ($noprint) {
                   7994:             my $symb = &Apache::lonnet::symbread();
                   7995:             if ($symb ne '') {
                   7996:                 my $navmap = Apache::lonnavmaps::navmap->new();
                   7997:                 if (ref($navmap)) {
                   7998:                     my $res = $navmap->getBySymb($symb);
                   7999:                     if (ref($res)) {
                   8000:                         if (!$res->resprintable()) {
                   8001:                             $noprint = 1;
                   8002:                         }
                   8003:                     }
                   8004:                 }
                   8005:             }
                   8006:         }
                   8007:         if ($noprint) {
                   8008:             return <<"ENDSTYLE";
                   8009: <style type="text/css" media="print">
                   8010:     body { display:none }
                   8011: </style>
                   8012: ENDSTYLE
                   8013:         }
                   8014:     }
                   8015:     return;
                   8016: }
                   8017: 
                   8018: =pod
                   8019: 
1.341     albertel 8020: =item * &xml_begin()
                   8021: 
                   8022: Returns the needed doctype and <html>
                   8023: 
                   8024: Inputs: none
                   8025: 
                   8026: =cut
                   8027: 
                   8028: sub xml_begin {
1.1075.2.61  raeburn  8029:     my ($is_frameset) = @_;
1.341     albertel 8030:     my $output='';
                   8031: 
                   8032:     if ($env{'browser.mathml'}) {
                   8033: 	$output='<?xml version="1.0"?>'
                   8034:             #.'<?xml-stylesheet type="text/css" href="/adm/MathML/mathml.css"?>'."\n"
                   8035: #            .'<!DOCTYPE html SYSTEM "/adm/MathML/mathml.dtd" '
                   8036:             
                   8037: #	    .'<!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">] >'
                   8038: 	    .'<!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">'
                   8039:             .'<html xmlns:math="http://www.w3.org/1998/Math/MathML" ' 
                   8040: 	    .'xmlns="http://www.w3.org/1999/xhtml">';
1.1075.2.61  raeburn  8041:     } elsif ($is_frameset) {
                   8042:         $output='<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Frameset//EN" "http://www.w3.org/TR/html4/frameset.dtd">'."\n".
                   8043:                 '<html>'."\n";
1.341     albertel 8044:     } else {
1.1075.2.61  raeburn  8045: 	$output='<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'."\n".
                   8046:                 '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">'."\n";
1.341     albertel 8047:     }
                   8048:     return $output;
                   8049: }
1.340     albertel 8050: 
                   8051: =pod
                   8052: 
1.306     albertel 8053: =item * &start_page()
                   8054: 
                   8055: Returns a complete <html> .. <body> section for LON-CAPA web pages.
                   8056: 
1.648     raeburn  8057: Inputs:
                   8058: 
                   8059: =over 4
                   8060: 
                   8061: $title - optional title for the page
                   8062: 
                   8063: $head_extra - optional extra HTML to incude inside the <head>
                   8064: 
                   8065: $args - additional optional args supported are:
                   8066: 
                   8067: =over 8
                   8068: 
                   8069:              only_body      -> is true will set &bodytag() onlybodytag
1.317     albertel 8070:                                     arg on
1.814     bisitz   8071:              no_nav_bar     -> is true will set &bodytag() no_nav_bar arg on
1.648     raeburn  8072:              add_entries    -> additional attributes to add to the  <body>
                   8073:              domain         -> force to color decorate a page for a 
1.317     albertel 8074:                                     specific domain
1.648     raeburn  8075:              function       -> force usage of a specific rolish color
1.317     albertel 8076:                                     scheme
1.648     raeburn  8077:              redirect       -> see &headtag()
                   8078:              bgcolor        -> override the default page bg color
                   8079:              js_ready       -> return a string ready for being used in 
1.317     albertel 8080:                                     a javascript writeln
1.648     raeburn  8081:              html_encode    -> return a string ready for being used in 
1.320     albertel 8082:                                     a html attribute
1.648     raeburn  8083:              force_register -> if is true will turn on the &bodytag()
1.317     albertel 8084:                                     $forcereg arg
1.648     raeburn  8085:              frameset       -> if true will start with a <frameset>
1.330     albertel 8086:                                     rather than <body>
1.648     raeburn  8087:              skip_phases    -> hash ref of 
1.338     albertel 8088:                                     head -> skip the <html><head> generation
                   8089:                                     body -> skip all <body> generation
1.1075.2.12  raeburn  8090:              no_inline_link -> if true and in remote mode, don't show the
                   8091:                                     'Switch To Inline Menu' link
1.648     raeburn  8092:              no_auto_mt_title -> prevent &mt()ing the title arg
1.867     kalberla 8093:              bread_crumbs ->             Array containing breadcrumbs
1.983     raeburn  8094:              bread_crumbs_component ->  if exists show it as headline else show only the breadcrumbs
1.1075.2.123  raeburn  8095:              bread_crumbs_nomenu -> if true will pass false as the value of $menulink
                   8096:                                     to lonhtmlcommon::breadcrumbs
1.1075.2.15  raeburn  8097:              group          -> includes the current group, if page is for a
                   8098:                                specific group
1.1075.2.133! raeburn  8099:              use_absolute   -> for request for external resource or syllabus, this
        !          8100:                                will contain https://<hostname> if server uses
        !          8101:                                https (as per hosts.tab), but request is for http
        !          8102:              hostname       -> hostname, originally from $r->hostname(), (optional).
1.361     albertel 8103: 
1.648     raeburn  8104: =back
1.460     albertel 8105: 
1.648     raeburn  8106: =back
1.562     albertel 8107: 
1.306     albertel 8108: =cut
                   8109: 
                   8110: sub start_page {
1.309     albertel 8111:     my ($title,$head_extra,$args) = @_;
1.318     albertel 8112:     #&Apache::lonnet::logthis("start_page ".join(':',caller(0)));
1.319     albertel 8113: 
1.315     albertel 8114:     $env{'internal.start_page'}++;
1.1075.2.15  raeburn  8115:     my ($result,@advtools);
1.964     droeschl 8116: 
1.338     albertel 8117:     if (! exists($args->{'skip_phases'}{'head'}) ) {
1.1075.2.62  raeburn  8118:         $result .= &xml_begin($args->{'frameset'}) . &headtag($title, $head_extra, $args);
1.338     albertel 8119:     }
                   8120:     
                   8121:     if (! exists($args->{'skip_phases'}{'body'}) ) {
                   8122: 	if ($args->{'frameset'}) {
                   8123: 	    my $attr_string = &make_attr_string($args->{'force_register'},
                   8124: 						$args->{'add_entries'});
                   8125: 	    $result .= "\n<frameset $attr_string>\n";
1.831     bisitz   8126:         } else {
                   8127:             $result .=
                   8128:                 &bodytag($title, 
                   8129:                          $args->{'function'},       $args->{'add_entries'},
                   8130:                          $args->{'only_body'},      $args->{'domain'},
                   8131:                          $args->{'force_register'}, $args->{'no_nav_bar'},
1.1075.2.12  raeburn  8132:                          $args->{'bgcolor'},        $args->{'no_inline_link'},
1.1075.2.15  raeburn  8133:                          $args,                     \@advtools);
1.831     bisitz   8134:         }
1.330     albertel 8135:     }
1.338     albertel 8136: 
1.315     albertel 8137:     if ($args->{'js_ready'}) {
1.713     kaisler  8138: 		$result = &js_ready($result);
1.315     albertel 8139:     }
1.320     albertel 8140:     if ($args->{'html_encode'}) {
1.713     kaisler  8141: 		$result = &html_encode($result);
                   8142:     }
                   8143: 
1.813     bisitz   8144:     # Preparation for new and consistent functionlist at top of screen
                   8145:     # if ($args->{'functionlist'}) {
                   8146:     #            $result .= &build_functionlist();
                   8147:     #}
                   8148: 
1.964     droeschl 8149:     # Don't add anything more if only_body wanted or in const space
                   8150:     return $result if    $args->{'only_body'} 
                   8151:                       || $env{'request.state'} eq 'construct';
1.813     bisitz   8152: 
                   8153:     #Breadcrumbs
1.758     kaisler  8154:     if (exists($args->{'bread_crumbs'}) or exists($args->{'bread_crumbs_component'})) {
                   8155: 		&Apache::lonhtmlcommon::clear_breadcrumbs();
                   8156: 		#if any br links exists, add them to the breadcrumbs
                   8157: 		if (exists($args->{'bread_crumbs'}) and ref($args->{'bread_crumbs'}) eq 'ARRAY') {         
                   8158: 			foreach my $crumb (@{$args->{'bread_crumbs'}}){
                   8159: 				&Apache::lonhtmlcommon::add_breadcrumb($crumb);
                   8160: 			}
                   8161: 		}
1.1075.2.19  raeburn  8162:                 # if @advtools array contains items add then to the breadcrumbs
                   8163:                 if (@advtools > 0) {
                   8164:                     &Apache::lonmenu::advtools_crumbs(@advtools);
                   8165:                 }
1.1075.2.123  raeburn  8166:                 my $menulink;
                   8167:                 # if arg: bread_crumbs_nomenu is true pass 0 as $menulink item.
                   8168:                 if (exists($args->{'bread_crumbs_nomenu'})) {
                   8169:                     $menulink = 0;
                   8170:                 } else {
                   8171:                     undef($menulink);
                   8172:                 }
1.758     kaisler  8173: 		#if bread_crumbs_component exists show it as headline else show only the breadcrumbs
                   8174: 		if(exists($args->{'bread_crumbs_component'})){
1.1075.2.123  raeburn  8175: 			$result .= &Apache::lonhtmlcommon::breadcrumbs($args->{'bread_crumbs_component'},'',$menulink);
1.758     kaisler  8176: 		}else{
1.1075.2.123  raeburn  8177: 			$result .= &Apache::lonhtmlcommon::breadcrumbs('','',$menulink);
1.758     kaisler  8178: 		}
1.1075.2.24  raeburn  8179:     } elsif (($env{'environment.remote'} eq 'on') &&
                   8180:              ($env{'form.inhibitmenu'} ne 'yes') &&
                   8181:              ($env{'request.noversionuri'} =~ m{^/res/}) &&
                   8182:              ($env{'request.noversionuri'} !~ m{^/res/adm/pages/})) {
1.1075.2.21  raeburn  8183:         $result .= '<div style="padding:0;margin:0;clear:both"><hr /></div>';
1.320     albertel 8184:     }
1.315     albertel 8185:     return $result;
1.306     albertel 8186: }
                   8187: 
                   8188: sub end_page {
1.315     albertel 8189:     my ($args) = @_;
                   8190:     $env{'internal.end_page'}++;
1.330     albertel 8191:     my $result;
1.335     albertel 8192:     if ($args->{'discussion'}) {
                   8193: 	my ($target,$parser);
                   8194: 	if (ref($args->{'discussion'})) {
                   8195: 	    ($target,$parser) =($args->{'discussion'}{'target'},
                   8196: 				$args->{'discussion'}{'parser'});
                   8197: 	}
                   8198: 	$result .= &Apache::lonxml::xmlend($target,$parser);
                   8199:     }
1.330     albertel 8200:     if ($args->{'frameset'}) {
                   8201: 	$result .= '</frameset>';
                   8202:     } else {
1.635     raeburn  8203: 	$result .= &endbodytag($args);
1.330     albertel 8204:     }
1.1075.2.6  raeburn  8205:     unless ($args->{'notbody'}) {
                   8206:         $result .= "\n</html>";
                   8207:     }
1.330     albertel 8208: 
1.315     albertel 8209:     if ($args->{'js_ready'}) {
1.317     albertel 8210: 	$result = &js_ready($result);
1.315     albertel 8211:     }
1.335     albertel 8212: 
1.320     albertel 8213:     if ($args->{'html_encode'}) {
                   8214: 	$result = &html_encode($result);
                   8215:     }
1.335     albertel 8216: 
1.315     albertel 8217:     return $result;
                   8218: }
                   8219: 
1.1034    www      8220: sub wishlist_window {
                   8221:     return(<<'ENDWISHLIST');
1.1046    raeburn  8222: <script type="text/javascript">
1.1034    www      8223: // <![CDATA[
                   8224: // <!-- BEGIN LON-CAPA Internal
                   8225: function set_wishlistlink(title, path) {
                   8226:     if (!title) {
                   8227:         title = document.title;
                   8228:         title = title.replace(/^LON-CAPA /,'');
                   8229:     }
1.1075.2.65  raeburn  8230:     title = encodeURIComponent(title);
1.1075.2.83  raeburn  8231:     title = title.replace("'","\\\'");
1.1034    www      8232:     if (!path) {
                   8233:         path = location.pathname;
                   8234:     }
1.1075.2.65  raeburn  8235:     path = encodeURIComponent(path);
1.1075.2.83  raeburn  8236:     path = path.replace("'","\\\'");
1.1034    www      8237:     Win = window.open('/adm/wishlist?mode=newLink&setTitle='+title+'&setPath='+path,
                   8238:                       'wishlistNewLink','width=560,height=350,scrollbars=0');
                   8239: }
                   8240: // END LON-CAPA Internal -->
                   8241: // ]]>
                   8242: </script>
                   8243: ENDWISHLIST
                   8244: }
                   8245: 
1.1030    www      8246: sub modal_window {
                   8247:     return(<<'ENDMODAL');
1.1046    raeburn  8248: <script type="text/javascript">
1.1030    www      8249: // <![CDATA[
                   8250: // <!-- BEGIN LON-CAPA Internal
                   8251: var modalWindow = {
                   8252: 	parent:"body",
                   8253: 	windowId:null,
                   8254: 	content:null,
                   8255: 	width:null,
                   8256: 	height:null,
                   8257: 	close:function()
                   8258: 	{
                   8259: 	        $(".LCmodal-window").remove();
                   8260: 	        $(".LCmodal-overlay").remove();
                   8261: 	},
                   8262: 	open:function()
                   8263: 	{
                   8264: 		var modal = "";
                   8265: 		modal += "<div class=\"LCmodal-overlay\"></div>";
                   8266: 		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;\">";
                   8267: 		modal += this.content;
                   8268: 		modal += "</div>";	
                   8269: 
                   8270: 		$(this.parent).append(modal);
                   8271: 
                   8272: 		$(".LCmodal-window").append("<a class=\"LCclose-window\"></a>");
                   8273: 		$(".LCclose-window").click(function(){modalWindow.close();});
                   8274: 		$(".LCmodal-overlay").click(function(){modalWindow.close();});
                   8275: 	}
                   8276: };
1.1075.2.42  raeburn  8277: 	var openMyModal = function(source,width,height,scrolling,transparency,style)
1.1030    www      8278: 	{
1.1075.2.119  raeburn  8279:                 source = source.replace(/'/g,"&#39;");
1.1030    www      8280: 		modalWindow.windowId = "myModal";
                   8281: 		modalWindow.width = width;
                   8282: 		modalWindow.height = height;
1.1075.2.80  raeburn  8283: 		modalWindow.content = "<iframe width='"+width+"' height='"+height+"' frameborder='0' scrolling='"+scrolling+"' allowtransparency='"+transparency+"' src='" + source + "' style='"+style+"'></iframe>";
1.1030    www      8284: 		modalWindow.open();
1.1075.2.87  raeburn  8285: 	};
1.1030    www      8286: // END LON-CAPA Internal -->
                   8287: // ]]>
                   8288: </script>
                   8289: ENDMODAL
                   8290: }
                   8291: 
                   8292: sub modal_link {
1.1075.2.42  raeburn  8293:     my ($link,$linktext,$width,$height,$target,$scrolling,$title,$transparency,$style)=@_;
1.1030    www      8294:     unless ($width) { $width=480; }
                   8295:     unless ($height) { $height=400; }
1.1031    www      8296:     unless ($scrolling) { $scrolling='yes'; }
1.1075.2.42  raeburn  8297:     unless ($transparency) { $transparency='true'; }
                   8298: 
1.1074    raeburn  8299:     my $target_attr;
                   8300:     if (defined($target)) {
                   8301:         $target_attr = 'target="'.$target.'"';
                   8302:     }
                   8303:     return <<"ENDLINK";
1.1075.2.42  raeburn  8304: <a href="$link" $target_attr title="$title" onclick="javascript:openMyModal('$link',$width,$height,'$scrolling','$transparency','$style'); return false;">
1.1074    raeburn  8305:            $linktext</a>
                   8306: ENDLINK
1.1030    www      8307: }
                   8308: 
1.1032    www      8309: sub modal_adhoc_script {
                   8310:     my ($funcname,$width,$height,$content)=@_;
                   8311:     return (<<ENDADHOC);
1.1046    raeburn  8312: <script type="text/javascript">
1.1032    www      8313: // <![CDATA[
                   8314:         var $funcname = function()
                   8315:         {
                   8316:                 modalWindow.windowId = "myModal";
                   8317:                 modalWindow.width = $width;
                   8318:                 modalWindow.height = $height;
                   8319:                 modalWindow.content = '$content';
                   8320:                 modalWindow.open();
                   8321:         };  
                   8322: // ]]>
                   8323: </script>
                   8324: ENDADHOC
                   8325: }
                   8326: 
1.1041    www      8327: sub modal_adhoc_inner {
                   8328:     my ($funcname,$width,$height,$content)=@_;
                   8329:     my $innerwidth=$width-20;
                   8330:     $content=&js_ready(
1.1042    www      8331:                &start_page('Dialog',undef,{'only_body'=>1,'bgcolor'=>'#FFFFFF'}).
1.1075.2.42  raeburn  8332:                  &start_scrollbox($width.'px',$innerwidth.'px',$height.'px','myModal','#FFFFFF',undef,1).
                   8333:                  $content.
1.1041    www      8334:                  &end_scrollbox().
1.1075.2.42  raeburn  8335:                  &end_page()
1.1041    www      8336:              );
                   8337:     return &modal_adhoc_script($funcname,$width,$height,$content);
                   8338: }
                   8339: 
                   8340: sub modal_adhoc_window {
                   8341:     my ($funcname,$width,$height,$content,$linktext)=@_;
                   8342:     return &modal_adhoc_inner($funcname,$width,$height,$content).
                   8343:            "<a href=\"javascript:$funcname();void(0);\">".$linktext."</a>";
                   8344: }
                   8345: 
                   8346: sub modal_adhoc_launch {
                   8347:     my ($funcname,$width,$height,$content)=@_;
                   8348:     return &modal_adhoc_inner($funcname,$width,$height,$content).(<<ENDLAUNCH);
                   8349: <script type="text/javascript">
                   8350: // <![CDATA[
                   8351: $funcname();
                   8352: // ]]>
                   8353: </script>
                   8354: ENDLAUNCH
                   8355: }
                   8356: 
                   8357: sub modal_adhoc_close {
                   8358:     return (<<ENDCLOSE);
                   8359: <script type="text/javascript">
                   8360: // <![CDATA[
                   8361: modalWindow.close();
                   8362: // ]]>
                   8363: </script>
                   8364: ENDCLOSE
                   8365: }
                   8366: 
1.1038    www      8367: sub togglebox_script {
                   8368:    return(<<ENDTOGGLE);
                   8369: <script type="text/javascript"> 
                   8370: // <![CDATA[
                   8371: function LCtoggleDisplay(id,hidetext,showtext) {
                   8372:    link = document.getElementById(id + "link").childNodes[0];
                   8373:    with (document.getElementById(id).style) {
                   8374:       if (display == "none" ) {
                   8375:           display = "inline";
                   8376:           link.nodeValue = hidetext;
                   8377:         } else {
                   8378:           display = "none";
                   8379:           link.nodeValue = showtext;
                   8380:        }
                   8381:    }
                   8382: }
                   8383: // ]]>
                   8384: </script>
                   8385: ENDTOGGLE
                   8386: }
                   8387: 
1.1039    www      8388: sub start_togglebox {
                   8389:     my ($id,$heading,$headerbg,$hidetext,$showtext)=@_;
                   8390:     unless ($heading) { $heading=''; } else { $heading.=' '; }
                   8391:     unless ($showtext) { $showtext=&mt('show'); }
                   8392:     unless ($hidetext) { $hidetext=&mt('hide'); }
                   8393:     unless ($headerbg) { $headerbg='#FFFFFF'; }
                   8394:     return &start_data_table().
                   8395:            &start_data_table_header_row().
                   8396:            '<td bgcolor="'.$headerbg.'">'.$heading.
                   8397:            '[<a id="'.$id.'link" href="javascript:LCtoggleDisplay(\''.$id.'\',\''.$hidetext.'\',\''.
                   8398:            $showtext.'\')">'.$showtext.'</a>]</td>'.
                   8399:            &end_data_table_header_row().
                   8400:            '<tr id="'.$id.'" style="display:none""><td>';
                   8401: }
                   8402: 
                   8403: sub end_togglebox {
                   8404:     return '</td></tr>'.&end_data_table();
                   8405: }
                   8406: 
1.1041    www      8407: sub LCprogressbar_script {
1.1075.2.130  raeburn  8408:    my ($id,$number_to_do)=@_;
                   8409:    if ($number_to_do) {
                   8410:        return(<<ENDPROGRESS);
1.1041    www      8411: <script type="text/javascript">
                   8412: // <![CDATA[
1.1045    www      8413: \$('#progressbar$id').progressbar({
1.1041    www      8414:   value: 0,
                   8415:   change: function(event, ui) {
                   8416:     var newVal = \$(this).progressbar('option', 'value');
                   8417:     \$('.pblabel', this).text(LCprogressTxt);
                   8418:   }
                   8419: });
                   8420: // ]]>
                   8421: </script>
                   8422: ENDPROGRESS
1.1075.2.130  raeburn  8423:    } else {
                   8424:        return(<<ENDPROGRESS);
                   8425: <script type="text/javascript">
                   8426: // <![CDATA[
                   8427: \$('#progressbar$id').progressbar({
                   8428:   value: false,
                   8429:   create: function(event, ui) {
                   8430:     \$('.ui-widget-header', this).css({'background':'#F0F0F0'});
                   8431:     \$('.ui-progressbar-overlay', this).css({'margin':'0'});
                   8432:   }
                   8433: });
                   8434: // ]]>
                   8435: </script>
                   8436: ENDPROGRESS
                   8437:    }
1.1041    www      8438: }
                   8439: 
                   8440: sub LCprogressbarUpdate_script {
                   8441:    return(<<ENDPROGRESSUPDATE);
                   8442: <style type="text/css">
                   8443: .ui-progressbar { position:relative; }
1.1075.2.130  raeburn  8444: .progress-label {position: absolute; width: 100%; text-align: center; top: 1px; font-weight: bold; text-shadow: 1px 1px 0 #fff;margin: 0; line-height: 200%; }
1.1041    www      8445: .pblabel { position: absolute; width: 100%; text-align: center; line-height: 1.9em; }
                   8446: </style>
                   8447: <script type="text/javascript">
                   8448: // <![CDATA[
1.1045    www      8449: var LCprogressTxt='---';
                   8450: 
1.1075.2.130  raeburn  8451: function LCupdateProgress(percent,progresstext,id,maxnum) {
1.1041    www      8452:    LCprogressTxt=progresstext;
1.1075.2.130  raeburn  8453:    if ((maxnum == '') || (maxnum == undefined) || (maxnum == null)) {
                   8454:        \$('#progressbar'+id).find('.progress-label').text(LCprogressTxt);
                   8455:    } else if (percent === \$('#progressbar'+id).progressbar( "value" )) {
                   8456:        \$('#progressbar'+id).find('.pblabel').text(LCprogressTxt);
                   8457:    } else {
                   8458:        \$('#progressbar'+id).progressbar('value',percent);
                   8459:    }
1.1041    www      8460: }
                   8461: // ]]>
                   8462: </script>
                   8463: ENDPROGRESSUPDATE
                   8464: }
                   8465: 
1.1042    www      8466: my $LClastpercent;
1.1045    www      8467: my $LCidcnt;
                   8468: my $LCcurrentid;
1.1042    www      8469: 
1.1041    www      8470: sub LCprogressbar {
1.1075.2.130  raeburn  8471:     my ($r,$number_to_do,$preamble)=@_;
1.1042    www      8472:     $LClastpercent=0;
1.1045    www      8473:     $LCidcnt++;
                   8474:     $LCcurrentid=$$.'_'.$LCidcnt;
1.1075.2.130  raeburn  8475:     my ($starting,$content);
                   8476:     if ($number_to_do) {
                   8477:         $starting=&mt('Starting');
                   8478:         $content=(<<ENDPROGBAR);
                   8479: $preamble
1.1045    www      8480:   <div id="progressbar$LCcurrentid">
1.1041    www      8481:     <span class="pblabel">$starting</span>
                   8482:   </div>
                   8483: ENDPROGBAR
1.1075.2.130  raeburn  8484:     } else {
                   8485:         $starting=&mt('Loading...');
                   8486:         $LClastpercent='false';
                   8487:         $content=(<<ENDPROGBAR);
                   8488: $preamble
                   8489:   <div id="progressbar$LCcurrentid">
                   8490:       <div class="progress-label">$starting</div>
                   8491:   </div>
                   8492: ENDPROGBAR
                   8493:     }
                   8494:     &r_print($r,$content.&LCprogressbar_script($LCcurrentid,$number_to_do));
1.1041    www      8495: }
                   8496: 
                   8497: sub LCprogressbarUpdate {
1.1075.2.130  raeburn  8498:     my ($r,$val,$text,$number_to_do)=@_;
                   8499:     if ($number_to_do) {
                   8500:         unless ($val) { 
                   8501:             if ($LClastpercent) {
                   8502:                 $val=$LClastpercent;
                   8503:             } else {
                   8504:                 $val=0;
                   8505:             }
                   8506:         }
                   8507:         if ($val<0) { $val=0; }
                   8508:         if ($val>100) { $val=0; }
                   8509:         $LClastpercent=$val;
                   8510:         unless ($text) { $text=$val.'%'; }
                   8511:     } else {
                   8512:         $val = 'false';
1.1042    www      8513:     }
1.1041    www      8514:     $text=&js_ready($text);
1.1044    www      8515:     &r_print($r,<<ENDUPDATE);
1.1041    www      8516: <script type="text/javascript">
                   8517: // <![CDATA[
1.1075.2.130  raeburn  8518: LCupdateProgress($val,'$text','$LCcurrentid','$number_to_do');
1.1041    www      8519: // ]]>
                   8520: </script>
                   8521: ENDUPDATE
1.1035    www      8522: }
                   8523: 
1.1042    www      8524: sub LCprogressbarClose {
                   8525:     my ($r)=@_;
                   8526:     $LClastpercent=0;
1.1044    www      8527:     &r_print($r,<<ENDCLOSE);
1.1042    www      8528: <script type="text/javascript">
                   8529: // <![CDATA[
1.1045    www      8530: \$("#progressbar$LCcurrentid").hide('slow'); 
1.1042    www      8531: // ]]>
                   8532: </script>
                   8533: ENDCLOSE
1.1044    www      8534: }
                   8535: 
                   8536: sub r_print {
                   8537:     my ($r,$to_print)=@_;
                   8538:     if ($r) {
                   8539:       $r->print($to_print);
                   8540:       $r->rflush();
                   8541:     } else {
                   8542:       print($to_print);
                   8543:     }
1.1042    www      8544: }
                   8545: 
1.320     albertel 8546: sub html_encode {
                   8547:     my ($result) = @_;
                   8548: 
1.322     albertel 8549:     $result = &HTML::Entities::encode($result,'<>&"');
1.320     albertel 8550:     
                   8551:     return $result;
                   8552: }
1.1044    www      8553: 
1.317     albertel 8554: sub js_ready {
                   8555:     my ($result) = @_;
                   8556: 
1.323     albertel 8557:     $result =~ s/[\n\r]/ /xmsg;
                   8558:     $result =~ s/\\/\\\\/xmsg;
                   8559:     $result =~ s/'/\\'/xmsg;
1.372     albertel 8560:     $result =~ s{</}{<\\/}xmsg;
1.317     albertel 8561:     
                   8562:     return $result;
                   8563: }
                   8564: 
1.315     albertel 8565: sub validate_page {
                   8566:     if (  exists($env{'internal.start_page'})
1.316     albertel 8567: 	  &&     $env{'internal.start_page'} > 1) {
                   8568: 	&Apache::lonnet::logthis('start_page called multiple times '.
1.318     albertel 8569: 				 $env{'internal.start_page'}.' '.
1.316     albertel 8570: 				 $ENV{'request.filename'});
1.315     albertel 8571:     }
                   8572:     if (  exists($env{'internal.end_page'})
1.316     albertel 8573: 	  &&     $env{'internal.end_page'} > 1) {
                   8574: 	&Apache::lonnet::logthis('end_page called multiple times '.
1.318     albertel 8575: 				 $env{'internal.end_page'}.' '.
1.316     albertel 8576: 				 $env{'request.filename'});
1.315     albertel 8577:     }
                   8578:     if (     exists($env{'internal.start_page'})
                   8579: 	&& ! exists($env{'internal.end_page'})) {
1.316     albertel 8580: 	&Apache::lonnet::logthis('start_page called without end_page '.
                   8581: 				 $env{'request.filename'});
1.315     albertel 8582:     }
                   8583:     if (   ! exists($env{'internal.start_page'})
                   8584: 	&&   exists($env{'internal.end_page'})) {
1.316     albertel 8585: 	&Apache::lonnet::logthis('end_page called without start_page'.
                   8586: 				 $env{'request.filename'});
1.315     albertel 8587:     }
1.306     albertel 8588: }
1.315     albertel 8589: 
1.996     www      8590: 
                   8591: sub start_scrollbox {
1.1075.2.56  raeburn  8592:     my ($outerwidth,$width,$height,$id,$bgcolor,$cursor,$needjsready) = @_;
1.998     raeburn  8593:     unless ($outerwidth) { $outerwidth='520px'; }
                   8594:     unless ($width) { $width='500px'; }
                   8595:     unless ($height) { $height='200px'; }
1.1075    raeburn  8596:     my ($table_id,$div_id,$tdcol);
1.1018    raeburn  8597:     if ($id ne '') {
1.1075.2.42  raeburn  8598:         $table_id = ' id="table_'.$id.'"';
                   8599:         $div_id = ' id="div_'.$id.'"';
1.1018    raeburn  8600:     }
1.1075    raeburn  8601:     if ($bgcolor ne '') {
                   8602:         $tdcol = "background-color: $bgcolor;";
                   8603:     }
1.1075.2.42  raeburn  8604:     my $nicescroll_js;
                   8605:     if ($env{'browser.mobile'}) {
                   8606:         $nicescroll_js = &nicescroll_javascript('div_'.$id,$cursor,$needjsready);
                   8607:     }
1.1075    raeburn  8608:     return <<"END";
1.1075.2.42  raeburn  8609: $nicescroll_js
                   8610: 
                   8611: <table style="width: $outerwidth; border: 1px solid none;"$table_id><tr><td style="width: $width;$tdcol">
1.1075.2.56  raeburn  8612: <div style="overflow:auto; width:$width; height:$height;"$div_id>
1.1075    raeburn  8613: END
1.996     www      8614: }
                   8615: 
                   8616: sub end_scrollbox {
1.1036    www      8617:     return '</div></td></tr></table>';
1.996     www      8618: }
                   8619: 
1.1075.2.42  raeburn  8620: sub nicescroll_javascript {
                   8621:     my ($id,$cursor,$needjsready,$framecheck,$location) = @_;
                   8622:     my %options;
                   8623:     if (ref($cursor) eq 'HASH') {
                   8624:         %options = %{$cursor};
                   8625:     }
                   8626:     unless ($options{'railalign'} =~ /^left|right$/) {
                   8627:         $options{'railalign'} = 'left';
                   8628:     }
                   8629:     unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8630:         my $function  = &get_users_function();
                   8631:         $options{'cursorcolor'} = &designparm($function.'.sidebg',$env{'request.role.domain'});
                   8632:         unless ($options{'cursorcolor'} =~ /^\#\w+$/) {
                   8633:             $options{'cursorcolor'} = '#00F';
                   8634:         }
                   8635:     }
                   8636:     if ($options{'cursoropacity'} =~ /^[\d.]+$/) {
                   8637:         unless ($options{'cursoropacity'} >= 0.0 && $options{'cursoropacity'} <=1.0) {
                   8638:             $options{'cursoropacity'}='1.0';
                   8639:         }
                   8640:     } else {
                   8641:         $options{'cursoropacity'}='1.0';
                   8642:     }
                   8643:     if ($options{'cursorfixedheight'} eq 'none') {
                   8644:         delete($options{'cursorfixedheight'});
                   8645:     } else {
                   8646:         unless ($options{'cursorfixedheight'} =~ /^\d+$/) { $options{'cursorfixedheight'}='50'; }
                   8647:     }
                   8648:     unless ($options{'railoffset'} =~ /^{[\w\:\d\-,]+}$/) {
                   8649:         delete($options{'railoffset'});
                   8650:     }
                   8651:     my @niceoptions;
                   8652:     while (my($key,$value) = each(%options)) {
                   8653:         if ($value =~ /^\{.+\}$/) {
                   8654:             push(@niceoptions,$key.':'.$value);
                   8655:         } else {
                   8656:             push(@niceoptions,$key.':"'.$value.'"');
                   8657:         }
                   8658:     }
                   8659:     my $nicescroll_js = '
                   8660: $(document).ready(
                   8661:       function() {
                   8662:           $("#'.$id.'").niceScroll({'.join(',',@niceoptions).'});
                   8663:       }
                   8664: );
                   8665: ';
                   8666:     if ($framecheck) {
                   8667:         $nicescroll_js .= '
                   8668: function expand_div(caller) {
                   8669:     if (top === self) {
                   8670:         document.getElementById("'.$id.'").style.width = "auto";
                   8671:         document.getElementById("'.$id.'").style.height = "auto";
                   8672:     } else {
                   8673:         try {
                   8674:             if (parent.frames) {
                   8675:                 if (parent.frames.length > 1) {
                   8676:                     var framesrc = parent.frames[1].location.href;
                   8677:                     var currsrc = framesrc.replace(/\#.*$/,"");
                   8678:                     if ((caller == "search") || (currsrc == "'.$location.'")) {
                   8679:                         document.getElementById("'.$id.'").style.width = "auto";
                   8680:                         document.getElementById("'.$id.'").style.height = "auto";
                   8681:                     }
                   8682:                 }
                   8683:             }
                   8684:         } catch (e) {
                   8685:             return;
                   8686:         }
                   8687:     }
                   8688:     return;
                   8689: }
                   8690: ';
                   8691:     }
                   8692:     if ($needjsready) {
                   8693:         $nicescroll_js = '
                   8694: <script type="text/javascript">'."\n".$nicescroll_js."\n</script>\n";
                   8695:     } else {
                   8696:         $nicescroll_js = &Apache::lonhtmlcommon::scripttag($nicescroll_js);
                   8697:     }
                   8698:     return $nicescroll_js;
                   8699: }
                   8700: 
1.318     albertel 8701: sub simple_error_page {
1.1075.2.49  raeburn  8702:     my ($r,$title,$msg,$args) = @_;
                   8703:     if (ref($args) eq 'HASH') {
                   8704:         if (!$args->{'no_auto_mt_msg'}) { $msg = &mt($msg); }
                   8705:     } else {
                   8706:         $msg = &mt($msg);
                   8707:     }
                   8708: 
1.318     albertel 8709:     my $page =
                   8710: 	&Apache::loncommon::start_page($title).
1.1075.2.49  raeburn  8711: 	'<p class="LC_error">'.$msg.'</p>'.
1.318     albertel 8712: 	&Apache::loncommon::end_page();
                   8713:     if (ref($r)) {
                   8714: 	$r->print($page);
1.327     albertel 8715: 	return;
1.318     albertel 8716:     }
                   8717:     return $page;
                   8718: }
1.347     albertel 8719: 
                   8720: {
1.610     albertel 8721:     my @row_count;
1.961     onken    8722: 
                   8723:     sub start_data_table_count {
                   8724:         unshift(@row_count, 0);
                   8725:         return;
                   8726:     }
                   8727: 
                   8728:     sub end_data_table_count {
                   8729:         shift(@row_count);
                   8730:         return;
                   8731:     }
                   8732: 
1.347     albertel 8733:     sub start_data_table {
1.1018    raeburn  8734: 	my ($add_class,$id) = @_;
1.422     albertel 8735: 	my $css_class = (join(' ','LC_data_table',$add_class));
1.1018    raeburn  8736:         my $table_id;
                   8737:         if (defined($id)) {
                   8738:             $table_id = ' id="'.$id.'"';
                   8739:         }
1.961     onken    8740: 	&start_data_table_count();
1.1018    raeburn  8741: 	return '<table class="'.$css_class.'"'.$table_id.'>'."\n";
1.347     albertel 8742:     }
                   8743: 
                   8744:     sub end_data_table {
1.961     onken    8745: 	&end_data_table_count();
1.389     albertel 8746: 	return '</table>'."\n";;
1.347     albertel 8747:     }
                   8748: 
                   8749:     sub start_data_table_row {
1.974     wenzelju 8750: 	my ($add_class, $id) = @_;
1.610     albertel 8751: 	$row_count[0]++;
                   8752: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.900     bisitz   8753: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
1.974     wenzelju 8754:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8755:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.347     albertel 8756:     }
1.471     banghart 8757:     
                   8758:     sub continue_data_table_row {
1.974     wenzelju 8759: 	my ($add_class, $id) = @_;
1.610     albertel 8760: 	my $css_class = ($row_count[0] % 2)?'LC_odd_row':'LC_even_row';
1.974     wenzelju 8761: 	$css_class = (join(' ',$css_class,$add_class)) unless ($add_class eq '');
                   8762:         $id = (' id="'.$id.'"') unless ($id eq '');
                   8763:         return  '<tr class="'.$css_class.'"'.$id.'>'."\n";
1.471     banghart 8764:     }
1.347     albertel 8765: 
                   8766:     sub end_data_table_row {
1.389     albertel 8767: 	return '</tr>'."\n";;
1.347     albertel 8768:     }
1.367     www      8769: 
1.421     albertel 8770:     sub start_data_table_empty_row {
1.707     bisitz   8771: #	$row_count[0]++;
1.421     albertel 8772: 	return  '<tr class="LC_empty_row" >'."\n";;
                   8773:     }
                   8774: 
                   8775:     sub end_data_table_empty_row {
                   8776: 	return '</tr>'."\n";;
                   8777:     }
                   8778: 
1.367     www      8779:     sub start_data_table_header_row {
1.389     albertel 8780: 	return  '<tr class="LC_header_row">'."\n";;
1.367     www      8781:     }
                   8782: 
                   8783:     sub end_data_table_header_row {
1.389     albertel 8784: 	return '</tr>'."\n";;
1.367     www      8785:     }
1.890     droeschl 8786: 
                   8787:     sub data_table_caption {
                   8788:         my $caption = shift;
                   8789:         return "<caption class=\"LC_caption\">$caption</caption>";
                   8790:     }
1.347     albertel 8791: }
                   8792: 
1.548     albertel 8793: =pod
                   8794: 
                   8795: =item * &inhibit_menu_check($arg)
                   8796: 
                   8797: Checks for a inhibitmenu state and generates output to preserve it
                   8798: 
                   8799: Inputs:         $arg - can be any of
                   8800:                      - undef - in which case the return value is a string 
                   8801:                                to add  into arguments list of a uri
                   8802:                      - 'input' - in which case the return value is a HTML
                   8803:                                  <form> <input> field of type hidden to
                   8804:                                  preserve the value
                   8805:                      - a url - in which case the return value is the url with
                   8806:                                the neccesary cgi args added to preserve the
                   8807:                                inhibitmenu state
                   8808:                      - a ref to a url - no return value, but the string is
                   8809:                                         updated to include the neccessary cgi
                   8810:                                         args to preserve the inhibitmenu state
                   8811: 
                   8812: =cut
                   8813: 
                   8814: sub inhibit_menu_check {
                   8815:     my ($arg) = @_;
                   8816:     &get_unprocessed_cgi($ENV{'QUERY_STRING'}, ['inhibitmenu']);
                   8817:     if ($arg eq 'input') {
                   8818: 	if ($env{'form.inhibitmenu'}) {
                   8819: 	    return '<input type="hidden" name="inhibitmenu" value="'.$env{'form.inhibitmenu'}.'" />';
                   8820: 	} else {
                   8821: 	    return
                   8822: 	}
                   8823:     }
                   8824:     if ($env{'form.inhibitmenu'}) {
                   8825: 	if (ref($arg)) {
                   8826: 	    $$arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8827: 	} elsif ($arg eq '') {
                   8828: 	    $arg .= 'inhibitmenu='.$env{'form.inhibitmenu'};
                   8829: 	} else {
                   8830: 	    $arg .= '?inhibitmenu='.$env{'form.inhibitmenu'};
                   8831: 	}
                   8832:     }
                   8833:     if (!ref($arg)) {
                   8834: 	return $arg;
                   8835:     }
                   8836: }
                   8837: 
1.251     albertel 8838: ###############################################
1.182     matthew  8839: 
                   8840: =pod
                   8841: 
1.549     albertel 8842: =back
                   8843: 
                   8844: =head1 User Information Routines
                   8845: 
                   8846: =over 4
                   8847: 
1.405     albertel 8848: =item * &get_users_function()
1.182     matthew  8849: 
                   8850: Used by &bodytag to determine the current users primary role.
                   8851: Returns either 'student','coordinator','admin', or 'author'.
                   8852: 
                   8853: =cut
                   8854: 
                   8855: ###############################################
                   8856: sub get_users_function {
1.815     tempelho 8857:     my $function = 'norole';
1.818     tempelho 8858:     if ($env{'request.role'}=~/^(st)/) {
                   8859:         $function='student';
                   8860:     }
1.907     raeburn  8861:     if ($env{'request.role'}=~/^(cc|co|in|ta|ep)/) {
1.182     matthew  8862:         $function='coordinator';
                   8863:     }
1.258     albertel 8864:     if ($env{'request.role'}=~/^(su|dc|ad|li)/) {
1.182     matthew  8865:         $function='admin';
                   8866:     }
1.826     bisitz   8867:     if (($env{'request.role'}=~/^(au|ca|aa)/) ||
1.1025    raeburn  8868:         ($ENV{'REQUEST_URI'}=~ m{/^(/priv)})) {
1.182     matthew  8869:         $function='author';
                   8870:     }
                   8871:     return $function;
1.54      www      8872: }
1.99      www      8873: 
                   8874: ###############################################
                   8875: 
1.233     raeburn  8876: =pod
                   8877: 
1.821     raeburn  8878: =item * &show_course()
                   8879: 
                   8880: Used by lonmenu.pm and lonroles.pm to determine whether to use the word
                   8881: 'Courses' or 'Roles' in inline navigation and on screen displaying user's roles.
                   8882: 
                   8883: Inputs:
                   8884: None
                   8885: 
                   8886: Outputs:
                   8887: Scalar: 1 if 'Course' to be used, 0 otherwise.
                   8888: 
                   8889: =cut
                   8890: 
                   8891: ###############################################
                   8892: sub show_course {
                   8893:     my $course = !$env{'user.adv'};
                   8894:     if (!$env{'user.adv'}) {
                   8895:         foreach my $env (keys(%env)) {
                   8896:             next if ($env !~ m/^user\.priv\./);
                   8897:             if ($env !~ m/^user\.priv\.(?:st|cm)/) {
                   8898:                 $course = 0;
                   8899:                 last;
                   8900:             }
                   8901:         }
                   8902:     }
                   8903:     return $course;
                   8904: }
                   8905: 
                   8906: ###############################################
                   8907: 
                   8908: =pod
                   8909: 
1.542     raeburn  8910: =item * &check_user_status()
1.274     raeburn  8911: 
                   8912: Determines current status of supplied role for a
                   8913: specific user. Roles can be active, previous or future.
                   8914: 
                   8915: Inputs: 
                   8916: user's domain, user's username, course's domain,
1.375     raeburn  8917: course's number, optional section ID.
1.274     raeburn  8918: 
                   8919: Outputs:
                   8920: role status: active, previous or future. 
                   8921: 
                   8922: =cut
                   8923: 
                   8924: sub check_user_status {
1.412     raeburn  8925:     my ($udom,$uname,$cdom,$crs,$role,$sec) = @_;
1.1073    raeburn  8926:     my %userinfo = &Apache::lonnet::dump('roles',$udom,$uname);
1.1075.2.85  raeburn  8927:     my @uroles = keys(%userinfo);
1.274     raeburn  8928:     my $srchstr;
                   8929:     my $active_chk = 'none';
1.412     raeburn  8930:     my $now = time;
1.274     raeburn  8931:     if (@uroles > 0) {
1.908     raeburn  8932:         if (($role eq 'cc') || ($role eq 'co') || ($sec eq '') || (!defined($sec))) {
1.274     raeburn  8933:             $srchstr = '/'.$cdom.'/'.$crs.'_'.$role;
                   8934:         } else {
1.412     raeburn  8935:             $srchstr = '/'.$cdom.'/'.$crs.'/'.$sec.'_'.$role;
                   8936:         }
                   8937:         if (grep/^\Q$srchstr\E$/,@uroles) {
1.274     raeburn  8938:             my $role_end = 0;
                   8939:             my $role_start = 0;
                   8940:             $active_chk = 'active';
1.412     raeburn  8941:             if ($userinfo{$srchstr} =~ m/^\Q$role\E_(\d+)/) {
                   8942:                 $role_end = $1;
                   8943:                 if ($userinfo{$srchstr} =~ m/^\Q$role\E_\Q$role_end\E_(\d+)$/) {
                   8944:                     $role_start = $1;
1.274     raeburn  8945:                 }
                   8946:             }
                   8947:             if ($role_start > 0) {
1.412     raeburn  8948:                 if ($now < $role_start) {
1.274     raeburn  8949:                     $active_chk = 'future';
                   8950:                 }
                   8951:             }
                   8952:             if ($role_end > 0) {
1.412     raeburn  8953:                 if ($now > $role_end) {
1.274     raeburn  8954:                     $active_chk = 'previous';
                   8955:                 }
                   8956:             }
                   8957:         }
                   8958:     }
                   8959:     return $active_chk;
                   8960: }
                   8961: 
                   8962: ###############################################
                   8963: 
                   8964: =pod
                   8965: 
1.405     albertel 8966: =item * &get_sections()
1.233     raeburn  8967: 
                   8968: Determines all the sections for a course including
                   8969: sections with students and sections containing other roles.
1.419     raeburn  8970: Incoming parameters: 
                   8971: 
                   8972: 1. domain
                   8973: 2. course number 
                   8974: 3. reference to array containing roles for which sections should 
                   8975: be gathered (optional).
                   8976: 4. reference to array containing status types for which sections 
                   8977: should be gathered (optional).
                   8978: 
                   8979: If the third argument is undefined, sections are gathered for any role. 
                   8980: If the fourth argument is undefined, sections are gathered for any status.
                   8981: Permissible values are 'active' or 'future' or 'previous'.
1.233     raeburn  8982:  
1.374     raeburn  8983: Returns section hash (keys are section IDs, values are
                   8984: number of users in each section), subject to the
1.419     raeburn  8985: optional roles filter, optional status filter 
1.233     raeburn  8986: 
                   8987: =cut
                   8988: 
                   8989: ###############################################
                   8990: sub get_sections {
1.419     raeburn  8991:     my ($cdom,$cnum,$possible_roles,$possible_status) = @_;
1.366     albertel 8992:     if (!defined($cdom) || !defined($cnum)) {
                   8993:         my $cid =  $env{'request.course.id'};
                   8994: 
                   8995: 	return if (!defined($cid));
                   8996: 
                   8997:         $cdom = $env{'course.'.$cid.'.domain'};
                   8998:         $cnum = $env{'course.'.$cid.'.num'};
                   8999:     }
                   9000: 
                   9001:     my %sectioncount;
1.419     raeburn  9002:     my $now = time;
1.240     albertel 9003: 
1.1075.2.33  raeburn  9004:     my $check_students = 1;
                   9005:     my $only_students = 0;
                   9006:     if (ref($possible_roles) eq 'ARRAY') {
                   9007:         if (grep(/^st$/,@{$possible_roles})) {
                   9008:             if (@{$possible_roles} == 1) {
                   9009:                 $only_students = 1;
                   9010:             }
                   9011:         } else {
                   9012:             $check_students = 0;
                   9013:         }
                   9014:     }
                   9015: 
                   9016:     if ($check_students) {
1.276     albertel 9017: 	my ($classlist) = &Apache::loncoursedata::get_classlist($cdom,$cnum);
1.240     albertel 9018: 	my $sec_index = &Apache::loncoursedata::CL_SECTION();
                   9019: 	my $status_index = &Apache::loncoursedata::CL_STATUS();
1.419     raeburn  9020:         my $start_index = &Apache::loncoursedata::CL_START();
                   9021:         my $end_index = &Apache::loncoursedata::CL_END();
                   9022:         my $status;
1.366     albertel 9023: 	while (my ($student,$data) = each(%$classlist)) {
1.419     raeburn  9024: 	    my ($section,$stu_status,$start,$end) = ($data->[$sec_index],
                   9025: 				                     $data->[$status_index],
                   9026:                                                      $data->[$start_index],
                   9027:                                                      $data->[$end_index]);
                   9028:             if ($stu_status eq 'Active') {
                   9029:                 $status = 'active';
                   9030:             } elsif ($end < $now) {
                   9031:                 $status = 'previous';
                   9032:             } elsif ($start > $now) {
                   9033:                 $status = 'future';
                   9034:             } 
                   9035: 	    if ($section ne '-1' && $section !~ /^\s*$/) {
                   9036:                 if ((!defined($possible_status)) || (($status ne '') && 
                   9037:                     (grep/^\Q$status\E$/,@{$possible_status}))) { 
                   9038: 		    $sectioncount{$section}++;
                   9039:                 }
1.240     albertel 9040: 	    }
                   9041: 	}
                   9042:     }
1.1075.2.33  raeburn  9043:     if ($only_students) {
                   9044:         return %sectioncount;
                   9045:     }
1.240     albertel 9046:     my %courseroles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9047:     foreach my $user (sort(keys(%courseroles))) {
                   9048: 	if ($user !~ /^(\w{2})/) { next; }
                   9049: 	my ($role) = ($user =~ /^(\w{2})/);
                   9050: 	if ($possible_roles && !(grep(/^$role$/,@$possible_roles))) { next; }
1.419     raeburn  9051: 	my ($section,$status);
1.240     albertel 9052: 	if ($role eq 'cr' &&
                   9053: 	    $user =~ m-^$role/[^/]*/[^/]*/[^/]*:[^:]*:[^:]*:(\w+)-) {
                   9054: 	    $section=$1;
                   9055: 	}
                   9056: 	if ($user =~ /^$role:[^:]*:[^:]*:(\w+)/) { $section=$1; }
                   9057: 	if (!defined($section) || $section eq '-1') { next; }
1.419     raeburn  9058:         my ($end,$start) = ($courseroles{$user} =~ /^([^:]*):([^:]*)$/);
                   9059:         if ($end == -1 && $start == -1) {
                   9060:             next; #deleted role
                   9061:         }
                   9062:         if (!defined($possible_status)) { 
                   9063:             $sectioncount{$section}++;
                   9064:         } else {
                   9065:             if ((!$end || $end >= $now) && (!$start || $start <= $now)) {
                   9066:                 $status = 'active';
                   9067:             } elsif ($end < $now) {
                   9068:                 $status = 'future';
                   9069:             } elsif ($start > $now) {
                   9070:                 $status = 'previous';
                   9071:             }
                   9072:             if (($status ne '') && (grep/^\Q$status\E$/,@{$possible_status})) {
                   9073:                 $sectioncount{$section}++;
                   9074:             }
                   9075:         }
1.233     raeburn  9076:     }
1.366     albertel 9077:     return %sectioncount;
1.233     raeburn  9078: }
                   9079: 
1.274     raeburn  9080: ###############################################
1.294     raeburn  9081: 
                   9082: =pod
1.405     albertel 9083: 
                   9084: =item * &get_course_users()
                   9085: 
1.275     raeburn  9086: Retrieves usernames:domains for users in the specified course
                   9087: with specific role(s), and access status. 
                   9088: 
                   9089: Incoming parameters:
1.277     albertel 9090: 1. course domain
                   9091: 2. course number
                   9092: 3. access status: users must have - either active, 
1.275     raeburn  9093: previous, future, or all.
1.277     albertel 9094: 4. reference to array of permissible roles
1.288     raeburn  9095: 5. reference to array of section restrictions (optional)
                   9096: 6. reference to results object (hash of hashes).
                   9097: 7. reference to optional userdata hash
1.609     raeburn  9098: 8. reference to optional statushash
1.630     raeburn  9099: 9. flag if privileged users (except those set to unhide in
                   9100:    course settings) should be excluded    
1.609     raeburn  9101: Keys of top level results hash are roles.
1.275     raeburn  9102: Keys of inner hashes are username:domain, with 
                   9103: values set to access type.
1.288     raeburn  9104: Optional userdata hash returns an array with arguments in the 
                   9105: same order as loncoursedata::get_classlist() for student data.
                   9106: 
1.609     raeburn  9107: Optional statushash returns
                   9108: 
1.288     raeburn  9109: Entries for end, start, section and status are blank because
                   9110: of the possibility of multiple values for non-student roles.
                   9111: 
1.275     raeburn  9112: =cut
1.405     albertel 9113: 
1.275     raeburn  9114: ###############################################
1.405     albertel 9115: 
1.275     raeburn  9116: sub get_course_users {
1.630     raeburn  9117:     my ($cdom,$cnum,$types,$roles,$sections,$users,$userdata,$statushash,$hidepriv) = @_;
1.288     raeburn  9118:     my %idx = ();
1.419     raeburn  9119:     my %seclists;
1.288     raeburn  9120: 
                   9121:     $idx{udom} = &Apache::loncoursedata::CL_SDOM();
                   9122:     $idx{uname} =  &Apache::loncoursedata::CL_SNAME();
                   9123:     $idx{end} = &Apache::loncoursedata::CL_END();
                   9124:     $idx{start} = &Apache::loncoursedata::CL_START();
                   9125:     $idx{id} = &Apache::loncoursedata::CL_ID();
                   9126:     $idx{section} = &Apache::loncoursedata::CL_SECTION();
                   9127:     $idx{fullname} = &Apache::loncoursedata::CL_FULLNAME();
                   9128:     $idx{status} = &Apache::loncoursedata::CL_STATUS();
                   9129: 
1.290     albertel 9130:     if (grep(/^st$/,@{$roles})) {
1.276     albertel 9131:         my ($classlist,$keylist)=&Apache::loncoursedata::get_classlist($cdom,$cnum);
1.278     raeburn  9132:         my $now = time;
1.277     albertel 9133:         foreach my $student (keys(%{$classlist})) {
1.288     raeburn  9134:             my $match = 0;
1.412     raeburn  9135:             my $secmatch = 0;
1.419     raeburn  9136:             my $section = $$classlist{$student}[$idx{section}];
1.609     raeburn  9137:             my $status = $$classlist{$student}[$idx{status}];
1.419     raeburn  9138:             if ($section eq '') {
                   9139:                 $section = 'none';
                   9140:             }
1.291     albertel 9141:             if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9142:                 if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9143:                     $secmatch = 1;
                   9144:                 } elsif ($$classlist{$student}[$idx{section}] eq '') {
1.420     albertel 9145:                     if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9146:                         $secmatch = 1;
                   9147:                     }
                   9148:                 } else {  
1.419     raeburn  9149: 		    if (grep(/^\Q$section\E$/,@{$sections})) {
1.412     raeburn  9150: 		        $secmatch = 1;
                   9151:                     }
1.290     albertel 9152: 		}
1.412     raeburn  9153:                 if (!$secmatch) {
                   9154:                     next;
                   9155:                 }
1.419     raeburn  9156:             }
1.275     raeburn  9157:             if (defined($$types{'active'})) {
1.288     raeburn  9158:                 if ($$classlist{$student}[$idx{status}] eq 'Active') {
1.275     raeburn  9159:                     push(@{$$users{st}{$student}},'active');
1.288     raeburn  9160:                     $match = 1;
1.275     raeburn  9161:                 }
                   9162:             }
                   9163:             if (defined($$types{'previous'})) {
1.609     raeburn  9164:                 if ($$classlist{$student}[$idx{status}] eq 'Expired') {
1.275     raeburn  9165:                     push(@{$$users{st}{$student}},'previous');
1.288     raeburn  9166:                     $match = 1;
1.275     raeburn  9167:                 }
                   9168:             }
                   9169:             if (defined($$types{'future'})) {
1.609     raeburn  9170:                 if ($$classlist{$student}[$idx{status}] eq 'Future') {
1.275     raeburn  9171:                     push(@{$$users{st}{$student}},'future');
1.288     raeburn  9172:                     $match = 1;
1.275     raeburn  9173:                 }
                   9174:             }
1.609     raeburn  9175:             if ($match) {
                   9176:                 push(@{$seclists{$student}},$section);
                   9177:                 if (ref($userdata) eq 'HASH') {
                   9178:                     $$userdata{$student} = $$classlist{$student};
                   9179:                 }
                   9180:                 if (ref($statushash) eq 'HASH') {
                   9181:                     $statushash->{$student}{'st'}{$section} = $status;
                   9182:                 }
1.288     raeburn  9183:             }
1.275     raeburn  9184:         }
                   9185:     }
1.412     raeburn  9186:     if ((@{$roles} > 1) || ((@{$roles} == 1) && ($$roles[0] ne "st"))) {
1.439     raeburn  9187:         my %coursepersonnel = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9188:         my $now = time;
1.609     raeburn  9189:         my %displaystatus = ( previous => 'Expired',
                   9190:                               active   => 'Active',
                   9191:                               future   => 'Future',
                   9192:                             );
1.1075.2.36  raeburn  9193:         my (%nothide,@possdoms);
1.630     raeburn  9194:         if ($hidepriv) {
                   9195:             my %coursehash=&Apache::lonnet::coursedescription($cdom.'_'.$cnum);
                   9196:             foreach my $user (split(/\s*\,\s*/,$coursehash{'nothideprivileged'})) {
                   9197:                 if ($user !~ /:/) {
                   9198:                     $nothide{join(':',split(/[\@]/,$user))}=1;
                   9199:                 } else {
                   9200:                     $nothide{$user} = 1;
                   9201:                 }
                   9202:             }
1.1075.2.36  raeburn  9203:             my @possdoms = ($cdom);
                   9204:             if ($coursehash{'checkforpriv'}) {
                   9205:                 push(@possdoms,split(/,/,$coursehash{'checkforpriv'}));
                   9206:             }
1.630     raeburn  9207:         }
1.439     raeburn  9208:         foreach my $person (sort(keys(%coursepersonnel))) {
1.288     raeburn  9209:             my $match = 0;
1.412     raeburn  9210:             my $secmatch = 0;
1.439     raeburn  9211:             my $status;
1.412     raeburn  9212:             my ($role,$user,$usec) = ($person =~ /^([^:]*):([^:]+:[^:]+):([^:]*)/);
1.275     raeburn  9213:             $user =~ s/:$//;
1.439     raeburn  9214:             my ($end,$start) = split(/:/,$coursepersonnel{$person});
                   9215:             if ($end == -1 || $start == -1) {
                   9216:                 next;
                   9217:             }
                   9218:             if (($role) && ((grep(/^\Q$role\E$/,@{$roles})) ||
                   9219:                 (grep(/^cr$/,@{$roles}) && $role =~ /^cr\//))) {
1.412     raeburn  9220:                 my ($uname,$udom) = split(/:/,$user);
                   9221:                 if ((ref($sections) eq 'ARRAY') && (@{$sections} > 0)) {
1.420     albertel 9222:                     if (grep(/^all$/,@{$sections})) {
1.412     raeburn  9223:                         $secmatch = 1;
                   9224:                     } elsif ($usec eq '') {
1.420     albertel 9225:                         if (grep(/^none$/,@{$sections})) {
1.412     raeburn  9226:                             $secmatch = 1;
                   9227:                         }
                   9228:                     } else {
                   9229:                         if (grep(/^\Q$usec\E$/,@{$sections})) {
                   9230:                             $secmatch = 1;
                   9231:                         }
                   9232:                     }
                   9233:                     if (!$secmatch) {
                   9234:                         next;
                   9235:                     }
1.288     raeburn  9236:                 }
1.419     raeburn  9237:                 if ($usec eq '') {
                   9238:                     $usec = 'none';
                   9239:                 }
1.275     raeburn  9240:                 if ($uname ne '' && $udom ne '') {
1.630     raeburn  9241:                     if ($hidepriv) {
1.1075.2.36  raeburn  9242:                         if ((&Apache::lonnet::privileged($uname,$udom,\@possdoms)) &&
1.630     raeburn  9243:                             (!$nothide{$uname.':'.$udom})) {
                   9244:                             next;
                   9245:                         }
                   9246:                     }
1.503     raeburn  9247:                     if ($end > 0 && $end < $now) {
1.439     raeburn  9248:                         $status = 'previous';
                   9249:                     } elsif ($start > $now) {
                   9250:                         $status = 'future';
                   9251:                     } else {
                   9252:                         $status = 'active';
                   9253:                     }
1.277     albertel 9254:                     foreach my $type (keys(%{$types})) { 
1.275     raeburn  9255:                         if ($status eq $type) {
1.420     albertel 9256:                             if (!grep(/^\Q$type\E$/,@{$$users{$role}{$user}})) {
1.419     raeburn  9257:                                 push(@{$$users{$role}{$user}},$type);
                   9258:                             }
1.288     raeburn  9259:                             $match = 1;
                   9260:                         }
                   9261:                     }
1.419     raeburn  9262:                     if (($match) && (ref($userdata) eq 'HASH')) {
                   9263:                         if (!exists($$userdata{$uname.':'.$udom})) {
                   9264: 			    &get_user_info($udom,$uname,\%idx,$userdata);
                   9265:                         }
1.420     albertel 9266:                         if (!grep(/^\Q$usec\E$/,@{$seclists{$uname.':'.$udom}})) {
1.419     raeburn  9267:                             push(@{$seclists{$uname.':'.$udom}},$usec);
                   9268:                         }
1.609     raeburn  9269:                         if (ref($statushash) eq 'HASH') {
                   9270:                             $statushash->{$uname.':'.$udom}{$role}{$usec} = $displaystatus{$status};
                   9271:                         }
1.275     raeburn  9272:                     }
                   9273:                 }
                   9274:             }
                   9275:         }
1.290     albertel 9276:         if (grep(/^ow$/,@{$roles})) {
1.279     raeburn  9277:             if ((defined($cdom)) && (defined($cnum))) {
                   9278:                 my %csettings = &Apache::lonnet::get('environment',['internal.courseowner'],$cdom,$cnum);
                   9279:                 if ( defined($csettings{'internal.courseowner'}) ) {
                   9280:                     my $owner = $csettings{'internal.courseowner'};
1.609     raeburn  9281:                     next if ($owner eq '');
                   9282:                     my ($ownername,$ownerdom);
                   9283:                     if ($owner =~ /^([^:]+):([^:]+)$/) {
                   9284:                         $ownername = $1;
                   9285:                         $ownerdom = $2;
                   9286:                     } else {
                   9287:                         $ownername = $owner;
                   9288:                         $ownerdom = $cdom;
                   9289:                         $owner = $ownername.':'.$ownerdom;
1.439     raeburn  9290:                     }
                   9291:                     @{$$users{'ow'}{$owner}} = 'any';
1.290     albertel 9292:                     if (defined($userdata) && 
1.609     raeburn  9293: 			!exists($$userdata{$owner})) {
                   9294: 			&get_user_info($ownerdom,$ownername,\%idx,$userdata);
                   9295:                         if (!grep(/^none$/,@{$seclists{$owner}})) {
                   9296:                             push(@{$seclists{$owner}},'none');
                   9297:                         }
                   9298:                         if (ref($statushash) eq 'HASH') {
                   9299:                             $statushash->{$owner}{'ow'}{'none'} = 'Any';
1.419     raeburn  9300:                         }
1.290     albertel 9301: 		    }
1.279     raeburn  9302:                 }
                   9303:             }
                   9304:         }
1.419     raeburn  9305:         foreach my $user (keys(%seclists)) {
                   9306:             @{$seclists{$user}} = (sort {$a <=> $b} @{$seclists{$user}});
                   9307:             $$userdata{$user}[$idx{section}] = join(',',@{$seclists{$user}});
                   9308:         }
1.275     raeburn  9309:     }
                   9310:     return;
                   9311: }
                   9312: 
1.288     raeburn  9313: sub get_user_info {
                   9314:     my ($udom,$uname,$idx,$userdata) = @_;
1.289     albertel 9315:     $$userdata{$uname.':'.$udom}[$$idx{fullname}] = 
                   9316: 	&plainname($uname,$udom,'lastname');
1.291     albertel 9317:     $$userdata{$uname.':'.$udom}[$$idx{uname}] = $uname;
1.297     raeburn  9318:     $$userdata{$uname.':'.$udom}[$$idx{udom}] = $udom;
1.609     raeburn  9319:     my %idhash =  &Apache::lonnet::idrget($udom,($uname));
                   9320:     $$userdata{$uname.':'.$udom}[$$idx{id}] = $idhash{$uname}; 
1.288     raeburn  9321:     return;
                   9322: }
1.275     raeburn  9323: 
1.472     raeburn  9324: ###############################################
                   9325: 
                   9326: =pod
                   9327: 
                   9328: =item * &get_user_quota()
                   9329: 
1.1075.2.41  raeburn  9330: Retrieves quota assigned for storage of user files.
                   9331: Default is to report quota for portfolio files.
1.472     raeburn  9332: 
                   9333: Incoming parameters:
                   9334: 1. user's username
                   9335: 2. user's domain
1.1075.2.41  raeburn  9336: 3. quota name - portfolio, author, or course
                   9337:    (if no quota name provided, defaults to portfolio).
1.1075.2.59  raeburn  9338: 4. crstype - official, unofficial, textbook or community, if quota name is
1.1075.2.42  raeburn  9339:    course
1.472     raeburn  9340: 
                   9341: Returns:
1.1075.2.58  raeburn  9342: 1. Disk quota (in MB) assigned to student.
1.536     raeburn  9343: 2. (Optional) Type of setting: custom or default
                   9344:    (individually assigned or default for user's 
                   9345:    institutional status).
                   9346: 3. (Optional) - User's institutional status (e.g., faculty, staff
                   9347:    or student - types as defined in localenroll::inst_usertypes 
                   9348:    for user's domain, which determines default quota for user.
                   9349: 4. (Optional) - Default quota which would apply to the user.
1.472     raeburn  9350: 
                   9351: If a value has been stored in the user's environment, 
1.536     raeburn  9352: it will return that, otherwise it returns the maximal default
1.1075.2.41  raeburn  9353: defined for the user's institutional status(es) in the domain.
1.472     raeburn  9354: 
                   9355: =cut
                   9356: 
                   9357: ###############################################
                   9358: 
                   9359: 
                   9360: sub get_user_quota {
1.1075.2.42  raeburn  9361:     my ($uname,$udom,$quotaname,$crstype) = @_;
1.536     raeburn  9362:     my ($quota,$quotatype,$settingstatus,$defquota);
1.472     raeburn  9363:     if (!defined($udom)) {
                   9364:         $udom = $env{'user.domain'};
                   9365:     }
                   9366:     if (!defined($uname)) {
                   9367:         $uname = $env{'user.name'};
                   9368:     }
                   9369:     if (($udom eq '' || $uname eq '') ||
                   9370:         ($udom eq 'public') && ($uname eq 'public')) {
                   9371:         $quota = 0;
1.536     raeburn  9372:         $quotatype = 'default';
                   9373:         $defquota = 0; 
1.472     raeburn  9374:     } else {
1.536     raeburn  9375:         my $inststatus;
1.1075.2.41  raeburn  9376:         if ($quotaname eq 'course') {
                   9377:             if (($env{'course.'.$udom.'_'.$uname.'.num'} eq $uname) &&
                   9378:                 ($env{'course.'.$udom.'_'.$uname.'.domain'} eq $udom)) {
                   9379:                 $quota = $env{'course.'.$udom.'_'.$uname.'.internal.uploadquota'};
                   9380:             } else {
                   9381:                 my %cenv = &Apache::lonnet::coursedescription("$udom/$uname");
                   9382:                 $quota = $cenv{'internal.uploadquota'};
                   9383:             }
1.536     raeburn  9384:         } else {
1.1075.2.41  raeburn  9385:             if ($udom eq $env{'user.domain'} && $uname eq $env{'user.name'}) {
                   9386:                 if ($quotaname eq 'author') {
                   9387:                     $quota = $env{'environment.authorquota'};
                   9388:                 } else {
                   9389:                     $quota = $env{'environment.portfolioquota'};
                   9390:                 }
                   9391:                 $inststatus = $env{'environment.inststatus'};
                   9392:             } else {
                   9393:                 my %userenv = 
                   9394:                     &Apache::lonnet::get('environment',['portfolioquota',
                   9395:                                          'authorquota','inststatus'],$udom,$uname);
                   9396:                 my ($tmp) = keys(%userenv);
                   9397:                 if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   9398:                     if ($quotaname eq 'author') {
                   9399:                         $quota = $userenv{'authorquota'};
                   9400:                     } else {
                   9401:                         $quota = $userenv{'portfolioquota'};
                   9402:                     }
                   9403:                     $inststatus = $userenv{'inststatus'};
                   9404:                 } else {
                   9405:                     undef(%userenv);
                   9406:                 }
                   9407:             }
                   9408:         }
                   9409:         if ($quota eq '' || wantarray) {
                   9410:             if ($quotaname eq 'course') {
                   9411:                 my %domdefs = &Apache::lonnet::get_domain_defaults($udom);
1.1075.2.59  raeburn  9412:                 if (($crstype eq 'official') || ($crstype eq 'unofficial') ||
                   9413:                     ($crstype eq 'community') || ($crstype eq 'textbook')) {
1.1075.2.42  raeburn  9414:                     $defquota = $domdefs{$crstype.'quota'};
                   9415:                 }
                   9416:                 if ($defquota eq '') {
                   9417:                     $defquota = 500;
                   9418:                 }
1.1075.2.41  raeburn  9419:             } else {
                   9420:                 ($defquota,$settingstatus) = &default_quota($udom,$inststatus,$quotaname);
                   9421:             }
                   9422:             if ($quota eq '') {
                   9423:                 $quota = $defquota;
                   9424:                 $quotatype = 'default';
                   9425:             } else {
                   9426:                 $quotatype = 'custom';
                   9427:             }
1.472     raeburn  9428:         }
                   9429:     }
1.536     raeburn  9430:     if (wantarray) {
                   9431:         return ($quota,$quotatype,$settingstatus,$defquota);
                   9432:     } else {
                   9433:         return $quota;
                   9434:     }
1.472     raeburn  9435: }
                   9436: 
                   9437: ###############################################
                   9438: 
                   9439: =pod
                   9440: 
                   9441: =item * &default_quota()
                   9442: 
1.536     raeburn  9443: Retrieves default quota assigned for storage of user portfolio files,
                   9444: given an (optional) user's institutional status.
1.472     raeburn  9445: 
                   9446: Incoming parameters:
1.1075.2.42  raeburn  9447: 
1.472     raeburn  9448: 1. domain
1.536     raeburn  9449: 2. (Optional) institutional status(es).  This is a : separated list of 
                   9450:    status types (e.g., faculty, staff, student etc.)
                   9451:    which apply to the user for whom the default is being retrieved.
                   9452:    If the institutional status string in undefined, the domain
1.1075.2.41  raeburn  9453:    default quota will be returned.
                   9454: 3.  quota name - portfolio, author, or course
                   9455:    (if no quota name provided, defaults to portfolio).
1.472     raeburn  9456: 
                   9457: Returns:
1.1075.2.42  raeburn  9458: 
1.1075.2.58  raeburn  9459: 1. Default disk quota (in MB) for user portfolios in the domain.
1.536     raeburn  9460: 2. (Optional) institutional type which determined the value of the
                   9461:    default quota.
1.472     raeburn  9462: 
                   9463: If a value has been stored in the domain's configuration db,
                   9464: it will return that, otherwise it returns 20 (for backwards 
                   9465: compatibility with domains which have not set up a configuration
1.1075.2.58  raeburn  9466: db file; the original statically defined portfolio quota was 20 MB). 
1.472     raeburn  9467: 
1.536     raeburn  9468: If the user's status includes multiple types (e.g., staff and student),
                   9469: the largest default quota which applies to the user determines the
                   9470: default quota returned.
                   9471: 
1.472     raeburn  9472: =cut
                   9473: 
                   9474: ###############################################
                   9475: 
                   9476: 
                   9477: sub default_quota {
1.1075.2.41  raeburn  9478:     my ($udom,$inststatus,$quotaname) = @_;
1.536     raeburn  9479:     my ($defquota,$settingstatus);
                   9480:     my %quotahash = &Apache::lonnet::get_dom('configuration',
1.622     raeburn  9481:                                             ['quotas'],$udom);
1.1075.2.41  raeburn  9482:     my $key = 'defaultquota';
                   9483:     if ($quotaname eq 'author') {
                   9484:         $key = 'authorquota';
                   9485:     }
1.622     raeburn  9486:     if (ref($quotahash{'quotas'}) eq 'HASH') {
1.536     raeburn  9487:         if ($inststatus ne '') {
1.765     raeburn  9488:             my @statuses = map { &unescape($_); } split(/:/,$inststatus);
1.536     raeburn  9489:             foreach my $item (@statuses) {
1.1075.2.41  raeburn  9490:                 if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9491:                     if ($quotahash{'quotas'}{$key}{$item} ne '') {
1.711     raeburn  9492:                         if ($defquota eq '') {
1.1075.2.41  raeburn  9493:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9494:                             $settingstatus = $item;
1.1075.2.41  raeburn  9495:                         } elsif ($quotahash{'quotas'}{$key}{$item} > $defquota) {
                   9496:                             $defquota = $quotahash{'quotas'}{$key}{$item};
1.711     raeburn  9497:                             $settingstatus = $item;
                   9498:                         }
                   9499:                     }
1.1075.2.41  raeburn  9500:                 } elsif ($key eq 'defaultquota') {
1.711     raeburn  9501:                     if ($quotahash{'quotas'}{$item} ne '') {
                   9502:                         if ($defquota eq '') {
                   9503:                             $defquota = $quotahash{'quotas'}{$item};
                   9504:                             $settingstatus = $item;
                   9505:                         } elsif ($quotahash{'quotas'}{$item} > $defquota) {
                   9506:                             $defquota = $quotahash{'quotas'}{$item};
                   9507:                             $settingstatus = $item;
                   9508:                         }
1.536     raeburn  9509:                     }
                   9510:                 }
                   9511:             }
                   9512:         }
                   9513:         if ($defquota eq '') {
1.1075.2.41  raeburn  9514:             if (ref($quotahash{'quotas'}{$key}) eq 'HASH') {
                   9515:                 $defquota = $quotahash{'quotas'}{$key}{'default'};
                   9516:             } elsif ($key eq 'defaultquota') {
1.711     raeburn  9517:                 $defquota = $quotahash{'quotas'}{'default'};
                   9518:             }
1.536     raeburn  9519:             $settingstatus = 'default';
1.1075.2.42  raeburn  9520:             if ($defquota eq '') {
                   9521:                 if ($quotaname eq 'author') {
                   9522:                     $defquota = 500;
                   9523:                 }
                   9524:             }
1.536     raeburn  9525:         }
                   9526:     } else {
                   9527:         $settingstatus = 'default';
1.1075.2.41  raeburn  9528:         if ($quotaname eq 'author') {
                   9529:             $defquota = 500;
                   9530:         } else {
                   9531:             $defquota = 20;
                   9532:         }
1.536     raeburn  9533:     }
                   9534:     if (wantarray) {
                   9535:         return ($defquota,$settingstatus);
1.472     raeburn  9536:     } else {
1.536     raeburn  9537:         return $defquota;
1.472     raeburn  9538:     }
                   9539: }
                   9540: 
1.1075.2.41  raeburn  9541: ###############################################
                   9542: 
                   9543: =pod
                   9544: 
1.1075.2.42  raeburn  9545: =item * &excess_filesize_warning()
1.1075.2.41  raeburn  9546: 
                   9547: Returns warning message if upload of file to authoring space, or copying
1.1075.2.42  raeburn  9548: of existing file within authoring space will cause quota for the authoring
                   9549: space to be exceeded.
                   9550: 
                   9551: Same, if upload of a file directly to a course/community via Course Editor
                   9552: will cause quota for uploaded content for the course to be exceeded.
1.1075.2.41  raeburn  9553: 
1.1075.2.61  raeburn  9554: Inputs: 7 
1.1075.2.42  raeburn  9555: 1. username or coursenum
1.1075.2.41  raeburn  9556: 2. domain
1.1075.2.42  raeburn  9557: 3. context ('author' or 'course')
1.1075.2.41  raeburn  9558: 4. filename of file for which action is being requested
                   9559: 5. filesize (kB) of file
                   9560: 6. action being taken: copy or upload.
1.1075.2.59  raeburn  9561: 7. quotatype (in course context -- official, unofficial, community or textbook).
1.1075.2.41  raeburn  9562: 
                   9563: Returns: 1 scalar: HTML to display containing warning if quota would be exceeded,
                   9564:          otherwise return null.
                   9565: 
1.1075.2.42  raeburn  9566: =back
                   9567: 
1.1075.2.41  raeburn  9568: =cut
                   9569: 
1.1075.2.42  raeburn  9570: sub excess_filesize_warning {
1.1075.2.59  raeburn  9571:     my ($uname,$udom,$context,$filename,$filesize,$action,$quotatype) = @_;
1.1075.2.42  raeburn  9572:     my $current_disk_usage = 0;
1.1075.2.59  raeburn  9573:     my $disk_quota = &get_user_quota($uname,$udom,$context,$quotatype); #expressed in MB
1.1075.2.42  raeburn  9574:     if ($context eq 'author') {
                   9575:         my $authorspace = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname";
                   9576:         $current_disk_usage = &Apache::lonnet::diskusage($udom,$uname,$authorspace);
                   9577:     } else {
                   9578:         foreach my $subdir ('docs','supplemental') {
                   9579:             $current_disk_usage += &Apache::lonnet::diskusage($udom,$uname,"userfiles/$subdir",1);
                   9580:         }
                   9581:     }
1.1075.2.41  raeburn  9582:     $disk_quota = int($disk_quota * 1000);
                   9583:     if (($current_disk_usage + $filesize) > $disk_quota) {
1.1075.2.69  raeburn  9584:         return '<p class="LC_warning">'.
1.1075.2.41  raeburn  9585:                 &mt("Unable to $action [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.",
1.1075.2.69  raeburn  9586:                     '<span class="LC_filename">'.$filename.'</span>',$filesize).'</p>'.
                   9587:                '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
1.1075.2.41  raeburn  9588:                             $disk_quota,$current_disk_usage).
                   9589:                '</p>';
                   9590:     }
                   9591:     return;
                   9592: }
                   9593: 
                   9594: ###############################################
                   9595: 
                   9596: 
1.384     raeburn  9597: sub get_secgrprole_info {
                   9598:     my ($cdom,$cnum,$needroles,$type)  = @_;
                   9599:     my %sections_count = &get_sections($cdom,$cnum);
                   9600:     my @sections =  (sort {$a <=> $b} keys(%sections_count));
                   9601:     my %curr_groups = &Apache::longroup::coursegroups($cdom,$cnum);
                   9602:     my @groups = sort(keys(%curr_groups));
                   9603:     my $allroles = [];
                   9604:     my $rolehash;
                   9605:     my $accesshash = {
                   9606:                      active => 'Currently has access',
                   9607:                      future => 'Will have future access',
                   9608:                      previous => 'Previously had access',
                   9609:                   };
                   9610:     if ($needroles) {
                   9611:         $rolehash = {'all' => 'all'};
1.385     albertel 9612:         my %user_roles = &Apache::lonnet::dump('nohist_userroles',$cdom,$cnum);
                   9613: 	if (&Apache::lonnet::error(%user_roles)) {
                   9614: 	    undef(%user_roles);
                   9615: 	}
                   9616:         foreach my $item (keys(%user_roles)) {
1.384     raeburn  9617:             my ($role)=split(/\:/,$item,2);
                   9618:             if ($role eq 'cr') { next; }
                   9619:             if ($role =~ /^cr/) {
                   9620:                 $$rolehash{$role} = (split('/',$role))[3];
                   9621:             } else {
                   9622:                 $$rolehash{$role} = &Apache::lonnet::plaintext($role,$type);
                   9623:             }
                   9624:         }
                   9625:         foreach my $key (sort(keys(%{$rolehash}))) {
                   9626:             push(@{$allroles},$key);
                   9627:         }
                   9628:         push (@{$allroles},'st');
                   9629:         $$rolehash{'st'} = &Apache::lonnet::plaintext('st',$type);
                   9630:     }
                   9631:     return (\@sections,\@groups,$allroles,$rolehash,$accesshash);
                   9632: }
                   9633: 
1.555     raeburn  9634: sub user_picker {
1.1075.2.127  raeburn  9635:     my ($dom,$srch,$forcenewuser,$caller,$cancreate,$usertype,$context,$fixeddom,$noinstd) = @_;
1.555     raeburn  9636:     my $currdom = $dom;
1.1075.2.114  raeburn  9637:     my @alldoms = &Apache::lonnet::all_domains();
                   9638:     if (@alldoms == 1) {
                   9639:         my %domsrch = &Apache::lonnet::get_dom('configuration',
                   9640:                                                ['directorysrch'],$alldoms[0]);
                   9641:         my $domdesc = &Apache::lonnet::domain($alldoms[0],'description');
                   9642:         my $showdom = $domdesc;
                   9643:         if ($showdom eq '') {
                   9644:             $showdom = $dom;
                   9645:         }
                   9646:         if (ref($domsrch{'directorysrch'}) eq 'HASH') {
                   9647:             if ((!$domsrch{'directorysrch'}{'available'}) &&
                   9648:                 ($domsrch{'directorysrch'}{'lcavailable'} eq '0')) {
                   9649:                 return (&mt('LON-CAPA directory search is not available in domain: [_1]',$showdom),0);
                   9650:             }
                   9651:         }
                   9652:     }
1.555     raeburn  9653:     my %curr_selected = (
                   9654:                         srchin => 'dom',
1.580     raeburn  9655:                         srchby => 'lastname',
1.555     raeburn  9656:                       );
                   9657:     my $srchterm;
1.625     raeburn  9658:     if ((ref($srch) eq 'HASH') && ($env{'form.origform'} ne 'crtusername')) {
1.555     raeburn  9659:         if ($srch->{'srchby'} ne '') {
                   9660:             $curr_selected{'srchby'} = $srch->{'srchby'};
                   9661:         }
                   9662:         if ($srch->{'srchin'} ne '') {
                   9663:             $curr_selected{'srchin'} = $srch->{'srchin'};
                   9664:         }
                   9665:         if ($srch->{'srchtype'} ne '') {
                   9666:             $curr_selected{'srchtype'} = $srch->{'srchtype'};
                   9667:         }
                   9668:         if ($srch->{'srchdomain'} ne '') {
                   9669:             $currdom = $srch->{'srchdomain'};
                   9670:         }
                   9671:         $srchterm = $srch->{'srchterm'};
                   9672:     }
1.1075.2.98  raeburn  9673:     my %html_lt=&Apache::lonlocal::texthash(
1.573     raeburn  9674:                     'usr'       => 'Search criteria',
1.563     raeburn  9675:                     'doma'      => 'Domain/institution to search',
1.558     albertel 9676:                     'uname'     => 'username',
                   9677:                     'lastname'  => 'last name',
1.555     raeburn  9678:                     'lastfirst' => 'last name, first name',
1.558     albertel 9679:                     'crs'       => 'in this course',
1.576     raeburn  9680:                     'dom'       => 'in selected LON-CAPA domain', 
1.558     albertel 9681:                     'alc'       => 'all LON-CAPA',
1.573     raeburn  9682:                     'instd'     => 'in institutional directory for selected domain',
1.558     albertel 9683:                     'exact'     => 'is',
                   9684:                     'contains'  => 'contains',
1.569     raeburn  9685:                     'begins'    => 'begins with',
1.1075.2.98  raeburn  9686:                                        );
                   9687:     my %js_lt=&Apache::lonlocal::texthash(
1.571     raeburn  9688:                     'youm'      => "You must include some text to search for.",
                   9689:                     'thte'      => "The text you are searching for must contain at least two characters when using a 'begins' type search.",
                   9690:                     'thet'      => "The text you are searching for must contain at least three characters when using a 'contains' type search.",
                   9691:                     'yomc'      => "You must choose a domain when using an institutional directory search.",
                   9692:                     'ymcd'      => "You must choose a domain when using a domain search.",
                   9693:                     'whus'      => "When using searching by last,first you must include a comma as separator between last name and first name.",
                   9694:                     'whse'      => "When searching by last,first you must include at least one character in the first name.",
                   9695:                      'thfo'     => "The following need to be corrected before the search can be run:",
1.555     raeburn  9696:                                        );
1.1075.2.98  raeburn  9697:     &html_escape(\%html_lt);
                   9698:     &js_escape(\%js_lt);
1.1075.2.115  raeburn  9699:     my $domform;
1.1075.2.126  raeburn  9700:     my $allow_blank = 1;
1.1075.2.115  raeburn  9701:     if ($fixeddom) {
1.1075.2.126  raeburn  9702:         $allow_blank = 0;
                   9703:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1,undef,[$currdom]);
1.1075.2.115  raeburn  9704:     } else {
1.1075.2.126  raeburn  9705:         $domform = &select_dom_form($currdom,'srchdomain',$allow_blank,1);
1.1075.2.115  raeburn  9706:     }
1.563     raeburn  9707:     my $srchinsel = ' <select name="srchin">';
1.555     raeburn  9708: 
                   9709:     my @srchins = ('crs','dom','alc','instd');
                   9710: 
                   9711:     foreach my $option (@srchins) {
                   9712:         # FIXME 'alc' option unavailable until 
                   9713:         #       loncreateuser::print_user_query_page()
                   9714:         #       has been completed.
                   9715:         next if ($option eq 'alc');
1.880     raeburn  9716:         next if (($option eq 'crs') && ($env{'form.form'} eq 'requestcrs'));  
1.555     raeburn  9717:         next if ($option eq 'crs' && !$env{'request.course.id'});
1.1075.2.127  raeburn  9718:         next if (($option eq 'instd') && ($noinstd));
1.563     raeburn  9719:         if ($curr_selected{'srchin'} eq $option) {
                   9720:             $srchinsel .= ' 
1.1075.2.98  raeburn  9721:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.563     raeburn  9722:         } else {
                   9723:             $srchinsel .= '
1.1075.2.98  raeburn  9724:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.563     raeburn  9725:         }
1.555     raeburn  9726:     }
1.563     raeburn  9727:     $srchinsel .= "\n  </select>\n";
1.555     raeburn  9728: 
                   9729:     my $srchbysel =  ' <select name="srchby">';
1.580     raeburn  9730:     foreach my $option ('lastname','lastfirst','uname') {
1.555     raeburn  9731:         if ($curr_selected{'srchby'} eq $option) {
                   9732:             $srchbysel .= '
1.1075.2.98  raeburn  9733:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9734:         } else {
                   9735:             $srchbysel .= '
1.1075.2.98  raeburn  9736:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9737:          }
                   9738:     }
                   9739:     $srchbysel .= "\n  </select>\n";
                   9740: 
                   9741:     my $srchtypesel = ' <select name="srchtype">';
1.580     raeburn  9742:     foreach my $option ('begins','contains','exact') {
1.555     raeburn  9743:         if ($curr_selected{'srchtype'} eq $option) {
                   9744:             $srchtypesel .= '
1.1075.2.98  raeburn  9745:    <option value="'.$option.'" selected="selected">'.$html_lt{$option}.'</option>';
1.555     raeburn  9746:         } else {
                   9747:             $srchtypesel .= '
1.1075.2.98  raeburn  9748:    <option value="'.$option.'">'.$html_lt{$option}.'</option>';
1.555     raeburn  9749:         }
                   9750:     }
                   9751:     $srchtypesel .= "\n  </select>\n";
                   9752: 
1.558     albertel 9753:     my ($newuserscript,$new_user_create);
1.994     raeburn  9754:     my $context_dom = $env{'request.role.domain'};
                   9755:     if ($context eq 'requestcrs') {
                   9756:         if ($env{'form.coursedom'} ne '') { 
                   9757:             $context_dom = $env{'form.coursedom'};
                   9758:         }
                   9759:     }
1.556     raeburn  9760:     if ($forcenewuser) {
1.576     raeburn  9761:         if (ref($srch) eq 'HASH') {
1.994     raeburn  9762:             if ($srch->{'srchby'} eq 'uname' && $srch->{'srchtype'} eq 'exact' && $srch->{'srchin'} eq 'dom' && $srch->{'srchdomain'} eq $context_dom) {
1.627     raeburn  9763:                 if ($cancreate) {
                   9764:                     $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>';
                   9765:                 } else {
1.799     bisitz   9766:                     my $helplink = 'javascript:helpMenu('."'display'".')';
1.627     raeburn  9767:                     my %usertypetext = (
                   9768:                         official   => 'institutional',
                   9769:                         unofficial => 'non-institutional',
                   9770:                     );
1.799     bisitz   9771:                     $new_user_create = '<p class="LC_warning">'
                   9772:                                       .&mt("You are not authorized to create new $usertypetext{$usertype} users in this domain.")
                   9773:                                       .' '
                   9774:                                       .&mt('Please contact the [_1]helpdesk[_2] for assistance.'
                   9775:                                           ,'<a href="'.$helplink.'">','</a>')
                   9776:                                       .'</p><br />';
1.627     raeburn  9777:                 }
1.576     raeburn  9778:             }
                   9779:         }
                   9780: 
1.556     raeburn  9781:         $newuserscript = <<"ENDSCRIPT";
                   9782: 
1.570     raeburn  9783: function setSearch(createnew,callingForm) {
1.556     raeburn  9784:     if (createnew == 1) {
1.570     raeburn  9785:         for (var i=0; i<callingForm.srchby.length; i++) {
                   9786:             if (callingForm.srchby.options[i].value == 'uname') {
                   9787:                 callingForm.srchby.selectedIndex = i;
1.556     raeburn  9788:             }
                   9789:         }
1.570     raeburn  9790:         for (var i=0; i<callingForm.srchin.length; i++) {
                   9791:             if ( callingForm.srchin.options[i].value == 'dom') {
                   9792: 		callingForm.srchin.selectedIndex = i;
1.556     raeburn  9793:             }
                   9794:         }
1.570     raeburn  9795:         for (var i=0; i<callingForm.srchtype.length; i++) {
                   9796:             if (callingForm.srchtype.options[i].value == 'exact') {
                   9797:                 callingForm.srchtype.selectedIndex = i;
1.556     raeburn  9798:             }
                   9799:         }
1.570     raeburn  9800:         for (var i=0; i<callingForm.srchdomain.length; i++) {
1.994     raeburn  9801:             if (callingForm.srchdomain.options[i].value == '$context_dom') {
1.570     raeburn  9802:                 callingForm.srchdomain.selectedIndex = i;
1.556     raeburn  9803:             }
                   9804:         }
                   9805:     }
                   9806: }
                   9807: ENDSCRIPT
1.558     albertel 9808: 
1.556     raeburn  9809:     }
                   9810: 
1.555     raeburn  9811:     my $output = <<"END_BLOCK";
1.556     raeburn  9812: <script type="text/javascript">
1.824     bisitz   9813: // <![CDATA[
1.570     raeburn  9814: function validateEntry(callingForm) {
1.558     albertel 9815: 
1.556     raeburn  9816:     var checkok = 1;
1.558     albertel 9817:     var srchin;
1.570     raeburn  9818:     for (var i=0; i<callingForm.srchin.length; i++) {
                   9819: 	if ( callingForm.srchin[i].checked ) {
                   9820: 	    srchin = callingForm.srchin[i].value;
1.558     albertel 9821: 	}
                   9822:     }
                   9823: 
1.570     raeburn  9824:     var srchtype = callingForm.srchtype.options[callingForm.srchtype.selectedIndex].value;
                   9825:     var srchby = callingForm.srchby.options[callingForm.srchby.selectedIndex].value;
                   9826:     var srchdomain = callingForm.srchdomain.options[callingForm.srchdomain.selectedIndex].value;
                   9827:     var srchterm =  callingForm.srchterm.value;
                   9828:     var srchin = callingForm.srchin.options[callingForm.srchin.selectedIndex].value;
1.556     raeburn  9829:     var msg = "";
                   9830: 
                   9831:     if (srchterm == "") {
                   9832:         checkok = 0;
1.1075.2.98  raeburn  9833:         msg += "$js_lt{'youm'}\\n";
1.556     raeburn  9834:     }
                   9835: 
1.569     raeburn  9836:     if (srchtype== 'begins') {
                   9837:         if (srchterm.length < 2) {
                   9838:             checkok = 0;
1.1075.2.98  raeburn  9839:             msg += "$js_lt{'thte'}\\n";
1.569     raeburn  9840:         }
                   9841:     }
                   9842: 
1.556     raeburn  9843:     if (srchtype== 'contains') {
                   9844:         if (srchterm.length < 3) {
                   9845:             checkok = 0;
1.1075.2.98  raeburn  9846:             msg += "$js_lt{'thet'}\\n";
1.556     raeburn  9847:         }
                   9848:     }
                   9849:     if (srchin == 'instd') {
                   9850:         if (srchdomain == '') {
                   9851:             checkok = 0;
1.1075.2.98  raeburn  9852:             msg += "$js_lt{'yomc'}\\n";
1.556     raeburn  9853:         }
                   9854:     }
                   9855:     if (srchin == 'dom') {
                   9856:         if (srchdomain == '') {
                   9857:             checkok = 0;
1.1075.2.98  raeburn  9858:             msg += "$js_lt{'ymcd'}\\n";
1.556     raeburn  9859:         }
                   9860:     }
                   9861:     if (srchby == 'lastfirst') {
                   9862:         if (srchterm.indexOf(",") == -1) {
                   9863:             checkok = 0;
1.1075.2.98  raeburn  9864:             msg += "$js_lt{'whus'}\\n";
1.556     raeburn  9865:         }
                   9866:         if (srchterm.indexOf(",") == srchterm.length -1) {
                   9867:             checkok = 0;
1.1075.2.98  raeburn  9868:             msg += "$js_lt{'whse'}\\n";
1.556     raeburn  9869:         }
                   9870:     }
                   9871:     if (checkok == 0) {
1.1075.2.98  raeburn  9872:         alert("$js_lt{'thfo'}\\n"+msg);
1.556     raeburn  9873:         return;
                   9874:     }
                   9875:     if (checkok == 1) {
1.570     raeburn  9876:         callingForm.submit();
1.556     raeburn  9877:     }
                   9878: }
                   9879: 
                   9880: $newuserscript
                   9881: 
1.824     bisitz   9882: // ]]>
1.556     raeburn  9883: </script>
1.558     albertel 9884: 
                   9885: $new_user_create
                   9886: 
1.555     raeburn  9887: END_BLOCK
1.558     albertel 9888: 
1.876     raeburn  9889:     $output .= &Apache::lonhtmlcommon::start_pick_box().
1.1075.2.98  raeburn  9890:                &Apache::lonhtmlcommon::row_title($html_lt{'doma'}).
1.876     raeburn  9891:                $domform.
                   9892:                &Apache::lonhtmlcommon::row_closure().
1.1075.2.98  raeburn  9893:                &Apache::lonhtmlcommon::row_title($html_lt{'usr'}).
1.876     raeburn  9894:                $srchbysel.
                   9895:                $srchtypesel. 
                   9896:                '<input type="text" size="15" name="srchterm" value="'.$srchterm.'" />'.
                   9897:                $srchinsel.
                   9898:                &Apache::lonhtmlcommon::row_closure(1). 
                   9899:                &Apache::lonhtmlcommon::end_pick_box().
                   9900:                '<br />';
1.1075.2.114  raeburn  9901:     return ($output,1);
1.555     raeburn  9902: }
                   9903: 
1.612     raeburn  9904: sub user_rule_check {
1.615     raeburn  9905:     my ($usershash,$checks,$alerts,$rulematch,$inst_results,$curr_rules,$got_rules) = @_;
1.1075.2.99  raeburn  9906:     my ($response,%inst_response);
1.612     raeburn  9907:     if (ref($usershash) eq 'HASH') {
1.1075.2.99  raeburn  9908:         if (keys(%{$usershash}) > 1) {
                   9909:             my (%by_username,%by_id,%userdoms);
                   9910:             my $checkid;
1.612     raeburn  9911:             if (ref($checks) eq 'HASH') {
1.1075.2.99  raeburn  9912:                 if ((!defined($checks->{'username'})) && (defined($checks->{'id'}))) {
                   9913:                     $checkid = 1;
                   9914:                 }
                   9915:             }
                   9916:             foreach my $user (keys(%{$usershash})) {
                   9917:                 my ($uname,$udom) = split(/:/,$user);
                   9918:                 if ($checkid) {
                   9919:                     if (ref($usershash->{$user}) eq 'HASH') {
                   9920:                         if ($usershash->{$user}->{'id'} ne '') {
                   9921:                             $by_id{$udom}{$usershash->{$user}->{'id'}} = $uname;
                   9922:                             $userdoms{$udom} = 1;
                   9923:                             if (ref($inst_results) eq 'HASH') {
                   9924:                                 $inst_results->{$uname.':'.$udom} = {};
                   9925:                             }
                   9926:                         }
                   9927:                     }
                   9928:                 } else {
                   9929:                     $by_username{$udom}{$uname} = 1;
                   9930:                     $userdoms{$udom} = 1;
                   9931:                     if (ref($inst_results) eq 'HASH') {
                   9932:                         $inst_results->{$uname.':'.$udom} = {};
                   9933:                     }
                   9934:                 }
                   9935:             }
                   9936:             foreach my $udom (keys(%userdoms)) {
                   9937:                 if (!$got_rules->{$udom}) {
                   9938:                     my %domconfig = &Apache::lonnet::get_dom('configuration',
                   9939:                                                              ['usercreation'],$udom);
                   9940:                     if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   9941:                         foreach my $item ('username','id') {
                   9942:                             if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   9943:                                 $$curr_rules{$udom}{$item} =
                   9944:                                     $domconfig{'usercreation'}{$item.'_rule'};
                   9945:                             }
                   9946:                         }
                   9947:                     }
                   9948:                     $got_rules->{$udom} = 1;
                   9949:                 }
                   9950:             }
                   9951:             if ($checkid) {
                   9952:                 foreach my $udom (keys(%by_id)) {
                   9953:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_id{$udom},'id');
                   9954:                     if ($outcome eq 'ok') {
                   9955:                         foreach my $id (keys(%{$by_id{$udom}})) {
                   9956:                             my $uname = $by_id{$udom}{$id};
                   9957:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9958:                         }
                   9959:                         if (ref($results) eq 'HASH') {
                   9960:                             foreach my $uname (keys(%{$results})) {
                   9961:                                 if (exists($inst_response{$uname.':'.$udom})) {
                   9962:                                     $inst_response{$uname.':'.$udom} = $outcome;
                   9963:                                     $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9964:                                 }
                   9965:                             }
                   9966:                         }
                   9967:                     }
1.612     raeburn  9968:                 }
1.615     raeburn  9969:             } else {
1.1075.2.99  raeburn  9970:                 foreach my $udom (keys(%by_username)) {
                   9971:                     my ($outcome,$results) = &Apache::lonnet::get_multiple_instusers($udom,$by_username{$udom});
                   9972:                     if ($outcome eq 'ok') {
                   9973:                         foreach my $uname (keys(%{$by_username{$udom}})) {
                   9974:                             $inst_response{$uname.':'.$udom} = $outcome;
                   9975:                         }
                   9976:                         if (ref($results) eq 'HASH') {
                   9977:                             foreach my $uname (keys(%{$results})) {
                   9978:                                 $inst_results->{$uname.':'.$udom} = $results->{$uname};
                   9979:                             }
                   9980:                         }
                   9981:                     }
                   9982:                 }
1.612     raeburn  9983:             }
1.1075.2.99  raeburn  9984:         } elsif (keys(%{$usershash}) == 1) {
                   9985:             my $user = (keys(%{$usershash}))[0];
                   9986:             my ($uname,$udom) = split(/:/,$user);
                   9987:             if (($udom ne '') && ($uname ne '')) {
                   9988:                 if (ref($usershash->{$user}) eq 'HASH') {
                   9989:                     if (ref($checks) eq 'HASH') {
                   9990:                         if (defined($checks->{'username'})) {
                   9991:                             ($inst_response{$user},%{$inst_results->{$user}}) =
                   9992:                                 &Apache::lonnet::get_instuser($udom,$uname);
                   9993:                         } elsif (defined($checks->{'id'})) {
                   9994:                             if ($usershash->{$user}->{'id'} ne '') {
                   9995:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   9996:                                     &Apache::lonnet::get_instuser($udom,undef,
                   9997:                                                                   $usershash->{$user}->{'id'});
                   9998:                             } else {
                   9999:                                 ($inst_response{$user},%{$inst_results->{$user}}) =
                   10000:                                     &Apache::lonnet::get_instuser($udom,$uname);
                   10001:                             }
                   10002:                         }
                   10003:                     } else {
                   10004:                        ($inst_response{$user},%{$inst_results->{$user}}) =
                   10005:                             &Apache::lonnet::get_instuser($udom,$uname);
                   10006:                        return;
                   10007:                     }
                   10008:                     if (!$got_rules->{$udom}) {
                   10009:                         my %domconfig = &Apache::lonnet::get_dom('configuration',
                   10010:                                                                  ['usercreation'],$udom);
                   10011:                         if (ref($domconfig{'usercreation'}) eq 'HASH') {
                   10012:                             foreach my $item ('username','id') {
                   10013:                                 if (ref($domconfig{'usercreation'}{$item.'_rule'}) eq 'ARRAY') {
                   10014:                                    $$curr_rules{$udom}{$item} =
                   10015:                                        $domconfig{'usercreation'}{$item.'_rule'};
                   10016:                                 }
                   10017:                             }
1.585     raeburn  10018:                         }
1.1075.2.99  raeburn  10019:                         $got_rules->{$udom} = 1;
1.585     raeburn  10020:                     }
                   10021:                 }
1.1075.2.99  raeburn  10022:             } else {
                   10023:                 return;
                   10024:             }
                   10025:         } else {
                   10026:             return;
                   10027:         }
                   10028:         foreach my $user (keys(%{$usershash})) {
                   10029:             my ($uname,$udom) = split(/:/,$user);
                   10030:             next if (($udom eq '') || ($uname eq ''));
                   10031:             my $id;
                   10032:             if (ref($inst_results) eq 'HASH') {
                   10033:                 if (ref($inst_results->{$user}) eq 'HASH') {
                   10034:                     $id = $inst_results->{$user}->{'id'};
                   10035:                 }
                   10036:             }
                   10037:             if ($id eq '') {
                   10038:                 if (ref($usershash->{$user})) {
                   10039:                     $id = $usershash->{$user}->{'id'};
                   10040:                 }
1.585     raeburn  10041:             }
1.612     raeburn  10042:             foreach my $item (keys(%{$checks})) {
                   10043:                 if (ref($$curr_rules{$udom}) eq 'HASH') {
                   10044:                     if (ref($$curr_rules{$udom}{$item}) eq 'ARRAY') {
                   10045:                         if (@{$$curr_rules{$udom}{$item}} > 0) {
1.1075.2.99  raeburn  10046:                             my %rule_check = &Apache::lonnet::inst_rulecheck($udom,$uname,$id,$item,
                   10047:                                                                              $$curr_rules{$udom}{$item});
1.612     raeburn  10048:                             foreach my $rule (@{$$curr_rules{$udom}{$item}}) {
                   10049:                                 if ($rule_check{$rule}) {
                   10050:                                     $$rulematch{$user}{$item} = $rule;
1.1075.2.99  raeburn  10051:                                     if ($inst_response{$user} eq 'ok') {
1.615     raeburn  10052:                                         if (ref($inst_results) eq 'HASH') {
                   10053:                                             if (ref($inst_results->{$user}) eq 'HASH') {
                   10054:                                                 if (keys(%{$inst_results->{$user}}) == 0) {
                   10055:                                                     $$alerts{$item}{$udom}{$uname} = 1;
1.1075.2.99  raeburn  10056:                                                 } elsif ($item eq 'id') {
                   10057:                                                     if ($inst_results->{$user}->{'id'} eq '') {
                   10058:                                                         $$alerts{$item}{$udom}{$uname} = 1;
                   10059:                                                     }
1.615     raeburn  10060:                                                 }
1.612     raeburn  10061:                                             }
                   10062:                                         }
1.615     raeburn  10063:                                     }
                   10064:                                     last;
1.585     raeburn  10065:                                 }
                   10066:                             }
                   10067:                         }
                   10068:                     }
                   10069:                 }
                   10070:             }
                   10071:         }
                   10072:     }
1.612     raeburn  10073:     return;
                   10074: }
                   10075: 
                   10076: sub user_rule_formats {
                   10077:     my ($domain,$domdesc,$curr_rules,$check) = @_;
                   10078:     my %text = ( 
                   10079:                  'username' => 'Usernames',
                   10080:                  'id'       => 'IDs',
                   10081:                );
                   10082:     my $output;
                   10083:     my ($rules,$ruleorder) = &Apache::lonnet::inst_userrules($domain,$check);
                   10084:     if ((ref($rules) eq 'HASH') && (ref($ruleorder) eq 'ARRAY')) {
                   10085:         if (@{$ruleorder} > 0) {
1.1075.2.20  raeburn  10086:             $output = '<br />'.
                   10087:                       &mt($text{$check}.' with the following format(s) may [_1]only[_2] be used for verified users at [_3]:',
                   10088:                           '<span class="LC_cusr_emph">','</span>',$domdesc).
                   10089:                       ' <ul>';
1.612     raeburn  10090:             foreach my $rule (@{$ruleorder}) {
                   10091:                 if (ref($curr_rules) eq 'ARRAY') {
                   10092:                     if (grep(/^\Q$rule\E$/,@{$curr_rules})) {
                   10093:                         if (ref($rules->{$rule}) eq 'HASH') {
                   10094:                             $output .= '<li>'.$rules->{$rule}{'name'}.': '.
                   10095:                                         $rules->{$rule}{'desc'}.'</li>';
                   10096:                         }
                   10097:                     }
                   10098:                 }
                   10099:             }
                   10100:             $output .= '</ul>';
                   10101:         }
                   10102:     }
                   10103:     return $output;
                   10104: }
                   10105: 
                   10106: sub instrule_disallow_msg {
1.615     raeburn  10107:     my ($checkitem,$domdesc,$count,$mode) = @_;
1.612     raeburn  10108:     my $response;
                   10109:     my %text = (
                   10110:                   item   => 'username',
                   10111:                   items  => 'usernames',
                   10112:                   match  => 'matches',
                   10113:                   do     => 'does',
                   10114:                   action => 'a username',
                   10115:                   one    => 'one',
                   10116:                );
                   10117:     if ($count > 1) {
                   10118:         $text{'item'} = 'usernames';
                   10119:         $text{'match'} ='match';
                   10120:         $text{'do'} = 'do';
                   10121:         $text{'action'} = 'usernames',
                   10122:         $text{'one'} = 'ones';
                   10123:     }
                   10124:     if ($checkitem eq 'id') {
                   10125:         $text{'items'} = 'IDs';
                   10126:         $text{'item'} = 'ID';
                   10127:         $text{'action'} = 'an ID';
1.615     raeburn  10128:         if ($count > 1) {
                   10129:             $text{'item'} = 'IDs';
                   10130:             $text{'action'} = 'IDs';
                   10131:         }
1.612     raeburn  10132:     }
1.674     bisitz   10133:     $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  10134:     if ($mode eq 'upload') {
                   10135:         if ($checkitem eq 'username') {
                   10136:             $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'}.");
                   10137:         } elsif ($checkitem eq 'id') {
1.674     bisitz   10138:             $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  10139:         }
1.669     raeburn  10140:     } elsif ($mode eq 'selfcreate') {
                   10141:         if ($checkitem eq 'id') {
                   10142:             $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.");
                   10143:         }
1.615     raeburn  10144:     } else {
                   10145:         if ($checkitem eq 'username') {
                   10146:             $response .= &mt("You must choose $text{'action'} with a different format --  $text{'one'} that will not conflict with 'official' institutional $text{'items'}.");
                   10147:         } elsif ($checkitem eq 'id') {
                   10148:             $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.");
                   10149:         }
1.612     raeburn  10150:     }
                   10151:     return $response;
1.585     raeburn  10152: }
                   10153: 
1.624     raeburn  10154: sub personal_data_fieldtitles {
                   10155:     my %fieldtitles = &Apache::lonlocal::texthash (
                   10156:                         id => 'Student/Employee ID',
                   10157:                         permanentemail => 'E-mail address',
                   10158:                         lastname => 'Last Name',
                   10159:                         firstname => 'First Name',
                   10160:                         middlename => 'Middle Name',
                   10161:                         generation => 'Generation',
                   10162:                         gen => 'Generation',
1.765     raeburn  10163:                         inststatus => 'Affiliation',
1.624     raeburn  10164:                    );
                   10165:     return %fieldtitles;
                   10166: }
                   10167: 
1.642     raeburn  10168: sub sorted_inst_types {
                   10169:     my ($dom) = @_;
1.1075.2.70  raeburn  10170:     my ($usertypes,$order);
                   10171:     my %domdefaults = &Apache::lonnet::get_domain_defaults($dom);
                   10172:     if (ref($domdefaults{'inststatus'}) eq 'HASH') {
                   10173:         $usertypes = $domdefaults{'inststatus'}{'inststatustypes'};
                   10174:         $order = $domdefaults{'inststatus'}{'inststatusorder'};
                   10175:     } else {
                   10176:         ($usertypes,$order) = &Apache::lonnet::retrieve_inst_usertypes($dom);
                   10177:     }
1.642     raeburn  10178:     my $othertitle = &mt('All users');
                   10179:     if ($env{'request.course.id'}) {
1.668     raeburn  10180:         $othertitle  = &mt('Any users');
1.642     raeburn  10181:     }
                   10182:     my @types;
                   10183:     if (ref($order) eq 'ARRAY') {
                   10184:         @types = @{$order};
                   10185:     }
                   10186:     if (@types == 0) {
                   10187:         if (ref($usertypes) eq 'HASH') {
                   10188:             @types = sort(keys(%{$usertypes}));
                   10189:         }
                   10190:     }
                   10191:     if (keys(%{$usertypes}) > 0) {
                   10192:         $othertitle = &mt('Other users');
                   10193:     }
                   10194:     return ($othertitle,$usertypes,\@types);
                   10195: }
                   10196: 
1.645     raeburn  10197: sub get_institutional_codes {
                   10198:     my ($settings,$allcourses,$LC_code) = @_;
                   10199: # Get complete list of course sections to update
                   10200:     my @currsections = ();
                   10201:     my @currxlists = ();
                   10202:     my $coursecode = $$settings{'internal.coursecode'};
                   10203: 
                   10204:     if ($$settings{'internal.sectionnums'} ne '') {
                   10205:         @currsections = split(/,/,$$settings{'internal.sectionnums'});
                   10206:     }
                   10207: 
                   10208:     if ($$settings{'internal.crosslistings'} ne '') {
                   10209:         @currxlists = split(/,/,$$settings{'internal.crosslistings'});
                   10210:     }
                   10211: 
                   10212:     if (@currxlists > 0) {
                   10213:         foreach (@currxlists) {
                   10214:             if (m/^([^:]+):(\w*)$/) {
                   10215:                 unless (grep/^$1$/,@{$allcourses}) {
1.1075.2.119  raeburn  10216:                     push(@{$allcourses},$1);
1.645     raeburn  10217:                     $$LC_code{$1} = $2;
                   10218:                 }
                   10219:             }
                   10220:         }
                   10221:     }
                   10222:  
                   10223:     if (@currsections > 0) {
                   10224:         foreach (@currsections) {
                   10225:             if (m/^(\w+):(\w*)$/) {
                   10226:                 my $sec = $coursecode.$1;
                   10227:                 my $lc_sec = $2;
                   10228:                 unless (grep/^$sec$/,@{$allcourses}) {
1.1075.2.119  raeburn  10229:                     push(@{$allcourses},$sec);
1.645     raeburn  10230:                     $$LC_code{$sec} = $lc_sec;
                   10231:                 }
                   10232:             }
                   10233:         }
                   10234:     }
                   10235:     return;
                   10236: }
                   10237: 
1.971     raeburn  10238: sub get_standard_codeitems {
                   10239:     return ('Year','Semester','Department','Number','Section');
                   10240: }
                   10241: 
1.112     bowersj2 10242: =pod
                   10243: 
1.780     raeburn  10244: =head1 Slot Helpers
                   10245: 
                   10246: =over 4
                   10247: 
                   10248: =item * sorted_slots()
                   10249: 
1.1040    raeburn  10250: Sorts an array of slot names in order of an optional sort key,
                   10251: default sort is by slot start time (earliest first). 
1.780     raeburn  10252: 
                   10253: Inputs:
                   10254: 
                   10255: =over 4
                   10256: 
                   10257: slotsarr  - Reference to array of unsorted slot names.
                   10258: 
                   10259: slots     - Reference to hash of hash, where outer hash keys are slot names.
                   10260: 
1.1040    raeburn  10261: sortkey   - Name of key in inner hash to be sorted on (e.g., starttime).
                   10262: 
1.549     albertel 10263: =back
                   10264: 
1.780     raeburn  10265: Returns:
                   10266: 
                   10267: =over 4
                   10268: 
1.1040    raeburn  10269: sorted   - An array of slot names sorted by a specified sort key 
                   10270:            (default sort key is start time of the slot).
1.780     raeburn  10271: 
                   10272: =back
                   10273: 
                   10274: =cut
                   10275: 
                   10276: 
                   10277: sub sorted_slots {
1.1040    raeburn  10278:     my ($slotsarr,$slots,$sortkey) = @_;
                   10279:     if ($sortkey eq '') {
                   10280:         $sortkey = 'starttime';
                   10281:     }
1.780     raeburn  10282:     my @sorted;
                   10283:     if ((ref($slotsarr) eq 'ARRAY') && (ref($slots) eq 'HASH')) {
                   10284:         @sorted =
                   10285:             sort {
                   10286:                      if (ref($slots->{$a}) && ref($slots->{$b})) {
1.1040    raeburn  10287:                          return $slots->{$a}{$sortkey} <=> $slots->{$b}{$sortkey}
1.780     raeburn  10288:                      }
                   10289:                      if (ref($slots->{$a})) { return -1;}
                   10290:                      if (ref($slots->{$b})) { return 1;}
                   10291:                      return 0;
                   10292:                  } @{$slotsarr};
                   10293:     }
                   10294:     return @sorted;
                   10295: }
                   10296: 
1.1040    raeburn  10297: =pod
                   10298: 
                   10299: =item * get_future_slots()
                   10300: 
                   10301: Inputs:
                   10302: 
                   10303: =over 4
                   10304: 
                   10305: cnum - course number
                   10306: 
                   10307: cdom - course domain
                   10308: 
                   10309: now - current UNIX time
                   10310: 
                   10311: symb - optional symb
                   10312: 
                   10313: =back
                   10314: 
                   10315: Returns:
                   10316: 
                   10317: =over 4
                   10318: 
                   10319: sorted_reservable - ref to array of student_schedulable slots currently 
                   10320:                     reservable, ordered by end date of reservation period.
                   10321: 
                   10322: reservable_now - ref to hash of student_schedulable slots currently
                   10323:                  reservable.
                   10324: 
                   10325:     Keys in inner hash are:
                   10326:     (a) symb: either blank or symb to which slot use is restricted.
1.1075.2.104  raeburn  10327:     (b) endreserve: end date of reservation period.
                   10328:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10329:         selected.
1.1040    raeburn  10330: 
                   10331: sorted_future - ref to array of student_schedulable slots reservable in
                   10332:                 the future, ordered by start date of reservation period.
                   10333: 
                   10334: future_reservable - ref to hash of student_schedulable slots reservable
                   10335:                     in the future.
                   10336: 
                   10337:     Keys in inner hash are:
                   10338:     (a) symb: either blank or symb to which slot use is restricted.
                   10339:     (b) startreserve:  start date of reservation period.
1.1075.2.104  raeburn  10340:     (c) uniqueperiod: start,end dates when slot is to be uniquely
                   10341:         selected.
1.1040    raeburn  10342: 
                   10343: =back
                   10344: 
                   10345: =cut
                   10346: 
                   10347: sub get_future_slots {
                   10348:     my ($cnum,$cdom,$now,$symb) = @_;
                   10349:     my (%reservable_now,%future_reservable,@sorted_reservable,@sorted_future);
                   10350:     my %slots = &Apache::lonnet::get_course_slots($cnum,$cdom);
                   10351:     foreach my $slot (keys(%slots)) {
                   10352:         next unless($slots{$slot}->{'type'} eq 'schedulable_student');
                   10353:         if ($symb) {
                   10354:             next if (($slots{$slot}->{'symb'} ne '') && 
                   10355:                      ($slots{$slot}->{'symb'} ne $symb));
                   10356:         }
                   10357:         if (($slots{$slot}->{'starttime'} > $now) &&
                   10358:             ($slots{$slot}->{'endtime'} > $now)) {
                   10359:             if (($slots{$slot}->{'allowedsections'}) || ($slots{$slot}->{'allowedusers'})) {
                   10360:                 my $userallowed = 0;
                   10361:                 if ($slots{$slot}->{'allowedsections'}) {
                   10362:                     my @allowed_sec = split(',',$slots{$slot}->{'allowedsections'});
                   10363:                     if (!defined($env{'request.role.sec'})
                   10364:                         && grep(/^No section assigned$/,@allowed_sec)) {
                   10365:                         $userallowed=1;
                   10366:                     } else {
                   10367:                         if (grep(/^\Q$env{'request.role.sec'}\E$/,@allowed_sec)) {
                   10368:                             $userallowed=1;
                   10369:                         }
                   10370:                     }
                   10371:                     unless ($userallowed) {
                   10372:                         if (defined($env{'request.course.groups'})) {
                   10373:                             my @groups = split(/:/,$env{'request.course.groups'});
                   10374:                             foreach my $group (@groups) {
                   10375:                                 if (grep(/^\Q$group\E$/,@allowed_sec)) {
                   10376:                                     $userallowed=1;
                   10377:                                     last;
                   10378:                                 }
                   10379:                             }
                   10380:                         }
                   10381:                     }
                   10382:                 }
                   10383:                 if ($slots{$slot}->{'allowedusers'}) {
                   10384:                     my @allowed_users = split(',',$slots{$slot}->{'allowedusers'});
                   10385:                     my $user = $env{'user.name'}.':'.$env{'user.domain'};
                   10386:                     if (grep(/^\Q$user\E$/,@allowed_users)) {
                   10387:                         $userallowed = 1;
                   10388:                     }
                   10389:                 }
                   10390:                 next unless($userallowed);
                   10391:             }
                   10392:             my $startreserve = $slots{$slot}->{'startreserve'};
                   10393:             my $endreserve = $slots{$slot}->{'endreserve'};
                   10394:             my $symb = $slots{$slot}->{'symb'};
1.1075.2.104  raeburn  10395:             my $uniqueperiod;
                   10396:             if (ref($slots{$slot}->{'uniqueperiod'}) eq 'ARRAY') {
                   10397:                 $uniqueperiod = join(',',@{$slots{$slot}->{'uniqueperiod'}});
                   10398:             }
1.1040    raeburn  10399:             if (($startreserve < $now) &&
                   10400:                 (!$endreserve || $endreserve > $now)) {
                   10401:                 my $lastres = $endreserve;
                   10402:                 if (!$lastres) {
                   10403:                     $lastres = $slots{$slot}->{'starttime'};
                   10404:                 }
                   10405:                 $reservable_now{$slot} = {
                   10406:                                            symb       => $symb,
1.1075.2.104  raeburn  10407:                                            endreserve => $lastres,
                   10408:                                            uniqueperiod => $uniqueperiod,   
1.1040    raeburn  10409:                                          };
                   10410:             } elsif (($startreserve > $now) &&
                   10411:                      (!$endreserve || $endreserve > $startreserve)) {
                   10412:                 $future_reservable{$slot} = {
                   10413:                                               symb         => $symb,
1.1075.2.104  raeburn  10414:                                               startreserve => $startreserve,
                   10415:                                               uniqueperiod => $uniqueperiod,
1.1040    raeburn  10416:                                             };
                   10417:             }
                   10418:         }
                   10419:     }
                   10420:     my @unsorted_reservable = keys(%reservable_now);
                   10421:     if (@unsorted_reservable > 0) {
                   10422:         @sorted_reservable = 
                   10423:             &sorted_slots(\@unsorted_reservable,\%reservable_now,'endreserve');
                   10424:     }
                   10425:     my @unsorted_future = keys(%future_reservable);
                   10426:     if (@unsorted_future > 0) {
                   10427:         @sorted_future =
                   10428:             &sorted_slots(\@unsorted_future,\%future_reservable,'startreserve');
                   10429:     }
                   10430:     return (\@sorted_reservable,\%reservable_now,\@sorted_future,\%future_reservable);
                   10431: }
1.780     raeburn  10432: 
                   10433: =pod
                   10434: 
1.1057    foxr     10435: =back
                   10436: 
1.549     albertel 10437: =head1 HTTP Helpers
                   10438: 
                   10439: =over 4
                   10440: 
1.648     raeburn  10441: =item * &get_unprocessed_cgi($query,$possible_names)
1.112     bowersj2 10442: 
1.258     albertel 10443: Modify the %env hash to contain unprocessed CGI form parameters held in
1.112     bowersj2 10444: $query.  The parameters listed in $possible_names (an array reference),
1.258     albertel 10445: will be set in $env{'form.name'} if they do not already exist.
1.112     bowersj2 10446: 
                   10447: Typically called with $ENV{'QUERY_STRING'} as the first parameter.  
                   10448: $possible_names is an ref to an array of form element names.  As an example:
                   10449: get_unprocessed_cgi($ENV{'QUERY_STRING'},['uname','udom']);
1.258     albertel 10450: will result in $env{'form.uname'} and $env{'form.udom'} being set.
1.112     bowersj2 10451: 
                   10452: =cut
1.1       albertel 10453: 
1.6       albertel 10454: sub get_unprocessed_cgi {
1.25      albertel 10455:   my ($query,$possible_names)= @_;
1.26      matthew  10456:   # $Apache::lonxml::debug=1;
1.356     albertel 10457:   foreach my $pair (split(/&/,$query)) {
                   10458:     my ($name, $value) = split(/=/,$pair);
1.369     www      10459:     $name = &unescape($name);
1.25      albertel 10460:     if (!defined($possible_names) || (grep {$_ eq $name} @$possible_names)) {
                   10461:       $value =~ tr/+/ /;
                   10462:       $value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
1.258     albertel 10463:       unless (defined($env{'form.'.$name})) { &add_to_env('form.'.$name,$value) };
1.25      albertel 10464:     }
1.16      harris41 10465:   }
1.6       albertel 10466: }
                   10467: 
1.112     bowersj2 10468: =pod
                   10469: 
1.648     raeburn  10470: =item * &cacheheader() 
1.112     bowersj2 10471: 
                   10472: returns cache-controlling header code
                   10473: 
                   10474: =cut
                   10475: 
1.7       albertel 10476: sub cacheheader {
1.258     albertel 10477:     unless ($env{'request.method'} eq 'GET') { return ''; }
1.216     albertel 10478:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime);
                   10479:     my $output .='<meta HTTP-EQUIV="Expires" CONTENT="'.$date.'" />
1.7       albertel 10480:                 <meta HTTP-EQUIV="Cache-control" CONTENT="no-cache" />
                   10481:                 <meta HTTP-EQUIV="Pragma" CONTENT="no-cache" />';
1.216     albertel 10482:     return $output;
1.7       albertel 10483: }
                   10484: 
1.112     bowersj2 10485: =pod
                   10486: 
1.648     raeburn  10487: =item * &no_cache($r) 
1.112     bowersj2 10488: 
                   10489: specifies header code to not have cache
                   10490: 
                   10491: =cut
                   10492: 
1.9       albertel 10493: sub no_cache {
1.216     albertel 10494:     my ($r) = @_;
                   10495:     if ($ENV{'REQUEST_METHOD'} ne 'GET' &&
1.258     albertel 10496: 	$env{'request.method'} ne 'GET') { return ''; }
1.216     albertel 10497:     my $date=strftime("%a, %d %b %Y %H:%M:%S GMT",gmtime(time));
                   10498:     $r->no_cache(1);
                   10499:     $r->header_out("Expires" => $date);
                   10500:     $r->header_out("Pragma" => "no-cache");
1.123     www      10501: }
                   10502: 
                   10503: sub content_type {
1.181     albertel 10504:     my ($r,$type,$charset) = @_;
1.299     foxr     10505:     if ($r) {
                   10506: 	#  Note that printout.pl calls this with undef for $r.
                   10507: 	&no_cache($r);
                   10508:     }
1.258     albertel 10509:     if ($env{'browser.mathml'} && $type eq 'text/html') { $type='text/xml'; }
1.181     albertel 10510:     unless ($charset) {
                   10511: 	$charset=&Apache::lonlocal::current_encoding;
                   10512:     }
                   10513:     if ($charset) { $type.='; charset='.$charset; }
                   10514:     if ($r) {
                   10515: 	$r->content_type($type);
                   10516:     } else {
                   10517: 	print("Content-type: $type\n\n");
                   10518:     }
1.9       albertel 10519: }
1.25      albertel 10520: 
1.112     bowersj2 10521: =pod
                   10522: 
1.648     raeburn  10523: =item * &add_to_env($name,$value) 
1.112     bowersj2 10524: 
1.258     albertel 10525: adds $name to the %env hash with value
1.112     bowersj2 10526: $value, if $name already exists, the entry is converted to an array
                   10527: reference and $value is added to the array.
                   10528: 
                   10529: =cut
                   10530: 
1.25      albertel 10531: sub add_to_env {
                   10532:   my ($name,$value)=@_;
1.258     albertel 10533:   if (defined($env{$name})) {
                   10534:     if (ref($env{$name})) {
1.25      albertel 10535:       #already have multiple values
1.258     albertel 10536:       push(@{ $env{$name} },$value);
1.25      albertel 10537:     } else {
                   10538:       #first time seeing multiple values, convert hash entry to an arrayref
1.258     albertel 10539:       my $first=$env{$name};
                   10540:       undef($env{$name});
                   10541:       push(@{ $env{$name} },$first,$value);
1.25      albertel 10542:     }
                   10543:   } else {
1.258     albertel 10544:     $env{$name}=$value;
1.25      albertel 10545:   }
1.31      albertel 10546: }
1.149     albertel 10547: 
                   10548: =pod
                   10549: 
1.648     raeburn  10550: =item * &get_env_multiple($name) 
1.149     albertel 10551: 
1.258     albertel 10552: gets $name from the %env hash, it seemlessly handles the cases where multiple
1.149     albertel 10553: values may be defined and end up as an array ref.
                   10554: 
                   10555: returns an array of values
                   10556: 
                   10557: =cut
                   10558: 
                   10559: sub get_env_multiple {
                   10560:     my ($name) = @_;
                   10561:     my @values;
1.258     albertel 10562:     if (defined($env{$name})) {
1.149     albertel 10563:         # exists is it an array
1.258     albertel 10564:         if (ref($env{$name})) {
                   10565:             @values=@{ $env{$name} };
1.149     albertel 10566:         } else {
1.258     albertel 10567:             $values[0]=$env{$name};
1.149     albertel 10568:         }
                   10569:     }
                   10570:     return(@values);
                   10571: }
                   10572: 
1.660     raeburn  10573: sub ask_for_embedded_content {
                   10574:     my ($actionurl,$state,$allfiles,$codebase,$args)=@_;
1.1071    raeburn  10575:     my (%subdependencies,%dependencies,%mapping,%existing,%newfiles,%pathchanges,
1.1075.2.11  raeburn  10576:         %currsubfile,%unused,$rem);
1.1071    raeburn  10577:     my $counter = 0;
                   10578:     my $numnew = 0;
1.987     raeburn  10579:     my $numremref = 0;
                   10580:     my $numinvalid = 0;
                   10581:     my $numpathchg = 0;
                   10582:     my $numexisting = 0;
1.1071    raeburn  10583:     my $numunused = 0;
                   10584:     my ($output,$upload_output,$toplevel,$url,$udom,$uname,$getpropath,$cdom,$cnum,
1.1075.2.53  raeburn  10585:         $fileloc,$filename,$delete_output,$modify_output,$title,$symb,$path,$navmap);
1.1071    raeburn  10586:     my $heading = &mt('Upload embedded files');
                   10587:     my $buttontext = &mt('Upload');
                   10588: 
1.1075.2.11  raeburn  10589:     if ($env{'request.course.id'}) {
1.1075.2.35  raeburn  10590:         if ($actionurl eq '/adm/dependencies') {
                   10591:             $navmap = Apache::lonnavmaps::navmap->new();
                   10592:         }
                   10593:         $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   10594:         $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
1.1075.2.11  raeburn  10595:     }
1.1075.2.35  raeburn  10596:     if (($actionurl eq '/adm/portfolio') ||
                   10597:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.984     raeburn  10598:         my $current_path='/';
                   10599:         if ($env{'form.currentpath'}) {
                   10600:             $current_path = $env{'form.currentpath'};
                   10601:         }
                   10602:         if ($actionurl eq '/adm/coursegrp_portfolio') {
1.1075.2.35  raeburn  10603:             $udom = $cdom;
                   10604:             $uname = $cnum;
1.984     raeburn  10605:             $url = '/userfiles/groups/'.$env{'form.group'}.'/portfolio';
                   10606:         } else {
                   10607:             $udom = $env{'user.domain'};
                   10608:             $uname = $env{'user.name'};
                   10609:             $url = '/userfiles/portfolio';
                   10610:         }
1.987     raeburn  10611:         $toplevel = $url.'/';
1.984     raeburn  10612:         $url .= $current_path;
                   10613:         $getpropath = 1;
1.987     raeburn  10614:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') ||
                   10615:              ($actionurl eq '/adm/imsimport')) { 
1.1022    www      10616:         my ($udom,$uname,$rest) = ($args->{'current_path'} =~ m{/priv/($match_domain)/($match_username)/?(.*)$});
1.1026    raeburn  10617:         $url = $Apache::lonnet::perlvar{'lonDocRoot'}."/priv/$udom/$uname/";
1.987     raeburn  10618:         $toplevel = $url;
1.984     raeburn  10619:         if ($rest ne '') {
1.987     raeburn  10620:             $url .= $rest;
                   10621:         }
                   10622:     } elsif ($actionurl eq '/adm/coursedocs') {
                   10623:         if (ref($args) eq 'HASH') {
1.1071    raeburn  10624:             $url = $args->{'docs_url'};
                   10625:             $toplevel = $url;
1.1075.2.11  raeburn  10626:             if ($args->{'context'} eq 'paste') {
                   10627:                 ($cdom,$cnum) = ($url =~ m{^\Q/uploaded/\E($match_domain)/($match_courseid)/});
                   10628:                 ($path) =
                   10629:                     ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10630:                 $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10631:                 $fileloc =~ s{^/}{};
                   10632:             }
1.1071    raeburn  10633:         }
                   10634:     } elsif ($actionurl eq '/adm/dependencies') {
                   10635:         if ($env{'request.course.id'} ne '') {
                   10636:             if (ref($args) eq 'HASH') {
                   10637:                 $url = $args->{'docs_url'};
                   10638:                 $title = $args->{'docs_title'};
1.1075.2.35  raeburn  10639:                 $toplevel = $url;
                   10640:                 unless ($toplevel =~ m{^/}) {
                   10641:                     $toplevel = "/$url";
                   10642:                 }
1.1075.2.11  raeburn  10643:                 ($rem) = ($toplevel =~ m{^(.+/)[^/]+$});
1.1075.2.35  raeburn  10644:                 if ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E)}) {
                   10645:                     $path = $1;
                   10646:                 } else {
                   10647:                     ($path) =
                   10648:                         ($toplevel =~ m{^(\Q/uploaded/$cdom/$cnum/\E(?:docs|supplemental)/(?:default|\d+)/\d+)/});
                   10649:                 }
1.1075.2.79  raeburn  10650:                 if ($toplevel=~/^\/*(uploaded|editupload)/) {
                   10651:                     $fileloc = $toplevel;
                   10652:                     $fileloc=~ s/^\s*(\S+)\s*$/$1/;
                   10653:                     my ($udom,$uname,$fname) =
                   10654:                         ($fileloc=~ m{^/+(?:uploaded|editupload)/+($match_domain)/+($match_name)/+(.*)$});
                   10655:                     $fileloc = propath($udom,$uname).'/userfiles/'.$fname;
                   10656:                 } else {
                   10657:                     $fileloc = &Apache::lonnet::filelocation('',$toplevel);
                   10658:                 }
1.1071    raeburn  10659:                 $fileloc =~ s{^/}{};
                   10660:                 ($filename) = ($fileloc =~ m{.+/([^/]+)$});
                   10661:                 $heading = &mt('Status of dependencies in [_1]',"$title ($filename)");
                   10662:             }
1.987     raeburn  10663:         }
1.1075.2.35  raeburn  10664:     } elsif ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10665:         $udom = $cdom;
                   10666:         $uname = $cnum;
                   10667:         $url = "/uploaded/$cdom/$cnum/portfolio/syllabus";
                   10668:         $toplevel = $url;
                   10669:         $path = $url;
                   10670:         $fileloc = &Apache::lonnet::filelocation('',$toplevel).'/';
                   10671:         $fileloc =~ s{^/}{};
                   10672:     }
                   10673:     foreach my $file (keys(%{$allfiles})) {
                   10674:         my $embed_file;
                   10675:         if (($path eq "/uploaded/$cdom/$cnum/portfolio/syllabus") && ($file =~ m{^\Q$path/\E(.+)$})) {
                   10676:             $embed_file = $1;
                   10677:         } else {
                   10678:             $embed_file = $file;
                   10679:         }
1.1075.2.55  raeburn  10680:         my ($absolutepath,$cleaned_file);
                   10681:         if ($embed_file =~ m{^\w+://}) {
                   10682:             $cleaned_file = $embed_file;
1.1075.2.47  raeburn  10683:             $newfiles{$cleaned_file} = 1;
                   10684:             $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10685:         } else {
1.1075.2.55  raeburn  10686:             $cleaned_file = &clean_path($embed_file);
1.987     raeburn  10687:             if ($embed_file =~ m{^/}) {
                   10688:                 $absolutepath = $embed_file;
                   10689:             }
1.1075.2.47  raeburn  10690:             if ($cleaned_file =~ m{/}) {
                   10691:                 my ($path,$fname) = ($cleaned_file =~ m{^(.+)/([^/]*)$});
1.987     raeburn  10692:                 $path = &check_for_traversal($path,$url,$toplevel);
                   10693:                 my $item = $fname;
                   10694:                 if ($path ne '') {
                   10695:                     $item = $path.'/'.$fname;
                   10696:                     $subdependencies{$path}{$fname} = 1;
                   10697:                 } else {
                   10698:                     $dependencies{$item} = 1;
                   10699:                 }
                   10700:                 if ($absolutepath) {
                   10701:                     $mapping{$item} = $absolutepath;
                   10702:                 } else {
                   10703:                     $mapping{$item} = $embed_file;
                   10704:                 }
                   10705:             } else {
                   10706:                 $dependencies{$embed_file} = 1;
                   10707:                 if ($absolutepath) {
1.1075.2.47  raeburn  10708:                     $mapping{$cleaned_file} = $absolutepath;
1.987     raeburn  10709:                 } else {
1.1075.2.47  raeburn  10710:                     $mapping{$cleaned_file} = $embed_file;
1.987     raeburn  10711:                 }
                   10712:             }
1.984     raeburn  10713:         }
                   10714:     }
1.1071    raeburn  10715:     my $dirptr = 16384;
1.984     raeburn  10716:     foreach my $path (keys(%subdependencies)) {
1.1071    raeburn  10717:         $currsubfile{$path} = {};
1.1075.2.35  raeburn  10718:         if (($actionurl eq '/adm/portfolio') ||
                   10719:             ($actionurl eq '/adm/coursegrp_portfolio')) { 
1.1021    raeburn  10720:             my ($sublistref,$listerror) =
                   10721:                 &Apache::lonnet::dirlist($url.$path,$udom,$uname,$getpropath);
                   10722:             if (ref($sublistref) eq 'ARRAY') {
                   10723:                 foreach my $line (@{$sublistref}) {
                   10724:                     my ($file_name,$rest) = split(/\&/,$line,2);
1.1071    raeburn  10725:                     $currsubfile{$path}{$file_name} = 1;
1.1021    raeburn  10726:                 }
1.984     raeburn  10727:             }
1.987     raeburn  10728:         } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10729:             if (opendir(my $dir,$url.'/'.$path)) {
                   10730:                 my @subdir_list = grep(!/^\./,readdir($dir));
1.1071    raeburn  10731:                 map {$currsubfile{$path}{$_} = 1;} @subdir_list;
                   10732:             }
1.1075.2.11  raeburn  10733:         } elsif (($actionurl eq '/adm/dependencies') ||
                   10734:                  (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10735:                   ($args->{'context'} eq 'paste')) ||
                   10736:                  ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10737:             if ($env{'request.course.id'} ne '') {
1.1075.2.35  raeburn  10738:                 my $dir;
                   10739:                 if ($actionurl eq "/public/$cdom/$cnum/syllabus") {
                   10740:                     $dir = $fileloc;
                   10741:                 } else {
                   10742:                     ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10743:                 }
1.1071    raeburn  10744:                 if ($dir ne '') {
                   10745:                     my ($sublistref,$listerror) =
                   10746:                         &Apache::lonnet::dirlist($dir.$path,$cdom,$cnum,$getpropath,undef,'/');
                   10747:                     if (ref($sublistref) eq 'ARRAY') {
                   10748:                         foreach my $line (@{$sublistref}) {
                   10749:                             my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,$size,
                   10750:                                 undef,$mtime)=split(/\&/,$line,12);
                   10751:                             unless (($testdir&$dirptr) ||
                   10752:                                     ($file_name =~ /^\.\.?$/)) {
                   10753:                                 $currsubfile{$path}{$file_name} = [$size,$mtime];
                   10754:                             }
                   10755:                         }
                   10756:                     }
                   10757:                 }
1.984     raeburn  10758:             }
                   10759:         }
                   10760:         foreach my $file (keys(%{$subdependencies{$path}})) {
1.1071    raeburn  10761:             if (exists($currsubfile{$path}{$file})) {
1.987     raeburn  10762:                 my $item = $path.'/'.$file;
                   10763:                 unless ($mapping{$item} eq $item) {
                   10764:                     $pathchanges{$item} = 1;
                   10765:                 }
                   10766:                 $existing{$item} = 1;
                   10767:                 $numexisting ++;
                   10768:             } else {
                   10769:                 $newfiles{$path.'/'.$file} = 1;
1.984     raeburn  10770:             }
                   10771:         }
1.1071    raeburn  10772:         if ($actionurl eq '/adm/dependencies') {
                   10773:             foreach my $path (keys(%currsubfile)) {
                   10774:                 if (ref($currsubfile{$path}) eq 'HASH') {
                   10775:                     foreach my $file (keys(%{$currsubfile{$path}})) {
                   10776:                          unless ($subdependencies{$path}{$file}) {
1.1075.2.11  raeburn  10777:                              next if (($rem ne '') &&
                   10778:                                       (($env{"httpref.$rem"."$path/$file"} ne '') ||
                   10779:                                        (ref($navmap) &&
                   10780:                                        (($navmap->getResourceByUrl($rem."$path/$file") ne '') ||
                   10781:                                         (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10782:                                          ($navmap->getResourceByUrl($rem."$path/$1")))))));
1.1071    raeburn  10783:                              $unused{$path.'/'.$file} = 1; 
                   10784:                          }
                   10785:                     }
                   10786:                 }
                   10787:             }
                   10788:         }
1.984     raeburn  10789:     }
1.987     raeburn  10790:     my %currfile;
1.1075.2.35  raeburn  10791:     if (($actionurl eq '/adm/portfolio') ||
                   10792:         ($actionurl eq '/adm/coursegrp_portfolio')) {
1.1021    raeburn  10793:         my ($dirlistref,$listerror) =
                   10794:             &Apache::lonnet::dirlist($url,$udom,$uname,$getpropath);
                   10795:         if (ref($dirlistref) eq 'ARRAY') {
                   10796:             foreach my $line (@{$dirlistref}) {
                   10797:                 my ($file_name,$rest) = split(/\&/,$line,2);
                   10798:                 $currfile{$file_name} = 1;
                   10799:             }
1.984     raeburn  10800:         }
1.987     raeburn  10801:     } elsif (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
1.984     raeburn  10802:         if (opendir(my $dir,$url)) {
1.987     raeburn  10803:             my @dir_list = grep(!/^\./,readdir($dir));
1.984     raeburn  10804:             map {$currfile{$_} = 1;} @dir_list;
                   10805:         }
1.1075.2.11  raeburn  10806:     } elsif (($actionurl eq '/adm/dependencies') ||
                   10807:              (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
1.1075.2.35  raeburn  10808:               ($args->{'context'} eq 'paste')) ||
                   10809:              ($actionurl eq "/public/$cdom/$cnum/syllabus")) {
1.1071    raeburn  10810:         if ($env{'request.course.id'} ne '') {
                   10811:             my ($dir) = ($fileloc =~ m{^(.+/)[^/]+$});
                   10812:             if ($dir ne '') {
                   10813:                 my ($dirlistref,$listerror) =
                   10814:                     &Apache::lonnet::dirlist($dir,$cdom,$cnum,$getpropath,undef,'/');
                   10815:                 if (ref($dirlistref) eq 'ARRAY') {
                   10816:                     foreach my $line (@{$dirlistref}) {
                   10817:                         my ($file_name,$dom,undef,$testdir,undef,undef,undef,undef,
                   10818:                             $size,undef,$mtime)=split(/\&/,$line,12);
                   10819:                         unless (($testdir&$dirptr) ||
                   10820:                                 ($file_name =~ /^\.\.?$/)) {
                   10821:                             $currfile{$file_name} = [$size,$mtime];
                   10822:                         }
                   10823:                     }
                   10824:                 }
                   10825:             }
                   10826:         }
1.984     raeburn  10827:     }
                   10828:     foreach my $file (keys(%dependencies)) {
1.1071    raeburn  10829:         if (exists($currfile{$file})) {
1.987     raeburn  10830:             unless ($mapping{$file} eq $file) {
                   10831:                 $pathchanges{$file} = 1;
                   10832:             }
                   10833:             $existing{$file} = 1;
                   10834:             $numexisting ++;
                   10835:         } else {
1.984     raeburn  10836:             $newfiles{$file} = 1;
                   10837:         }
                   10838:     }
1.1071    raeburn  10839:     foreach my $file (keys(%currfile)) {
                   10840:         unless (($file eq $filename) ||
                   10841:                 ($file eq $filename.'.bak') ||
                   10842:                 ($dependencies{$file})) {
1.1075.2.11  raeburn  10843:             if ($actionurl eq '/adm/dependencies') {
1.1075.2.35  raeburn  10844:                 unless ($toplevel =~ m{^\Q/uploaded/$cdom/$cnum/portfolio/syllabus\E}) {
                   10845:                     next if (($rem ne '') &&
                   10846:                              (($env{"httpref.$rem".$file} ne '') ||
                   10847:                               (ref($navmap) &&
                   10848:                               (($navmap->getResourceByUrl($rem.$file) ne '') ||
                   10849:                                (($file =~ /^(.*\.s?html?)\.bak$/i) &&
                   10850:                                 ($navmap->getResourceByUrl($rem.$1)))))));
                   10851:                 }
1.1075.2.11  raeburn  10852:             }
1.1071    raeburn  10853:             $unused{$file} = 1;
                   10854:         }
                   10855:     }
1.1075.2.11  raeburn  10856:     if (($actionurl eq '/adm/coursedocs') && (ref($args) eq 'HASH') &&
                   10857:         ($args->{'context'} eq 'paste')) {
                   10858:         $counter = scalar(keys(%existing));
                   10859:         $numpathchg = scalar(keys(%pathchanges));
                   10860:         return ($output,$counter,$numpathchg,\%existing);
1.1075.2.35  raeburn  10861:     } elsif (($actionurl eq "/public/$cdom/$cnum/syllabus") &&
                   10862:              (ref($args) eq 'HASH') && ($args->{'context'} eq 'rewrites')) {
                   10863:         $counter = scalar(keys(%existing));
                   10864:         $numpathchg = scalar(keys(%pathchanges));
                   10865:         return ($output,$counter,$numpathchg,\%existing,\%mapping);
1.1075.2.11  raeburn  10866:     }
1.984     raeburn  10867:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%newfiles)) {
1.1071    raeburn  10868:         if ($actionurl eq '/adm/dependencies') {
                   10869:             next if ($embed_file =~ m{^\w+://});
                   10870:         }
1.660     raeburn  10871:         $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10872:                           '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
1.1071    raeburn  10873:                           '<span class="LC_filename">'.$embed_file.'</span>';
1.987     raeburn  10874:         unless ($mapping{$embed_file} eq $embed_file) {
1.1075.2.35  raeburn  10875:             $upload_output .= '<br /><span class="LC_info" style="font-size:smaller;">'.
                   10876:                               &mt('changed from: [_1]',$mapping{$embed_file}).'</span>';
1.987     raeburn  10877:         }
1.1075.2.35  raeburn  10878:         $upload_output .= '</td>';
1.1071    raeburn  10879:         if ($args->{'ignore_remote_references'} && $embed_file =~ m{^\w+://}) { 
1.1075.2.35  raeburn  10880:             $upload_output.='<td align="right">'.
                   10881:                             '<span class="LC_info LC_fontsize_medium">'.
                   10882:                             &mt("URL points to web address").'</span>';
1.987     raeburn  10883:             $numremref++;
1.660     raeburn  10884:         } elsif ($args->{'error_on_invalid_names'}
                   10885:             && $embed_file ne &Apache::lonnet::clean_filename($embed_file,{'keep_path' => 1,})) {
1.1075.2.35  raeburn  10886:             $upload_output.='<td align="right"><span class="LC_warning">'.
                   10887:                             &mt('Invalid characters').'</span>';
1.987     raeburn  10888:             $numinvalid++;
1.660     raeburn  10889:         } else {
1.1075.2.35  raeburn  10890:             $upload_output .= '<td>'.
                   10891:                               &embedded_file_element('upload_embedded',$counter,
1.987     raeburn  10892:                                                      $embed_file,\%mapping,
1.1071    raeburn  10893:                                                      $allfiles,$codebase,'upload');
                   10894:             $counter ++;
                   10895:             $numnew ++;
1.987     raeburn  10896:         }
                   10897:         $upload_output .= '</td>'.&Apache::loncommon::end_data_table_row()."\n";
                   10898:     }
                   10899:     foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%existing)) {
1.1071    raeburn  10900:         if ($actionurl eq '/adm/dependencies') {
                   10901:             my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$embed_file);
                   10902:             $modify_output .= &start_data_table_row().
                   10903:                               '<td><a href="'.$path.'/'.$embed_file.'" style="text-decoration:none;">'.
                   10904:                               '<img src="'.&icon($embed_file).'" border="0" />'.
                   10905:                               '&nbsp;<span class="LC_filename">'.$embed_file.'</span></a></td>'.
                   10906:                               '<td>'.$size.'</td>'.
                   10907:                               '<td>'.$mtime.'</td>'.
                   10908:                               '<td><label><input type="checkbox" name="mod_upload_dep" '.
                   10909:                               'onclick="toggleBrowse('."'$counter'".')" id="mod_upload_dep_'.
                   10910:                               $counter.'" value="'.$counter.'" />'.&mt('Yes').'</label>'.
                   10911:                               '<div id="moduploaddep_'.$counter.'" style="display:none;">'.
                   10912:                               &embedded_file_element('upload_embedded',$counter,
                   10913:                                                      $embed_file,\%mapping,
                   10914:                                                      $allfiles,$codebase,'modify').
                   10915:                               '</div></td>'.
                   10916:                               &end_data_table_row()."\n";
                   10917:             $counter ++;
                   10918:         } else {
                   10919:             $upload_output .= &start_data_table_row().
1.1075.2.35  raeburn  10920:                               '<td valign="top"><img src="'.&icon($embed_file).'" />&nbsp;'.
                   10921:                               '<span class="LC_filename">'.$embed_file.'</span></td>'.
                   10922:                               '<td align="right"><span class="LC_info LC_fontsize_medium">'.&mt('Already exists').'</span></td>'.
1.1071    raeburn  10923:                               &Apache::loncommon::end_data_table_row()."\n";
                   10924:         }
                   10925:     }
                   10926:     my $delidx = $counter;
                   10927:     foreach my $oldfile (sort {lc($a) cmp lc($b)} keys(%unused)) {
                   10928:         my ($size,$mtime) = &get_dependency_details(\%currfile,\%currsubfile,$oldfile);
                   10929:         $delete_output .= &start_data_table_row().
                   10930:                           '<td><img src="'.&icon($oldfile).'" />'.
                   10931:                           '&nbsp;<span class="LC_filename">'.$oldfile.'</span></td>'.
                   10932:                           '<td>'.$size.'</td>'.
                   10933:                           '<td>'.$mtime.'</td>'.
                   10934:                           '<td><label><input type="checkbox" name="del_upload_dep" '.
                   10935:                           ' value="'.$delidx.'" />'.&mt('Yes').'</label>'.
                   10936:                           &embedded_file_element('upload_embedded',$delidx,
                   10937:                                                  $oldfile,\%mapping,$allfiles,
                   10938:                                                  $codebase,'delete').'</td>'.
                   10939:                           &end_data_table_row()."\n"; 
                   10940:         $numunused ++;
                   10941:         $delidx ++;
1.987     raeburn  10942:     }
                   10943:     if ($upload_output) {
                   10944:         $upload_output = &start_data_table().
                   10945:                          $upload_output.
                   10946:                          &end_data_table()."\n";
                   10947:     }
1.1071    raeburn  10948:     if ($modify_output) {
                   10949:         $modify_output = &start_data_table().
                   10950:                          &start_data_table_header_row().
                   10951:                          '<th>'.&mt('File').'</th>'.
                   10952:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10953:                          '<th>'.&mt('Modified').'</th>'.
                   10954:                          '<th>'.&mt('Upload replacement?').'</th>'.
                   10955:                          &end_data_table_header_row().
                   10956:                          $modify_output.
                   10957:                          &end_data_table()."\n";
                   10958:     }
                   10959:     if ($delete_output) {
                   10960:         $delete_output = &start_data_table().
                   10961:                          &start_data_table_header_row().
                   10962:                          '<th>'.&mt('File').'</th>'.
                   10963:                          '<th>'.&mt('Size (KB)').'</th>'.
                   10964:                          '<th>'.&mt('Modified').'</th>'.
                   10965:                          '<th>'.&mt('Delete?').'</th>'.
                   10966:                          &end_data_table_header_row().
                   10967:                          $delete_output.
                   10968:                          &end_data_table()."\n";
                   10969:     }
1.987     raeburn  10970:     my $applies = 0;
                   10971:     if ($numremref) {
                   10972:         $applies ++;
                   10973:     }
                   10974:     if ($numinvalid) {
                   10975:         $applies ++;
                   10976:     }
                   10977:     if ($numexisting) {
                   10978:         $applies ++;
                   10979:     }
1.1071    raeburn  10980:     if ($counter || $numunused) {
1.987     raeburn  10981:         $output = '<form name="upload_embedded" action="'.$actionurl.'"'.
                   10982:                   ' method="post" enctype="multipart/form-data">'."\n".
1.1071    raeburn  10983:                   $state.'<h3>'.$heading.'</h3>'; 
                   10984:         if ($actionurl eq '/adm/dependencies') {
                   10985:             if ($numnew) {
                   10986:                 $output .= '<h4>'.&mt('Missing dependencies').'</h4>'.
                   10987:                            '<p>'.&mt('The following files need to be uploaded.').'</p>'."\n".
                   10988:                            $upload_output.'<br />'."\n";
                   10989:             }
                   10990:             if ($numexisting) {
                   10991:                 $output .= '<h4>'.&mt('Uploaded dependencies (in use)').'</h4>'.
                   10992:                            '<p>'.&mt('Upload a new file to replace the one currently in use.').'</p>'."\n".
                   10993:                            $modify_output.'<br />'."\n";
                   10994:                            $buttontext = &mt('Save changes');
                   10995:             }
                   10996:             if ($numunused) {
                   10997:                 $output .= '<h4>'.&mt('Unused files').'</h4>'.
                   10998:                            '<p>'.&mt('The following uploaded files are no longer used.').'</p>'."\n".
                   10999:                            $delete_output.'<br />'."\n";
                   11000:                            $buttontext = &mt('Save changes');
                   11001:             }
                   11002:         } else {
                   11003:             $output .= $upload_output.'<br />'."\n";
                   11004:         }
                   11005:         $output .= '<input type ="hidden" name="number_embedded_items" value="'.
                   11006:                    $counter.'" />'."\n";
                   11007:         if ($actionurl eq '/adm/dependencies') { 
                   11008:             $output .= '<input type ="hidden" name="number_newemb_items" value="'.
                   11009:                        $numnew.'" />'."\n";
                   11010:         } elsif ($actionurl eq '') {
1.987     raeburn  11011:             $output .=  '<input type="hidden" name="phase" value="three" />';
                   11012:         }
                   11013:     } elsif ($applies) {
                   11014:         $output = '<b>'.&mt('Referenced files').'</b>:<br />';
                   11015:         if ($applies > 1) {
                   11016:             $output .=  
1.1075.2.35  raeburn  11017:                 &mt('No dependencies need to be uploaded, as one of the following applies to each reference:').'<ul>';
1.987     raeburn  11018:             if ($numremref) {
                   11019:                 $output .= '<li>'.&mt('reference is to a URL which points to another server').'</li>'."\n";
                   11020:             }
                   11021:             if ($numinvalid) {
                   11022:                 $output .= '<li>'.&mt('reference is to file with a name containing invalid characters').'</li>'."\n";
                   11023:             }
                   11024:             if ($numexisting) {
                   11025:                 $output .= '<li>'.&mt('reference is to an existing file at the specified location').'</li>'."\n";
                   11026:             }
                   11027:             $output .= '</ul><br />';
                   11028:         } elsif ($numremref) {
                   11029:             $output .= '<p>'.&mt('None to upload, as all references are to URLs pointing to another server.').'</p>';
                   11030:         } elsif ($numinvalid) {
                   11031:             $output .= '<p>'.&mt('None to upload, as all references are to files with names containing invalid characters.').'</p>';
                   11032:         } elsif ($numexisting) {
                   11033:             $output .= '<p>'.&mt('None to upload, as all references are to existing files.').'</p>';
                   11034:         }
                   11035:         $output .= $upload_output.'<br />';
                   11036:     }
                   11037:     my ($pathchange_output,$chgcount);
1.1071    raeburn  11038:     $chgcount = $counter;
1.987     raeburn  11039:     if (keys(%pathchanges) > 0) {
                   11040:         foreach my $embed_file (sort {lc($a) cmp lc($b)} keys(%pathchanges)) {
1.1071    raeburn  11041:             if ($counter) {
1.987     raeburn  11042:                 $output .= &embedded_file_element('pathchange',$chgcount,
                   11043:                                                   $embed_file,\%mapping,
1.1071    raeburn  11044:                                                   $allfiles,$codebase,'change');
1.987     raeburn  11045:             } else {
                   11046:                 $pathchange_output .= 
                   11047:                     &start_data_table_row().
                   11048:                     '<td><input type ="checkbox" name="namechange" value="'.
                   11049:                     $chgcount.'" checked="checked" /></td>'.
                   11050:                     '<td>'.$mapping{$embed_file}.'</td>'.
                   11051:                     '<td>'.$embed_file.
                   11052:                     &embedded_file_element('pathchange',$numpathchg,$embed_file,
1.1071    raeburn  11053:                                            \%mapping,$allfiles,$codebase,'change').
1.987     raeburn  11054:                     '</td>'.&end_data_table_row();
1.660     raeburn  11055:             }
1.987     raeburn  11056:             $numpathchg ++;
                   11057:             $chgcount ++;
1.660     raeburn  11058:         }
                   11059:     }
1.1075.2.35  raeburn  11060:     if (($counter) || ($numunused)) {
1.987     raeburn  11061:         if ($numpathchg) {
                   11062:             $output .= '<input type ="hidden" name="number_pathchange_items" value="'.
                   11063:                        $numpathchg.'" />'."\n";
                   11064:         }
                   11065:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank') || 
                   11066:             ($actionurl eq '/adm/imsimport')) {
                   11067:             $output .= '<input type="hidden" name="phase" value="three" />'."\n";
                   11068:         } elsif ($actionurl eq '/adm/portfolio' || $actionurl eq '/adm/coursegrp_portfolio') {
                   11069:             $output .= '<input type="hidden" name="action" value="upload_embedded" />';
1.1071    raeburn  11070:         } elsif ($actionurl eq '/adm/dependencies') {
                   11071:             $output .= '<input type="hidden" name="action" value="process_changes" />';
1.987     raeburn  11072:         }
1.1075.2.35  raeburn  11073:         $output .= '<input type ="submit" value="'.$buttontext.'" />'."\n".'</form>'."\n";
1.987     raeburn  11074:     } elsif ($numpathchg) {
                   11075:         my %pathchange = ();
                   11076:         $output .= &modify_html_form('pathchange',$actionurl,$state,\%pathchange,$pathchange_output);
                   11077:         if (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11078:             $output .= '<p>'.&mt('or').'</p>'; 
1.1075.2.35  raeburn  11079:         }
1.987     raeburn  11080:     }
1.1071    raeburn  11081:     return ($output,$counter,$numpathchg);
1.987     raeburn  11082: }
                   11083: 
1.1075.2.47  raeburn  11084: =pod
                   11085: 
                   11086: =item * clean_path($name)
                   11087: 
                   11088: Performs clean-up of directories, subdirectories and filename in an
                   11089: embedded object, referenced in an HTML file which is being uploaded
                   11090: to a course or portfolio, where
                   11091: "Upload embedded images/multimedia files if HTML file" checkbox was
                   11092: checked.
                   11093: 
                   11094: Clean-up is similar to replacements in lonnet::clean_filename()
                   11095: except each / between sub-directory and next level is preserved.
                   11096: 
                   11097: =cut
                   11098: 
                   11099: sub clean_path {
                   11100:     my ($embed_file) = @_;
                   11101:     $embed_file =~s{^/+}{};
                   11102:     my @contents;
                   11103:     if ($embed_file =~ m{/}) {
                   11104:         @contents = split(/\//,$embed_file);
                   11105:     } else {
                   11106:         @contents = ($embed_file);
                   11107:     }
                   11108:     my $lastidx = scalar(@contents)-1;
                   11109:     for (my $i=0; $i<=$lastidx; $i++) {
                   11110:         $contents[$i]=~s{\\}{/}g;
                   11111:         $contents[$i]=~s/\s+/\_/g;
                   11112:         $contents[$i]=~s{[^/\w\.\-]}{}g;
                   11113:         if ($i == $lastidx) {
                   11114:             $contents[$i]=~s/\.(\d+)(?=\.)/_$1/g;
                   11115:         }
                   11116:     }
                   11117:     if ($lastidx > 0) {
                   11118:         return join('/',@contents);
                   11119:     } else {
                   11120:         return $contents[0];
                   11121:     }
                   11122: }
                   11123: 
1.987     raeburn  11124: sub embedded_file_element {
1.1071    raeburn  11125:     my ($context,$num,$embed_file,$mapping,$allfiles,$codebase,$type) = @_;
1.987     raeburn  11126:     return unless ((ref($mapping) eq 'HASH') && (ref($allfiles) eq 'HASH') &&
                   11127:                    (ref($codebase) eq 'HASH'));
                   11128:     my $output;
1.1071    raeburn  11129:     if (($context eq 'upload_embedded') && ($type ne 'delete')) {
1.987     raeburn  11130:        $output = '<input name="embedded_item_'.$num.'" type="file" value="" />'."\n";
                   11131:     }
                   11132:     $output .= '<input name="embedded_orig_'.$num.'" type="hidden" value="'.
                   11133:                &escape($embed_file).'" />';
                   11134:     unless (($context eq 'upload_embedded') && 
                   11135:             ($mapping->{$embed_file} eq $embed_file)) {
                   11136:         $output .='
                   11137:         <input name="embedded_ref_'.$num.'" type="hidden" value="'.&escape($mapping->{$embed_file}).'" />';
                   11138:     }
                   11139:     my $attrib;
                   11140:     if (ref($allfiles->{$mapping->{$embed_file}}) eq 'ARRAY') {
                   11141:         $attrib = &escape(join(':',@{$allfiles->{$mapping->{$embed_file}}}));
                   11142:     }
                   11143:     $output .=
                   11144:         "\n\t\t".
                   11145:         '<input name="embedded_attrib_'.$num.'" type="hidden" value="'.
                   11146:         $attrib.'" />';
                   11147:     if (exists($codebase->{$mapping->{$embed_file}})) {
                   11148:         $output .=
                   11149:             "\n\t\t".
                   11150:             '<input name="codebase_'.$num.'" type="hidden" value="'.
                   11151:             &escape($codebase->{$mapping->{$embed_file}}).'" />';
1.984     raeburn  11152:     }
1.987     raeburn  11153:     return $output;
1.660     raeburn  11154: }
                   11155: 
1.1071    raeburn  11156: sub get_dependency_details {
                   11157:     my ($currfile,$currsubfile,$embed_file) = @_;
                   11158:     my ($size,$mtime,$showsize,$showmtime);
                   11159:     if ((ref($currfile) eq 'HASH') && (ref($currsubfile))) {
                   11160:         if ($embed_file =~ m{/}) {
                   11161:             my ($path,$fname) = split(/\//,$embed_file);
                   11162:             if (ref($currsubfile->{$path}{$fname}) eq 'ARRAY') {
                   11163:                 ($size,$mtime) = @{$currsubfile->{$path}{$fname}};
                   11164:             }
                   11165:         } else {
                   11166:             if (ref($currfile->{$embed_file}) eq 'ARRAY') {
                   11167:                 ($size,$mtime) = @{$currfile->{$embed_file}};
                   11168:             }
                   11169:         }
                   11170:         $showsize = $size/1024.0;
                   11171:         $showsize = sprintf("%.1f",$showsize);
                   11172:         if ($mtime > 0) {
                   11173:             $showmtime = &Apache::lonlocal::locallocaltime($mtime);
                   11174:         }
                   11175:     }
                   11176:     return ($showsize,$showmtime);
                   11177: }
                   11178: 
                   11179: sub ask_embedded_js {
                   11180:     return <<"END";
                   11181: <script type="text/javascript"">
                   11182: // <![CDATA[
                   11183: function toggleBrowse(counter) {
                   11184:     var chkboxid = document.getElementById('mod_upload_dep_'+counter);
                   11185:     var fileid = document.getElementById('embedded_item_'+counter);
                   11186:     var uploaddivid = document.getElementById('moduploaddep_'+counter);
                   11187:     if (chkboxid.checked == true) {
                   11188:         uploaddivid.style.display='block';
                   11189:     } else {
                   11190:         uploaddivid.style.display='none';
                   11191:         fileid.value = '';
                   11192:     }
                   11193: }
                   11194: // ]]>
                   11195: </script>
                   11196: 
                   11197: END
                   11198: }
                   11199: 
1.661     raeburn  11200: sub upload_embedded {
                   11201:     my ($context,$dirpath,$uname,$udom,$dir_root,$url_root,$group,$disk_quota,
1.987     raeburn  11202:         $current_disk_usage,$hiddenstate,$actionurl) = @_;
                   11203:     my (%pathchange,$output,$modifyform,$footer,$returnflag);
1.661     raeburn  11204:     for (my $i=0; $i<$env{'form.number_embedded_items'}; $i++) {
                   11205:         next if (!exists($env{'form.embedded_item_'.$i.'.filename'}));
                   11206:         my $orig_uploaded_filename =
                   11207:             $env{'form.embedded_item_'.$i.'.filename'};
1.987     raeburn  11208:         foreach my $type ('orig','ref','attrib','codebase') {
                   11209:             if ($env{'form.embedded_'.$type.'_'.$i} ne '') {
                   11210:                 $env{'form.embedded_'.$type.'_'.$i} =
                   11211:                     &unescape($env{'form.embedded_'.$type.'_'.$i});
                   11212:             }
                   11213:         }
1.661     raeburn  11214:         my ($path,$fname) =
                   11215:             ($env{'form.embedded_orig_'.$i} =~ m{(.*/)([^/]*)});
                   11216:         # no path, whole string is fname
                   11217:         if (!$fname) { $fname = $env{'form.embedded_orig_'.$i} };
                   11218:         $fname = &Apache::lonnet::clean_filename($fname);
                   11219:         # See if there is anything left
                   11220:         next if ($fname eq '');
                   11221: 
                   11222:         # Check if file already exists as a file or directory.
                   11223:         my ($state,$msg);
                   11224:         if ($context eq 'portfolio') {
                   11225:             my $port_path = $dirpath;
                   11226:             if ($group ne '') {
                   11227:                 $port_path = "groups/$group/$port_path";
                   11228:             }
1.987     raeburn  11229:             ($state,$msg) = &check_for_upload($env{'form.currentpath'}.$path,
                   11230:                                               $fname,$group,'embedded_item_'.$i,
1.661     raeburn  11231:                                               $dir_root,$port_path,$disk_quota,
                   11232:                                               $current_disk_usage,$uname,$udom);
                   11233:             if ($state eq 'will_exceed_quota'
1.984     raeburn  11234:                 || $state eq 'file_locked') {
1.661     raeburn  11235:                 $output .= $msg;
                   11236:                 next;
                   11237:             }
                   11238:         } elsif (($context eq 'author') || ($context eq 'testbank')) {
                   11239:             ($state,$msg) = &check_for_existing($path,$fname,'embedded_item_'.$i);
                   11240:             if ($state eq 'exists') {
                   11241:                 $output .= $msg;
                   11242:                 next;
                   11243:             }
                   11244:         }
                   11245:         # Check if extension is valid
                   11246:         if (($fname =~ /\.(\w+)$/) &&
                   11247:             (&Apache::loncommon::fileembstyle($1) eq 'hdn')) {
1.1075.2.53  raeburn  11248:             $output .= &mt('Invalid file extension ([_1]) - reserved for internal use.',$1)
                   11249:                       .' '.&mt('Rename the file with a different extension and re-upload.').'<br />';
1.661     raeburn  11250:             next;
                   11251:         } elsif (($fname =~ /\.(\w+)$/) &&
                   11252:                  (!defined(&Apache::loncommon::fileembstyle($1)))) {
1.987     raeburn  11253:             $output .= &mt('Unrecognized file extension ([_1]) - rename the file with a proper extension and re-upload.',$1).'<br />';
1.661     raeburn  11254:             next;
                   11255:         } elsif ($fname=~/\.(\d+)\.(\w+)$/) {
1.1075.2.34  raeburn  11256:             $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  11257:             next;
                   11258:         }
                   11259:         $env{'form.embedded_item_'.$i.'.filename'}=$fname;
1.1075.2.35  raeburn  11260:         my $subdir = $path;
                   11261:         $subdir =~ s{/+$}{};
1.661     raeburn  11262:         if ($context eq 'portfolio') {
1.984     raeburn  11263:             my $result;
                   11264:             if ($state eq 'existingfile') {
                   11265:                 $result=
                   11266:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'existingfile',
1.1075.2.35  raeburn  11267:                                                     $dirpath.$env{'form.currentpath'}.$subdir);
1.661     raeburn  11268:             } else {
1.984     raeburn  11269:                 $result=
                   11270:                     &Apache::lonnet::userfileupload('embedded_item_'.$i,'',
1.987     raeburn  11271:                                                     $dirpath.
1.1075.2.35  raeburn  11272:                                                     $env{'form.currentpath'}.$subdir);
1.984     raeburn  11273:                 if ($result !~ m|^/uploaded/|) {
                   11274:                     $output .= '<span class="LC_error">'
                   11275:                                .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11276:                                ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11277:                                .'</span><br />';
                   11278:                     next;
                   11279:                 } else {
1.987     raeburn  11280:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11281:                                $path.$fname.'</span>').'<br />';     
1.984     raeburn  11282:                 }
1.661     raeburn  11283:             }
1.1075.2.35  raeburn  11284:         } elsif (($context eq 'coursedoc') || ($context eq 'syllabus')) {
                   11285:             my $extendedsubdir = $dirpath.'/'.$subdir;
                   11286:             $extendedsubdir =~ s{/+$}{};
1.987     raeburn  11287:             my $result =
1.1075.2.35  raeburn  11288:                 &Apache::lonnet::userfileupload('embedded_item_'.$i,$context,$extendedsubdir);
1.987     raeburn  11289:             if ($result !~ m|^/uploaded/|) {
                   11290:                 $output .= '<span class="LC_error">'
                   11291:                            .&mt('An error occurred ([_1]) while trying to upload [_2] for embedded element [_3].'
                   11292:                            ,$result,$orig_uploaded_filename,$env{'form.embedded_orig_'.$i})
                   11293:                            .'</span><br />';
                   11294:                     next;
                   11295:             } else {
                   11296:                 $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11297:                            $path.$fname.'</span>').'<br />';
1.1075.2.35  raeburn  11298:                 if ($context eq 'syllabus') {
                   11299:                     &Apache::lonnet::make_public_indefinitely($result);
                   11300:                 }
1.987     raeburn  11301:             }
1.661     raeburn  11302:         } else {
                   11303: # Save the file
                   11304:             my $target = $env{'form.embedded_item_'.$i};
                   11305:             my $fullpath = $dir_root.$dirpath.'/'.$path;
                   11306:             my $dest = $fullpath.$fname;
                   11307:             my $url = $url_root.$dirpath.'/'.$path.$fname;
1.1027    raeburn  11308:             my @parts=split(/\//,"$dirpath/$path");
1.661     raeburn  11309:             my $count;
                   11310:             my $filepath = $dir_root;
1.1027    raeburn  11311:             foreach my $subdir (@parts) {
                   11312:                 $filepath .= "/$subdir";
                   11313:                 if (!-e $filepath) {
1.661     raeburn  11314:                     mkdir($filepath,0770);
                   11315:                 }
                   11316:             }
                   11317:             my $fh;
                   11318:             if (!open($fh,'>'.$dest)) {
                   11319:                 &Apache::lonnet::logthis('Failed to create '.$dest);
                   11320:                 $output .= '<span class="LC_error">'.
1.1071    raeburn  11321:                            &mt('An error occurred while trying to upload [_1] for embedded element [_2].',
                   11322:                                $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11323:                            '</span><br />';
                   11324:             } else {
                   11325:                 if (!print $fh $env{'form.embedded_item_'.$i}) {
                   11326:                     &Apache::lonnet::logthis('Failed to write to '.$dest);
                   11327:                     $output .= '<span class="LC_error">'.
1.1071    raeburn  11328:                               &mt('An error occurred while writing the file [_1] for embedded element [_2].',
                   11329:                                   $orig_uploaded_filename,$env{'form.embedded_orig_'.$i}).
1.661     raeburn  11330:                               '</span><br />';
                   11331:                 } else {
1.987     raeburn  11332:                     $output .= &mt('Uploaded [_1]','<span class="LC_filename">'.
                   11333:                                $url.'</span>').'<br />';
                   11334:                     unless ($context eq 'testbank') {
                   11335:                         $footer .= &mt('View embedded file: [_1]',
                   11336:                                        '<a href="'.$url.'">'.$fname.'</a>').'<br />';
                   11337:                     }
                   11338:                 }
                   11339:                 close($fh);
                   11340:             }
                   11341:         }
                   11342:         if ($env{'form.embedded_ref_'.$i}) {
                   11343:             $pathchange{$i} = 1;
                   11344:         }
                   11345:     }
                   11346:     if ($output) {
                   11347:         $output = '<p>'.$output.'</p>';
                   11348:     }
                   11349:     $output .= &modify_html_form('upload_embedded',$actionurl,$hiddenstate,\%pathchange);
                   11350:     $returnflag = 'ok';
1.1071    raeburn  11351:     my $numpathchgs = scalar(keys(%pathchange));
                   11352:     if ($numpathchgs > 0) {
1.987     raeburn  11353:         if ($context eq 'portfolio') {
                   11354:             $output .= '<p>'.&mt('or').'</p>';
                   11355:         } elsif ($context eq 'testbank') {
1.1071    raeburn  11356:             $output .=  '<p>'.&mt('Or [_1]continue[_2] the testbank import without modifying the reference(s).',
                   11357:                                   '<a href="javascript:document.testbankForm.submit();">','</a>').'</p>';
1.987     raeburn  11358:             $returnflag = 'modify_orightml';
                   11359:         }
                   11360:     }
1.1071    raeburn  11361:     return ($output.$footer,$returnflag,$numpathchgs);
1.987     raeburn  11362: }
                   11363: 
                   11364: sub modify_html_form {
                   11365:     my ($context,$actionurl,$hiddenstate,$pathchange,$pathchgtable) = @_;
                   11366:     my $end = 0;
                   11367:     my $modifyform;
                   11368:     if ($context eq 'upload_embedded') {
                   11369:         return unless (ref($pathchange) eq 'HASH');
                   11370:         if ($env{'form.number_embedded_items'}) {
                   11371:             $end += $env{'form.number_embedded_items'};
                   11372:         }
                   11373:         if ($env{'form.number_pathchange_items'}) {
                   11374:             $end += $env{'form.number_pathchange_items'};
                   11375:         }
                   11376:         if ($end) {
                   11377:             for (my $i=0; $i<$end; $i++) {
                   11378:                 if ($i < $env{'form.number_embedded_items'}) {
                   11379:                     next unless($pathchange->{$i});
                   11380:                 }
                   11381:                 $modifyform .=
                   11382:                     &start_data_table_row().
                   11383:                     '<td><input type ="checkbox" name="namechange" value="'.$i.'" '.
                   11384:                     'checked="checked" /></td>'.
                   11385:                     '<td>'.$env{'form.embedded_ref_'.$i}.
                   11386:                     '<input type="hidden" name="embedded_ref_'.$i.'" value="'.
                   11387:                     &escape($env{'form.embedded_ref_'.$i}).'" />'.
                   11388:                     '<input type="hidden" name="embedded_codebase_'.$i.'" value="'.
                   11389:                     &escape($env{'form.embedded_codebase_'.$i}).'" />'.
                   11390:                     '<input type="hidden" name="embedded_attrib_'.$i.'" value="'.
                   11391:                     &escape($env{'form.embedded_attrib_'.$i}).'" /></td>'.
                   11392:                     '<td>'.$env{'form.embedded_orig_'.$i}.
                   11393:                     '<input type="hidden" name="embedded_orig_'.$i.'" value="'.
                   11394:                     &escape($env{'form.embedded_orig_'.$i}).'" /></td>'.
                   11395:                     &end_data_table_row();
1.1071    raeburn  11396:             }
1.987     raeburn  11397:         }
                   11398:     } else {
                   11399:         $modifyform = $pathchgtable;
                   11400:         if (($actionurl eq '/adm/upload') || ($actionurl eq '/adm/testbank')) {
                   11401:             $hiddenstate .= '<input type="hidden" name="phase" value="four" />';
                   11402:         } elsif (($actionurl eq '/adm/portfolio') || ($actionurl eq '/adm/coursegrp_portfolio')) {
                   11403:             $hiddenstate .= '<input type="hidden" name="action" value="modify_orightml" />';
                   11404:         }
                   11405:     }
                   11406:     if ($modifyform) {
1.1071    raeburn  11407:         if ($actionurl eq '/adm/dependencies') {
                   11408:             $hiddenstate .= '<input type="hidden" name="action" value="modifyhrefs" />';
                   11409:         }
1.987     raeburn  11410:         return '<h3>'.&mt('Changes in content of HTML file required').'</h3>'."\n".
                   11411:                '<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".
                   11412:                '<li>'.&mt('For consistency between the reference(s) and the location of the corresponding stored file within LON-CAPA.').'</li>'."\n".
                   11413:                '<li>'.&mt('To change absolute paths to relative paths, or replace directory traversal via "../" within the original reference.').'</li>'."\n".
                   11414:                '</ol></p>'."\n".'<p>'.
                   11415:                &mt('LON-CAPA can make the required changes to your HTML file.').'</p>'."\n".
                   11416:                '<form method="post" name="refchanger" action="'.$actionurl.'">'.
                   11417:                &start_data_table()."\n".
                   11418:                &start_data_table_header_row().
                   11419:                '<th>'.&mt('Change?').'</th>'.
                   11420:                '<th>'.&mt('Current reference').'</th>'.
                   11421:                '<th>'.&mt('Required reference').'</th>'.
                   11422:                &end_data_table_header_row()."\n".
                   11423:                $modifyform.
                   11424:                &end_data_table().'<br />'."\n".$hiddenstate.
                   11425:                '<input type="submit" name="pathchanges" value="'.&mt('Modify HTML file').'" />'.
                   11426:                '</form>'."\n";
                   11427:     }
                   11428:     return;
                   11429: }
                   11430: 
                   11431: sub modify_html_refs {
1.1075.2.35  raeburn  11432:     my ($context,$dirpath,$uname,$udom,$dir_root,$url) = @_;
1.987     raeburn  11433:     my $container;
                   11434:     if ($context eq 'portfolio') {
                   11435:         $container = $env{'form.container'};
                   11436:     } elsif ($context eq 'coursedoc') {
                   11437:         $container = $env{'form.primaryurl'};
1.1071    raeburn  11438:     } elsif ($context eq 'manage_dependencies') {
                   11439:         (undef,undef,$container) = &Apache::lonnet::decode_symb($env{'form.symb'});
                   11440:         $container = "/$container";
1.1075.2.35  raeburn  11441:     } elsif ($context eq 'syllabus') {
                   11442:         $container = $url;
1.987     raeburn  11443:     } else {
1.1027    raeburn  11444:         $container = $Apache::lonnet::perlvar{'lonDocRoot'}.$env{'form.filename'};
1.987     raeburn  11445:     }
                   11446:     my (%allfiles,%codebase,$output,$content);
                   11447:     my @changes = &get_env_multiple('form.namechange');
1.1075.2.35  raeburn  11448:     unless ((@changes > 0)  || ($context eq 'syllabus')) {
1.1071    raeburn  11449:         if (wantarray) {
                   11450:             return ('',0,0); 
                   11451:         } else {
                   11452:             return;
                   11453:         }
                   11454:     }
                   11455:     if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11456:         ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.1071    raeburn  11457:         unless ($container =~ m{^/uploaded/\Q$udom\E/\Q$uname\E/}) {
                   11458:             if (wantarray) {
                   11459:                 return ('',0,0);
                   11460:             } else {
                   11461:                 return;
                   11462:             }
                   11463:         } 
1.987     raeburn  11464:         $content = &Apache::lonnet::getfile($container);
1.1071    raeburn  11465:         if ($content eq '-1') {
                   11466:             if (wantarray) {
                   11467:                 return ('',0,0);
                   11468:             } else {
                   11469:                 return;
                   11470:             }
                   11471:         }
1.987     raeburn  11472:     } else {
1.1071    raeburn  11473:         unless ($container =~ /^\Q$dir_root\E/) {
                   11474:             if (wantarray) {
                   11475:                 return ('',0,0);
                   11476:             } else {
                   11477:                 return;
                   11478:             }
                   11479:         } 
1.1075.2.128  raeburn  11480:         if (open(my $fh,'<',$container)) {
1.987     raeburn  11481:             $content = join('', <$fh>);
                   11482:             close($fh);
                   11483:         } else {
1.1071    raeburn  11484:             if (wantarray) {
                   11485:                 return ('',0,0);
                   11486:             } else {
                   11487:                 return;
                   11488:             }
1.987     raeburn  11489:         }
                   11490:     }
                   11491:     my ($count,$codebasecount) = (0,0);
                   11492:     my $mm = new File::MMagic;
                   11493:     my $mime_type = $mm->checktype_contents($content);
                   11494:     if ($mime_type eq 'text/html') {
                   11495:         my $parse_result = 
                   11496:             &Apache::lonnet::extract_embedded_items($container,\%allfiles,
                   11497:                                                     \%codebase,\$content);
                   11498:         if ($parse_result eq 'ok') {
                   11499:             foreach my $i (@changes) {
                   11500:                 my $orig = &unescape($env{'form.embedded_orig_'.$i});
                   11501:                 my $ref = &unescape($env{'form.embedded_ref_'.$i});
                   11502:                 if ($allfiles{$ref}) {
                   11503:                     my $newname =  $orig;
                   11504:                     my ($attrib_regexp,$codebase);
1.1006    raeburn  11505:                     $attrib_regexp = &unescape($env{'form.embedded_attrib_'.$i});
1.987     raeburn  11506:                     if ($attrib_regexp =~ /:/) {
                   11507:                         $attrib_regexp =~ s/\:/|/g;
                   11508:                     }
                   11509:                     if ($content =~ m{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11510:                         my $numchg = ($content =~ s{($attrib_regexp\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11511:                         $count += $numchg;
1.1075.2.35  raeburn  11512:                         $allfiles{$newname} = $allfiles{$ref};
1.1075.2.48  raeburn  11513:                         delete($allfiles{$ref});
1.987     raeburn  11514:                     }
                   11515:                     if ($env{'form.embedded_codebase_'.$i} ne '') {
1.1006    raeburn  11516:                         $codebase = &unescape($env{'form.embedded_codebase_'.$i});
1.987     raeburn  11517:                         my $numchg = ($content =~ s/(codebase\s*=\s*["']?)\Q$codebase\E(["']?)/$1.$2/i); #' stupid emacs
                   11518:                         $codebasecount ++;
                   11519:                     }
                   11520:                 }
                   11521:             }
1.1075.2.35  raeburn  11522:             my $skiprewrites;
1.987     raeburn  11523:             if ($count || $codebasecount) {
                   11524:                 my $saveresult;
1.1071    raeburn  11525:                 if (($context eq 'portfolio') || ($context eq 'coursedoc') || 
1.1075.2.35  raeburn  11526:                     ($context eq 'manage_dependencies') || ($context eq 'syllabus')) {
1.987     raeburn  11527:                     my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11528:                     if ($url eq $container) {
                   11529:                         my ($fname) = ($container =~ m{/([^/]+)$});
                   11530:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11531:                                             $count,'<span class="LC_filename">'.
1.1071    raeburn  11532:                                             $fname.'</span>').'</p>';
1.987     raeburn  11533:                     } else {
                   11534:                          $output = '<p class="LC_error">'.
                   11535:                                    &mt('Error: update failed for: [_1].',
                   11536:                                    '<span class="LC_filename">'.
                   11537:                                    $container.'</span>').'</p>';
                   11538:                     }
1.1075.2.35  raeburn  11539:                     if ($context eq 'syllabus') {
                   11540:                         unless ($saveresult eq 'ok') {
                   11541:                             $skiprewrites = 1;
                   11542:                         }
                   11543:                     }
1.987     raeburn  11544:                 } else {
1.1075.2.128  raeburn  11545:                     if (open(my $fh,'>',$container)) {
1.987     raeburn  11546:                         print $fh $content;
                   11547:                         close($fh);
                   11548:                         $output = '<p>'.&mt('Updated [quant,_1,reference] in [_2].',
                   11549:                                   $count,'<span class="LC_filename">'.
                   11550:                                   $container.'</span>').'</p>';
1.661     raeburn  11551:                     } else {
1.987     raeburn  11552:                          $output = '<p class="LC_error">'.
                   11553:                                    &mt('Error: could not update [_1].',
                   11554:                                    '<span class="LC_filename">'.
                   11555:                                    $container.'</span>').'</p>';
1.661     raeburn  11556:                     }
                   11557:                 }
                   11558:             }
1.1075.2.35  raeburn  11559:             if (($context eq 'syllabus') && (!$skiprewrites)) {
                   11560:                 my ($actionurl,$state);
                   11561:                 $actionurl = "/public/$udom/$uname/syllabus";
                   11562:                 my ($ignore,$num,$numpathchanges,$existing,$mapping) =
                   11563:                     &ask_for_embedded_content($actionurl,$state,\%allfiles,
                   11564:                                               \%codebase,
                   11565:                                               {'context' => 'rewrites',
                   11566:                                                'ignore_remote_references' => 1,});
                   11567:                 if (ref($mapping) eq 'HASH') {
                   11568:                     my $rewrites = 0;
                   11569:                     foreach my $key (keys(%{$mapping})) {
                   11570:                         next if ($key =~ m{^https?://});
                   11571:                         my $ref = $mapping->{$key};
                   11572:                         my $newname = "/uploaded/$udom/$uname/portfolio/syllabus/$key";
                   11573:                         my $attrib;
                   11574:                         if (ref($allfiles{$mapping->{$key}}) eq 'ARRAY') {
                   11575:                             $attrib = join('|',@{$allfiles{$mapping->{$key}}});
                   11576:                         }
                   11577:                         if ($content =~ m{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}) {
                   11578:                             my $numchg = ($content =~ s{($attrib\s*=\s*['"]?)\Q$ref\E(['"]?)}{$1$newname$2}gi);
                   11579:                             $rewrites += $numchg;
                   11580:                         }
                   11581:                     }
                   11582:                     if ($rewrites) {
                   11583:                         my $saveresult;
                   11584:                         my $url = &Apache::lonnet::store_edited_file($container,$content,$udom,$uname,\$saveresult);
                   11585:                         if ($url eq $container) {
                   11586:                             my ($fname) = ($container =~ m{/([^/]+)$});
                   11587:                             $output .= '<p>'.&mt('Rewrote [quant,_1,link] as [quant,_1,absolute link] in [_2].',
                   11588:                                             $count,'<span class="LC_filename">'.
                   11589:                                             $fname.'</span>').'</p>';
                   11590:                         } else {
                   11591:                             $output .= '<p class="LC_error">'.
                   11592:                                        &mt('Error: could not update links in [_1].',
                   11593:                                        '<span class="LC_filename">'.
                   11594:                                        $container.'</span>').'</p>';
                   11595: 
                   11596:                         }
                   11597:                     }
                   11598:                 }
                   11599:             }
1.987     raeburn  11600:         } else {
                   11601:             &logthis('Failed to parse '.$container.
                   11602:                      ' to modify references: '.$parse_result);
1.661     raeburn  11603:         }
                   11604:     }
1.1071    raeburn  11605:     if (wantarray) {
                   11606:         return ($output,$count,$codebasecount);
                   11607:     } else {
                   11608:         return $output;
                   11609:     }
1.661     raeburn  11610: }
                   11611: 
                   11612: sub check_for_existing {
                   11613:     my ($path,$fname,$element) = @_;
                   11614:     my ($state,$msg);
                   11615:     if (-d $path.'/'.$fname) {
                   11616:         $state = 'exists';
                   11617:         $msg = &mt('Unable to upload [_1]. A directory by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11618:     } elsif (-e $path.'/'.$fname) {
                   11619:         $state = 'exists';
                   11620:         $msg = &mt('Unable to upload [_1]. A file by that name was found in [_2].','<span class="LC_filename">'.$fname.'</span>',$path);
                   11621:     }
                   11622:     if ($state eq 'exists') {
                   11623:         $msg = '<span class="LC_error">'.$msg.'</span><br />';
                   11624:     }
                   11625:     return ($state,$msg);
                   11626: }
                   11627: 
                   11628: sub check_for_upload {
                   11629:     my ($path,$fname,$group,$element,$portfolio_root,$port_path,
                   11630:         $disk_quota,$current_disk_usage,$uname,$udom) = @_;
1.985     raeburn  11631:     my $filesize = length($env{'form.'.$element});
                   11632:     if (!$filesize) {
                   11633:         my $msg = '<span class="LC_error">'.
                   11634:                   &mt('Unable to upload [_1]. (size = [_2] bytes)', 
                   11635:                       '<span class="LC_filename">'.$fname.'</span>',
                   11636:                       $filesize).'<br />'.
1.1007    raeburn  11637:                   &mt('Either the file you attempted to upload was empty, or your web browser was unable to read its contents.').'<br />'.
1.985     raeburn  11638:                   '</span>';
                   11639:         return ('zero_bytes',$msg);
                   11640:     }
                   11641:     $filesize =  $filesize/1000; #express in k (1024?)
1.661     raeburn  11642:     my $getpropath = 1;
1.1021    raeburn  11643:     my ($dirlistref,$listerror) =
                   11644:          &Apache::lonnet::dirlist($portfolio_root.$path,$udom,$uname,$getpropath);
1.661     raeburn  11645:     my $found_file = 0;
                   11646:     my $locked_file = 0;
1.991     raeburn  11647:     my @lockers;
                   11648:     my $navmap;
                   11649:     if ($env{'request.course.id'}) {
                   11650:         $navmap = Apache::lonnavmaps::navmap->new();
                   11651:     }
1.1021    raeburn  11652:     if (ref($dirlistref) eq 'ARRAY') {
                   11653:         foreach my $line (@{$dirlistref}) {
                   11654:             my ($file_name,$rest)=split(/\&/,$line,2);
                   11655:             if ($file_name eq $fname){
                   11656:                 $file_name = $path.$file_name;
                   11657:                 if ($group ne '') {
                   11658:                     $file_name = $group.$file_name;
                   11659:                 }
                   11660:                 $found_file = 1;
                   11661:                 if (&Apache::lonnet::is_locked($file_name,$udom,$uname,\@lockers) eq 'true') {
                   11662:                     foreach my $lock (@lockers) {
                   11663:                         if (ref($lock) eq 'ARRAY') {
                   11664:                             my ($symb,$crsid) = @{$lock};
                   11665:                             if ($crsid eq $env{'request.course.id'}) {
                   11666:                                 if (ref($navmap)) {
                   11667:                                     my $res = $navmap->getBySymb($symb);
                   11668:                                     foreach my $part (@{$res->parts()}) { 
                   11669:                                         my ($slot_status,$slot_time,$slot_name)=$res->check_for_slot($part);
                   11670:                                         unless (($slot_status == $res->RESERVED) ||
                   11671:                                                 ($slot_status == $res->RESERVED_LOCATION)) {
                   11672:                                             $locked_file = 1;
                   11673:                                         }
1.991     raeburn  11674:                                     }
1.1021    raeburn  11675:                                 } else {
                   11676:                                     $locked_file = 1;
1.991     raeburn  11677:                                 }
                   11678:                             } else {
                   11679:                                 $locked_file = 1;
                   11680:                             }
                   11681:                         }
1.1021    raeburn  11682:                    }
                   11683:                 } else {
                   11684:                     my @info = split(/\&/,$rest);
                   11685:                     my $currsize = $info[6]/1000;
                   11686:                     if ($currsize < $filesize) {
                   11687:                         my $extra = $filesize - $currsize;
                   11688:                         if (($current_disk_usage + $extra) > $disk_quota) {
1.1075.2.69  raeburn  11689:                             my $msg = '<p class="LC_warning">'.
1.1021    raeburn  11690:                                       &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  11691:                                           '<span class="LC_filename">'.$fname.'</span>',$filesize,$currsize).'</p>'.
                   11692:                                       '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',
                   11693:                                                    $disk_quota,$current_disk_usage).'</p>';
1.1021    raeburn  11694:                             return ('will_exceed_quota',$msg);
                   11695:                         }
1.984     raeburn  11696:                     }
                   11697:                 }
1.661     raeburn  11698:             }
                   11699:         }
                   11700:     }
                   11701:     if (($current_disk_usage + $filesize) > $disk_quota){
1.1075.2.69  raeburn  11702:         my $msg = '<p class="LC_warning">'.
                   11703:                 &mt('Unable to upload [_1]. (size = [_2] kilobytes). Disk quota will be exceeded.','<span class="LC_filename">'.$fname.'</span>',$filesize).'</p>'.
                   11704:                   '<p>'.&mt('Disk quota is [_1] kilobytes. Your current disk usage is [_2] kilobytes.',$disk_quota,$current_disk_usage).'</p>';
1.661     raeburn  11705:         return ('will_exceed_quota',$msg);
                   11706:     } elsif ($found_file) {
                   11707:         if ($locked_file) {
1.1075.2.69  raeburn  11708:             my $msg = '<p class="LC_warning">';
1.661     raeburn  11709:             $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  11710:             $msg .= '</p>';
1.661     raeburn  11711:             $msg .= &mt('You will be able to rename or delete existing [_1] after a grade has been assigned.','<span class="LC_filename">'.$fname.'</span>');
                   11712:             return ('file_locked',$msg);
                   11713:         } else {
1.1075.2.69  raeburn  11714:             my $msg = '<p class="LC_error">';
1.984     raeburn  11715:             $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  11716:             $msg .= '</p>';
1.984     raeburn  11717:             return ('existingfile',$msg);
1.661     raeburn  11718:         }
                   11719:     }
                   11720: }
                   11721: 
1.987     raeburn  11722: sub check_for_traversal {
                   11723:     my ($path,$url,$toplevel) = @_;
                   11724:     my @parts=split(/\//,$path);
                   11725:     my $cleanpath;
                   11726:     my $fullpath = $url;
                   11727:     for (my $i=0;$i<@parts;$i++) {
                   11728:         next if ($parts[$i] eq '.');
                   11729:         if ($parts[$i] eq '..') {
                   11730:             $fullpath =~ s{([^/]+/)$}{};
                   11731:         } else {
                   11732:             $fullpath .= $parts[$i].'/';
                   11733:         }
                   11734:     }
                   11735:     if ($fullpath =~ /^\Q$url\E(.*)$/) {
                   11736:         $cleanpath = $1;
                   11737:     } elsif ($fullpath =~ /^\Q$toplevel\E(.*)$/) {
                   11738:         my $curr_toprel = $1;
                   11739:         my @parts = split(/\//,$curr_toprel);
                   11740:         my ($url_toprel) = ($url =~ /^\Q$toplevel\E(.*)$/);
                   11741:         my @urlparts = split(/\//,$url_toprel);
                   11742:         my $doubledots;
                   11743:         my $startdiff = -1;
                   11744:         for (my $i=0; $i<@urlparts; $i++) {
                   11745:             if ($startdiff == -1) {
                   11746:                 unless ($urlparts[$i] eq $parts[$i]) {
                   11747:                     $startdiff = $i;
                   11748:                     $doubledots .= '../';
                   11749:                 }
                   11750:             } else {
                   11751:                 $doubledots .= '../';
                   11752:             }
                   11753:         }
                   11754:         if ($startdiff > -1) {
                   11755:             $cleanpath = $doubledots;
                   11756:             for (my $i=$startdiff; $i<@parts; $i++) {
                   11757:                 $cleanpath .= $parts[$i].'/';
                   11758:             }
                   11759:         }
                   11760:     }
                   11761:     $cleanpath =~ s{(/)$}{};
                   11762:     return $cleanpath;
                   11763: }
1.31      albertel 11764: 
1.1053    raeburn  11765: sub is_archive_file {
                   11766:     my ($mimetype) = @_;
                   11767:     if (($mimetype eq 'application/octet-stream') ||
                   11768:         ($mimetype eq 'application/x-stuffit') ||
                   11769:         ($mimetype =~ m{^application/(x\-)?(compressed|tar|zip|tgz|gz|gtar|gzip|gunzip|bz|bz2|bzip2)})) {
                   11770:         return 1;
                   11771:     }
                   11772:     return;
                   11773: }
                   11774: 
                   11775: sub decompress_form {
1.1065    raeburn  11776:     my ($mimetype,$archiveurl,$action,$noextract,$hiddenelements,$dirlist) = @_;
1.1053    raeburn  11777:     my %lt = &Apache::lonlocal::texthash (
                   11778:         this => 'This file is an archive file.',
1.1067    raeburn  11779:         camt => 'This file is a Camtasia archive file.',
1.1065    raeburn  11780:         itsc => 'Its contents are as follows:',
1.1053    raeburn  11781:         youm => 'You may wish to extract its contents.',
                   11782:         extr => 'Extract contents',
1.1067    raeburn  11783:         auto => 'LON-CAPA can process the files automatically, or you can decide how each should be handled.',
                   11784:         proa => 'Process automatically?',
1.1053    raeburn  11785:         yes  => 'Yes',
                   11786:         no   => 'No',
1.1067    raeburn  11787:         fold => 'Title for folder containing movie',
                   11788:         movi => 'Title for page containing embedded movie', 
1.1053    raeburn  11789:     );
1.1065    raeburn  11790:     my $fileloc = &Apache::lonnet::filelocation(undef,$archiveurl);
1.1067    raeburn  11791:     my ($is_camtasia,$topdir,%toplevel,@paths);
1.1065    raeburn  11792:     my $info = &list_archive_contents($fileloc,\@paths);
                   11793:     if (@paths) {
                   11794:         foreach my $path (@paths) {
                   11795:             $path =~ s{^/}{};
1.1067    raeburn  11796:             if ($path =~ m{^([^/]+)/$}) {
                   11797:                 $topdir = $1;
                   11798:             }
1.1065    raeburn  11799:             if ($path =~ m{^([^/]+)/}) {
                   11800:                 $toplevel{$1} = $path;
                   11801:             } else {
                   11802:                 $toplevel{$path} = $path;
                   11803:             }
                   11804:         }
                   11805:     }
1.1067    raeburn  11806:     if ($mimetype =~ m{^application/(x\-)?(compressed|zip)}) {
1.1075.2.59  raeburn  11807:         my @camtasia6 = ("$topdir/","$topdir/index.html",
1.1067    raeburn  11808:                         "$topdir/media/",
                   11809:                         "$topdir/media/$topdir.mp4",
                   11810:                         "$topdir/media/FirstFrame.png",
                   11811:                         "$topdir/media/player.swf",
                   11812:                         "$topdir/media/swfobject.js",
                   11813:                         "$topdir/media/expressInstall.swf");
1.1075.2.81  raeburn  11814:         my @camtasia8_1 = ("$topdir/","$topdir/$topdir.html",
1.1075.2.59  raeburn  11815:                          "$topdir/$topdir.mp4",
                   11816:                          "$topdir/$topdir\_config.xml",
                   11817:                          "$topdir/$topdir\_controller.swf",
                   11818:                          "$topdir/$topdir\_embed.css",
                   11819:                          "$topdir/$topdir\_First_Frame.png",
                   11820:                          "$topdir/$topdir\_player.html",
                   11821:                          "$topdir/$topdir\_Thumbnails.png",
                   11822:                          "$topdir/playerProductInstall.swf",
                   11823:                          "$topdir/scripts/",
                   11824:                          "$topdir/scripts/config_xml.js",
                   11825:                          "$topdir/scripts/handlebars.js",
                   11826:                          "$topdir/scripts/jquery-1.7.1.min.js",
                   11827:                          "$topdir/scripts/jquery-ui-1.8.15.custom.min.js",
                   11828:                          "$topdir/scripts/modernizr.js",
                   11829:                          "$topdir/scripts/player-min.js",
                   11830:                          "$topdir/scripts/swfobject.js",
                   11831:                          "$topdir/skins/",
                   11832:                          "$topdir/skins/configuration_express.xml",
                   11833:                          "$topdir/skins/express_show/",
                   11834:                          "$topdir/skins/express_show/player-min.css",
                   11835:                          "$topdir/skins/express_show/spritesheet.png");
1.1075.2.81  raeburn  11836:         my @camtasia8_4 = ("$topdir/","$topdir/$topdir.html",
                   11837:                          "$topdir/$topdir.mp4",
                   11838:                          "$topdir/$topdir\_config.xml",
                   11839:                          "$topdir/$topdir\_controller.swf",
                   11840:                          "$topdir/$topdir\_embed.css",
                   11841:                          "$topdir/$topdir\_First_Frame.png",
                   11842:                          "$topdir/$topdir\_player.html",
                   11843:                          "$topdir/$topdir\_Thumbnails.png",
                   11844:                          "$topdir/playerProductInstall.swf",
                   11845:                          "$topdir/scripts/",
                   11846:                          "$topdir/scripts/config_xml.js",
                   11847:                          "$topdir/scripts/techsmith-smart-player.min.js",
                   11848:                          "$topdir/skins/",
                   11849:                          "$topdir/skins/configuration_express.xml",
                   11850:                          "$topdir/skins/express_show/",
                   11851:                          "$topdir/skins/express_show/spritesheet.min.css",
                   11852:                          "$topdir/skins/express_show/spritesheet.png",
                   11853:                          "$topdir/skins/express_show/techsmith-smart-player.min.css");
1.1075.2.59  raeburn  11854:         my @diffs = &compare_arrays(\@paths,\@camtasia6);
1.1067    raeburn  11855:         if (@diffs == 0) {
1.1075.2.59  raeburn  11856:             $is_camtasia = 6;
                   11857:         } else {
1.1075.2.81  raeburn  11858:             @diffs = &compare_arrays(\@paths,\@camtasia8_1);
1.1075.2.59  raeburn  11859:             if (@diffs == 0) {
                   11860:                 $is_camtasia = 8;
1.1075.2.81  raeburn  11861:             } else {
                   11862:                 @diffs = &compare_arrays(\@paths,\@camtasia8_4);
                   11863:                 if (@diffs == 0) {
                   11864:                     $is_camtasia = 8;
                   11865:                 }
1.1075.2.59  raeburn  11866:             }
1.1067    raeburn  11867:         }
                   11868:     }
                   11869:     my $output;
                   11870:     if ($is_camtasia) {
                   11871:         $output = <<"ENDCAM";
                   11872: <script type="text/javascript" language="Javascript">
                   11873: // <![CDATA[
                   11874: 
                   11875: function camtasiaToggle() {
                   11876:     for (var i=0; i<document.uploaded_decompress.autoextract_camtasia.length; i++) {
                   11877:         if (document.uploaded_decompress.autoextract_camtasia[i].checked) {
1.1075.2.59  raeburn  11878:             if (document.uploaded_decompress.autoextract_camtasia[i].value == $is_camtasia) {
1.1067    raeburn  11879:                 document.getElementById('camtasia_titles').style.display='block';
                   11880:             } else {
                   11881:                 document.getElementById('camtasia_titles').style.display='none';
                   11882:             }
                   11883:         }
                   11884:     }
                   11885:     return;
                   11886: }
                   11887: 
                   11888: // ]]>
                   11889: </script>
                   11890: <p>$lt{'camt'}</p>
                   11891: ENDCAM
1.1065    raeburn  11892:     } else {
1.1067    raeburn  11893:         $output = '<p>'.$lt{'this'};
                   11894:         if ($info eq '') {
                   11895:             $output .= ' '.$lt{'youm'}.'</p>'."\n";
                   11896:         } else {
                   11897:             $output .= ' '.$lt{'itsc'}.'</p>'."\n".
                   11898:                        '<div><pre>'.$info.'</pre></div>';
                   11899:         }
1.1065    raeburn  11900:     }
1.1067    raeburn  11901:     $output .= '<form name="uploaded_decompress" action="'.$action.'" method="post">'."\n";
1.1065    raeburn  11902:     my $duplicates;
                   11903:     my $num = 0;
                   11904:     if (ref($dirlist) eq 'ARRAY') {
                   11905:         foreach my $item (@{$dirlist}) {
                   11906:             if (ref($item) eq 'ARRAY') {
                   11907:                 if (exists($toplevel{$item->[0]})) {
                   11908:                     $duplicates .= 
                   11909:                         &start_data_table_row().
                   11910:                         '<td><label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11911:                         'value="0" checked="checked" />'.&mt('No').'</label>'.
                   11912:                         '&nbsp;<label><input type="radio" name="archive_overwrite_'.$num.'" '.
                   11913:                         'value="1" />'.&mt('Yes').'</label>'.
                   11914:                         '<input type="hidden" name="archive_overwrite_name_'.$num.'" value="'.$item->[0].'" /></td>'."\n".
                   11915:                         '<td>'.$item->[0].'</td>';
                   11916:                     if ($item->[2]) {
                   11917:                         $duplicates .= '<td>'.&mt('Directory').'</td>';
                   11918:                     } else {
                   11919:                         $duplicates .= '<td>'.&mt('File').'</td>';
                   11920:                     }
                   11921:                     $duplicates .= '<td>'.$item->[3].'</td>'.
                   11922:                                    '<td>'.
                   11923:                                    &Apache::lonlocal::locallocaltime($item->[4]).
                   11924:                                    '</td>'.
                   11925:                                    &end_data_table_row();
                   11926:                     $num ++;
                   11927:                 }
                   11928:             }
                   11929:         }
                   11930:     }
                   11931:     my $itemcount;
                   11932:     if (@paths > 0) {
                   11933:         $itemcount = scalar(@paths);
                   11934:     } else {
                   11935:         $itemcount = 1;
                   11936:     }
1.1067    raeburn  11937:     if ($is_camtasia) {
                   11938:         $output .= $lt{'auto'}.'<br />'.
                   11939:                    '<span class="LC_nobreak">'.$lt{'proa'}.'<label>'.
1.1075.2.59  raeburn  11940:                    '<input type="radio" name="autoextract_camtasia" value="'.$is_camtasia.'" onclick="javascript:camtasiaToggle();" checked="checked" />'.
1.1067    raeburn  11941:                    $lt{'yes'}.'</label>&nbsp;<label>'.
                   11942:                    '<input type="radio" name="autoextract_camtasia" value="0" onclick="javascript:camtasiaToggle();" />'.
                   11943:                    $lt{'no'}.'</label></span><br />'.
                   11944:                    '<div id="camtasia_titles" style="display:block">'.
                   11945:                    &Apache::lonhtmlcommon::start_pick_box().
                   11946:                    &Apache::lonhtmlcommon::row_title($lt{'fold'}).
                   11947:                    '<input type="textbox" name="camtasia_foldername" value="'.$env{'form.comment'}.'" />'."\n".
                   11948:                    &Apache::lonhtmlcommon::row_closure().
                   11949:                    &Apache::lonhtmlcommon::row_title($lt{'movi'}).
                   11950:                    '<input type="textbox" name="camtasia_moviename" value="" />'."\n".
                   11951:                    &Apache::lonhtmlcommon::row_closure(1).
                   11952:                    &Apache::lonhtmlcommon::end_pick_box().
                   11953:                    '</div>';
                   11954:     }
1.1065    raeburn  11955:     $output .= 
                   11956:         '<input type="hidden" name="archive_overwrite_total" value="'.$num.'" />'.
1.1067    raeburn  11957:         '<input type="hidden" name="archive_itemcount" value="'.$itemcount.'" />'.
                   11958:         "\n";
1.1065    raeburn  11959:     if ($duplicates ne '') {
                   11960:         $output .= '<p><span class="LC_warning">'.
                   11961:                    &mt('Warning: decompression of the archive will overwrite the following items which already exist:').'</span><br />'.  
                   11962:                    &start_data_table().
                   11963:                    &start_data_table_header_row().
                   11964:                    '<th>'.&mt('Overwrite?').'</th>'.
                   11965:                    '<th>'.&mt('Name').'</th>'.
                   11966:                    '<th>'.&mt('Type').'</th>'.
                   11967:                    '<th>'.&mt('Size').'</th>'.
                   11968:                    '<th>'.&mt('Last modified').'</th>'.
                   11969:                    &end_data_table_header_row().
                   11970:                    $duplicates.
                   11971:                    &end_data_table().
                   11972:                    '</p>';
                   11973:     }
1.1067    raeburn  11974:     $output .= '<input type="hidden" name="archiveurl" value="'.$archiveurl.'" />'."\n";
1.1053    raeburn  11975:     if (ref($hiddenelements) eq 'HASH') {
                   11976:         foreach my $hidden (sort(keys(%{$hiddenelements}))) {
                   11977:             $output .= '<input type="hidden" name="'.$hidden.'" value="'.$hiddenelements->{$hidden}.'" />'."\n";
                   11978:         }
                   11979:     }
                   11980:     $output .= <<"END";
1.1067    raeburn  11981: <br />
1.1053    raeburn  11982: <input type="submit" name="decompress" value="$lt{'extr'}" />
                   11983: </form>
                   11984: $noextract
                   11985: END
                   11986:     return $output;
                   11987: }
                   11988: 
1.1065    raeburn  11989: sub decompression_utility {
                   11990:     my ($program) = @_;
                   11991:     my @utilities = ('tar','gunzip','bunzip2','unzip'); 
                   11992:     my $location;
                   11993:     if (grep(/^\Q$program\E$/,@utilities)) { 
                   11994:         foreach my $dir ('/bin/','/usr/bin/','/usr/local/bin/','/sbin/',
                   11995:                          '/usr/sbin/') {
                   11996:             if (-x $dir.$program) {
                   11997:                 $location = $dir.$program;
                   11998:                 last;
                   11999:             }
                   12000:         }
                   12001:     }
                   12002:     return $location;
                   12003: }
                   12004: 
                   12005: sub list_archive_contents {
                   12006:     my ($file,$pathsref) = @_;
                   12007:     my (@cmd,$output);
                   12008:     my $needsregexp;
                   12009:     if ($file =~ /\.zip$/) {
                   12010:         @cmd = (&decompression_utility('unzip'),"-l");
                   12011:         $needsregexp = 1;
                   12012:     } elsif (($file =~ m/\.tar\.gz$/) ||
                   12013:              ($file =~ /\.tgz$/)) {
                   12014:         @cmd = (&decompression_utility('tar'),"-ztf");
                   12015:     } elsif ($file =~ /\.tar\.bz2$/) {
                   12016:         @cmd = (&decompression_utility('tar'),"-jtf");
                   12017:     } elsif ($file =~ m|\.tar$|) {
                   12018:         @cmd = (&decompression_utility('tar'),"-tf");
                   12019:     }
                   12020:     if (@cmd) {
                   12021:         undef($!);
                   12022:         undef($@);
                   12023:         if (open(my $fh,"-|", @cmd, $file)) {
                   12024:             while (my $line = <$fh>) {
                   12025:                 $output .= $line;
                   12026:                 chomp($line);
                   12027:                 my $item;
                   12028:                 if ($needsregexp) {
                   12029:                     ($item) = ($line =~ /^\s*\d+\s+[\d\-]+\s+[\d:]+\s*(.+)$/); 
                   12030:                 } else {
                   12031:                     $item = $line;
                   12032:                 }
                   12033:                 if ($item ne '') {
                   12034:                     unless (grep(/^\Q$item\E$/,@{$pathsref})) {
                   12035:                         push(@{$pathsref},$item);
                   12036:                     } 
                   12037:                 }
                   12038:             }
                   12039:             close($fh);
                   12040:         }
                   12041:     }
                   12042:     return $output;
                   12043: }
                   12044: 
1.1053    raeburn  12045: sub decompress_uploaded_file {
                   12046:     my ($file,$dir) = @_;
                   12047:     &Apache::lonnet::appenv({'cgi.file' => $file});
                   12048:     &Apache::lonnet::appenv({'cgi.dir' => $dir});
                   12049:     my $result = &Apache::lonnet::ssi_body('/cgi-bin/decompress.pl');
                   12050:     my ($handle) = ($env{'user.environment'} =~m{/([^/]+)\.id$});
                   12051:     my $lonidsdir = $Apache::lonnet::perlvar{'lonIDsDir'};
                   12052:     &Apache::lonnet::transfer_profile_to_env($lonidsdir,$handle,1);
                   12053:     my $decompressed = $env{'cgi.decompressed'};
                   12054:     &Apache::lonnet::delenv('cgi.file');
                   12055:     &Apache::lonnet::delenv('cgi.dir');
                   12056:     &Apache::lonnet::delenv('cgi.decompressed');
                   12057:     return ($decompressed,$result);
                   12058: }
                   12059: 
1.1055    raeburn  12060: sub process_decompression {
                   12061:     my ($docudom,$docuname,$file,$destination,$dir_root,$hiddenelem) = @_;
1.1075.2.128  raeburn  12062:     unless (($dir_root eq '/userfiles') && ($destination =~ m{^(docs|supplemental)/(default|\d+)/\d+$})) {
                   12063:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12064:                &mt('Unexpected file path.').'</p>'."\n";
                   12065:     }
                   12066:     unless (($docudom =~ /^$match_domain$/) && ($docuname =~ /^$match_courseid$/)) {
                   12067:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12068:                &mt('Unexpected course context.').'</p>'."\n";
                   12069:     }
                   12070:     unless ($file eq &Apache::lonnet::clean_filename($file)) {
                   12071:         return '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12072:                &mt('Filename contained unexpected characters.').'</p>'."\n";
                   12073:     }
1.1055    raeburn  12074:     my ($dir,$error,$warning,$output);
1.1075.2.69  raeburn  12075:     if ($file !~ /\.(zip|tar|bz2|gz|tar.gz|tar.bz2|tgz)$/i) {
1.1075.2.34  raeburn  12076:         $error = &mt('Filename not a supported archive file type.').
                   12077:                  '<br />'.&mt('Filename should end with one of: [_1].',
1.1055    raeburn  12078:                               '.zip, .tar, .bz2, .gz, .tar.gz, .tar.bz2, .tgz');
                   12079:     } else {
                   12080:         my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12081:         if ($docuhome eq 'no_host') {
                   12082:             $error = &mt('Could not determine home server for course.');
                   12083:         } else {
                   12084:             my @ids=&Apache::lonnet::current_machine_ids();
                   12085:             my $currdir = "$dir_root/$destination";
                   12086:             if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12087:                 $dir = &LONCAPA::propath($docudom,$docuname).
                   12088:                        "$dir_root/$destination";
                   12089:             } else {
                   12090:                 $dir = $Apache::lonnet::perlvar{'lonDocRoot'}.
                   12091:                        "$dir_root/$docudom/$docuname/$destination";
                   12092:                 unless (&Apache::lonnet::repcopy_userfile("$dir/$file") eq 'ok') {
                   12093:                     $error = &mt('Archive file not found.');
                   12094:                 }
                   12095:             }
1.1065    raeburn  12096:             my (@to_overwrite,@to_skip);
                   12097:             if ($env{'form.archive_overwrite_total'} > 0) {
                   12098:                 my $total = $env{'form.archive_overwrite_total'};
                   12099:                 for (my $i=0; $i<$total; $i++) {
                   12100:                     if ($env{'form.archive_overwrite_'.$i} == 1) {
                   12101:                         push(@to_overwrite,$env{'form.archive_overwrite_name_'.$i});
                   12102:                     } elsif ($env{'form.archive_overwrite_'.$i} == 0) {
                   12103:                         push(@to_skip,$env{'form.archive_overwrite_name_'.$i});
                   12104:                     }
                   12105:                 }
                   12106:             }
                   12107:             my $numskip = scalar(@to_skip);
1.1075.2.128  raeburn  12108:             my $numoverwrite = scalar(@to_overwrite);
                   12109:             if (($numskip) && (!$numoverwrite)) {
1.1065    raeburn  12110:                 $warning = &mt('All items in the archive file already exist, and no overwriting of existing files has been requested.');         
                   12111:             } elsif ($dir eq '') {
1.1055    raeburn  12112:                 $error = &mt('Directory containing archive file unavailable.');
                   12113:             } elsif (!$error) {
1.1065    raeburn  12114:                 my ($decompressed,$display);
1.1075.2.128  raeburn  12115:                 if (($numskip) || ($numoverwrite)) {
1.1065    raeburn  12116:                     my $tempdir = time.'_'.$$.int(rand(10000));
                   12117:                     mkdir("$dir/$tempdir",0755);
1.1075.2.128  raeburn  12118:                     if (&File::Copy::move("$dir/$file","$dir/$tempdir/$file")) {
                   12119:                         ($decompressed,$display) =
                   12120:                             &decompress_uploaded_file($file,"$dir/$tempdir");
                   12121:                         foreach my $item (@to_skip) {
                   12122:                             if (($item ne '') && ($item !~ /\.\./)) {
                   12123:                                 if (-f "$dir/$tempdir/$item") {
                   12124:                                     unlink("$dir/$tempdir/$item");
                   12125:                                 } elsif (-d "$dir/$tempdir/$item") {
                   12126:                                     &File::Path::remove_tree("$dir/$tempdir/$item",{ safe => 1 });
                   12127:                                 }
                   12128:                             }
                   12129:                         }
                   12130:                         foreach my $item (@to_overwrite) {
                   12131:                             if ((-e "$dir/$tempdir/$item") && (-e "$dir/$item")) {
                   12132:                                 if (($item ne '') && ($item !~ /\.\./)) {
                   12133:                                     if (-f "$dir/$item") {
                   12134:                                         unlink("$dir/$item");
                   12135:                                     } elsif (-d "$dir/$item") {
                   12136:                                         &File::Path::remove_tree("$dir/$item",{ safe => 1 });
                   12137:                                     }
                   12138:                                     &File::Copy::move("$dir/$tempdir/$item","$dir/$item");
                   12139:                                 }
1.1065    raeburn  12140:                             }
                   12141:                         }
1.1075.2.128  raeburn  12142:                         if (&File::Copy::move("$dir/$tempdir/$file","$dir/$file")) {
                   12143:                             &File::Path::remove_tree("$dir/$tempdir",{ safe => 1 });
                   12144:                         }
1.1065    raeburn  12145:                     }
                   12146:                 } else {
                   12147:                     ($decompressed,$display) = 
                   12148:                         &decompress_uploaded_file($file,$dir);
                   12149:                 }
1.1055    raeburn  12150:                 if ($decompressed eq 'ok') {
1.1065    raeburn  12151:                     $output = '<p class="LC_info">'.
                   12152:                               &mt('Files extracted successfully from archive.').
                   12153:                               '</p>'."\n";
1.1055    raeburn  12154:                     my ($warning,$result,@contents);
                   12155:                     my ($newdirlistref,$newlisterror) =
                   12156:                         &Apache::lonnet::dirlist($currdir,$docudom,
                   12157:                                                  $docuname,1);
                   12158:                     my (%is_dir,%changes,@newitems);
                   12159:                     my $dirptr = 16384;
1.1065    raeburn  12160:                     if (ref($newdirlistref) eq 'ARRAY') {
1.1055    raeburn  12161:                         foreach my $dir_line (@{$newdirlistref}) {
                   12162:                             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
1.1075.2.128  raeburn  12163:                             unless (($item =~ /^\.+$/) || ($item eq $file)) { 
1.1055    raeburn  12164:                                 push(@newitems,$item);
                   12165:                                 if ($dirptr&$testdir) {
                   12166:                                     $is_dir{$item} = 1;
                   12167:                                 }
                   12168:                                 $changes{$item} = 1;
                   12169:                             }
                   12170:                         }
                   12171:                     }
                   12172:                     if (keys(%changes) > 0) {
                   12173:                         foreach my $item (sort(@newitems)) {
                   12174:                             if ($changes{$item}) {
                   12175:                                 push(@contents,$item);
                   12176:                             }
                   12177:                         }
                   12178:                     }
                   12179:                     if (@contents > 0) {
1.1067    raeburn  12180:                         my $wantform;
                   12181:                         unless ($env{'form.autoextract_camtasia'}) {
                   12182:                             $wantform = 1;
                   12183:                         }
1.1056    raeburn  12184:                         my (%children,%parent,%dirorder,%titles);
1.1055    raeburn  12185:                         my ($count,$datatable) = &get_extracted($docudom,$docuname,
                   12186:                                                                 $currdir,\%is_dir,
                   12187:                                                                 \%children,\%parent,
1.1056    raeburn  12188:                                                                 \@contents,\%dirorder,
                   12189:                                                                 \%titles,$wantform);
1.1055    raeburn  12190:                         if ($datatable ne '') {
                   12191:                             $output .= &archive_options_form('decompressed',$datatable,
                   12192:                                                              $count,$hiddenelem);
1.1065    raeburn  12193:                             my $startcount = 6;
1.1055    raeburn  12194:                             $output .= &archive_javascript($startcount,$count,
1.1056    raeburn  12195:                                                            \%titles,\%children);
1.1055    raeburn  12196:                         }
1.1067    raeburn  12197:                         if ($env{'form.autoextract_camtasia'}) {
1.1075.2.59  raeburn  12198:                             my $version = $env{'form.autoextract_camtasia'};
1.1067    raeburn  12199:                             my %displayed;
                   12200:                             my $total = 1;
                   12201:                             $env{'form.archive_directory'} = [];
                   12202:                             foreach my $i (sort { $a <=> $b } keys(%dirorder)) {
                   12203:                                 my $path = join('/',map { $titles{$_}; } @{$dirorder{$i}});
                   12204:                                 $path =~ s{/$}{};
                   12205:                                 my $item;
                   12206:                                 if ($path ne '') {
                   12207:                                     $item = "$path/$titles{$i}";
                   12208:                                 } else {
                   12209:                                     $item = $titles{$i};
                   12210:                                 }
                   12211:                                 $env{'form.archive_content_'.$i} = "$dir_root/$destination/$item";
                   12212:                                 if ($item eq $contents[0]) {
                   12213:                                     push(@{$env{'form.archive_directory'}},$i);
                   12214:                                     $env{'form.archive_'.$i} = 'display';
                   12215:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_foldername'};
                   12216:                                     $displayed{'folder'} = $i;
1.1075.2.59  raeburn  12217:                                 } elsif ((($item eq "$contents[0]/index.html") && ($version == 6)) ||
                   12218:                                          (($item eq "$contents[0]/$contents[0]".'.html') && ($version == 8))) {
1.1067    raeburn  12219:                                     $env{'form.archive_'.$i} = 'display';
                   12220:                                     $env{'form.archive_title_'.$i} = $env{'form.camtasia_moviename'};
                   12221:                                     $displayed{'web'} = $i;
                   12222:                                 } else {
1.1075.2.59  raeburn  12223:                                     if ((($item eq "$contents[0]/media") && ($version == 6)) ||
                   12224:                                         ((($item eq "$contents[0]/scripts") || ($item eq "$contents[0]/skins") ||
                   12225:                                              ($item eq "$contents[0]/skins/express_show")) && ($version == 8))) {
1.1067    raeburn  12226:                                         push(@{$env{'form.archive_directory'}},$i);
                   12227:                                     }
                   12228:                                     $env{'form.archive_'.$i} = 'dependency';
                   12229:                                 }
                   12230:                                 $total ++;
                   12231:                             }
                   12232:                             for (my $i=1; $i<$total; $i++) {
                   12233:                                 next if ($i == $displayed{'web'});
                   12234:                                 next if ($i == $displayed{'folder'});
                   12235:                                 $env{'form.archive_dependent_on_'.$i} = $displayed{'web'};
                   12236:                             }
                   12237:                             $env{'form.phase'} = 'decompress_cleanup';
                   12238:                             $env{'form.archivedelete'} = 1;
                   12239:                             $env{'form.archive_count'} = $total-1;
                   12240:                             $output .=
                   12241:                                 &process_extracted_files('coursedocs',$docudom,
                   12242:                                                          $docuname,$destination,
                   12243:                                                          $dir_root,$hiddenelem);
                   12244:                         }
1.1055    raeburn  12245:                     } else {
                   12246:                         $warning = &mt('No new items extracted from archive file.');
                   12247:                     }
                   12248:                 } else {
                   12249:                     $output = $display;
                   12250:                     $error = &mt('An error occurred during extraction from the archive file.');
                   12251:                 }
                   12252:             }
                   12253:         }
                   12254:     }
                   12255:     if ($error) {
                   12256:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12257:                    $error.'</p>'."\n";
                   12258:     }
                   12259:     if ($warning) {
                   12260:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12261:     }
                   12262:     return $output;
                   12263: }
                   12264: 
                   12265: sub get_extracted {
1.1056    raeburn  12266:     my ($docudom,$docuname,$currdir,$is_dir,$children,$parent,$contents,$dirorder,
                   12267:         $titles,$wantform) = @_;
1.1055    raeburn  12268:     my $count = 0;
                   12269:     my $depth = 0;
                   12270:     my $datatable;
1.1056    raeburn  12271:     my @hierarchy;
1.1055    raeburn  12272:     return unless ((ref($is_dir) eq 'HASH') && (ref($children) eq 'HASH') &&
1.1056    raeburn  12273:                    (ref($parent) eq 'HASH') && (ref($contents) eq 'ARRAY') &&
                   12274:                    (ref($dirorder) eq 'HASH') && (ref($titles) eq 'HASH'));
1.1055    raeburn  12275:     foreach my $item (@{$contents}) {
                   12276:         $count ++;
1.1056    raeburn  12277:         @{$dirorder->{$count}} = @hierarchy;
                   12278:         $titles->{$count} = $item;
1.1055    raeburn  12279:         &archive_hierarchy($depth,$count,$parent,$children);
                   12280:         if ($wantform) {
                   12281:             $datatable .= &archive_row($is_dir->{$item},$item,
                   12282:                                        $currdir,$depth,$count);
                   12283:         }
                   12284:         if ($is_dir->{$item}) {
                   12285:             $depth ++;
1.1056    raeburn  12286:             push(@hierarchy,$count);
                   12287:             $parent->{$depth} = $count;
1.1055    raeburn  12288:             $datatable .=
                   12289:                 &recurse_extracted_archive("$currdir/$item",$docudom,$docuname,
1.1056    raeburn  12290:                                            \$depth,\$count,\@hierarchy,$dirorder,
                   12291:                                            $children,$parent,$titles,$wantform);
1.1055    raeburn  12292:             $depth --;
1.1056    raeburn  12293:             pop(@hierarchy);
1.1055    raeburn  12294:         }
                   12295:     }
                   12296:     return ($count,$datatable);
                   12297: }
                   12298: 
                   12299: sub recurse_extracted_archive {
1.1056    raeburn  12300:     my ($currdir,$docudom,$docuname,$depth,$count,$hierarchy,$dirorder,
                   12301:         $children,$parent,$titles,$wantform) = @_;
1.1055    raeburn  12302:     my $result='';
1.1056    raeburn  12303:     unless ((ref($depth)) && (ref($count)) && (ref($hierarchy) eq 'ARRAY') &&
                   12304:             (ref($children) eq 'HASH') && (ref($parent) eq 'HASH') &&
                   12305:             (ref($dirorder) eq 'HASH')) {
1.1055    raeburn  12306:         return $result;
                   12307:     }
                   12308:     my $dirptr = 16384;
                   12309:     my ($newdirlistref,$newlisterror) =
                   12310:         &Apache::lonnet::dirlist($currdir,$docudom,$docuname,1);
                   12311:     if (ref($newdirlistref) eq 'ARRAY') {
                   12312:         foreach my $dir_line (@{$newdirlistref}) {
                   12313:             my ($item,undef,undef,$testdir)=split(/\&/,$dir_line,5);
                   12314:             unless ($item =~ /^\.+$/) {
                   12315:                 $$count ++;
1.1056    raeburn  12316:                 @{$dirorder->{$$count}} = @{$hierarchy};
                   12317:                 $titles->{$$count} = $item;
1.1055    raeburn  12318:                 &archive_hierarchy($$depth,$$count,$parent,$children);
1.1056    raeburn  12319: 
1.1055    raeburn  12320:                 my $is_dir;
                   12321:                 if ($dirptr&$testdir) {
                   12322:                     $is_dir = 1;
                   12323:                 }
                   12324:                 if ($wantform) {
                   12325:                     $result .= &archive_row($is_dir,$item,$currdir,$$depth,$$count);
                   12326:                 }
                   12327:                 if ($is_dir) {
                   12328:                     $$depth ++;
1.1056    raeburn  12329:                     push(@{$hierarchy},$$count);
                   12330:                     $parent->{$$depth} = $$count;
1.1055    raeburn  12331:                     $result .=
                   12332:                         &recurse_extracted_archive("$currdir/$item",$docudom,
                   12333:                                                    $docuname,$depth,$count,
1.1056    raeburn  12334:                                                    $hierarchy,$dirorder,$children,
                   12335:                                                    $parent,$titles,$wantform);
1.1055    raeburn  12336:                     $$depth --;
1.1056    raeburn  12337:                     pop(@{$hierarchy});
1.1055    raeburn  12338:                 }
                   12339:             }
                   12340:         }
                   12341:     }
                   12342:     return $result;
                   12343: }
                   12344: 
                   12345: sub archive_hierarchy {
                   12346:     my ($depth,$count,$parent,$children) =@_;
                   12347:     if ((ref($parent) eq 'HASH') && (ref($children) eq 'HASH')) {
                   12348:         if (exists($parent->{$depth})) {
                   12349:              $children->{$parent->{$depth}} .= $count.':';
                   12350:         }
                   12351:     }
                   12352:     return;
                   12353: }
                   12354: 
                   12355: sub archive_row {
                   12356:     my ($is_dir,$item,$currdir,$depth,$count) = @_;
                   12357:     my ($name) = ($item =~ m{([^/]+)$});
                   12358:     my %choices = &Apache::lonlocal::texthash (
1.1059    raeburn  12359:                                        'display'    => 'Add as file',
1.1055    raeburn  12360:                                        'dependency' => 'Include as dependency',
                   12361:                                        'discard'    => 'Discard',
                   12362:                                       );
                   12363:     if ($is_dir) {
1.1059    raeburn  12364:         $choices{'display'} = &mt('Add as folder'); 
1.1055    raeburn  12365:     }
1.1056    raeburn  12366:     my $output = &start_data_table_row().'<td align="right">'.$count.'</td>'."\n";
                   12367:     my $offset = 0;
1.1055    raeburn  12368:     foreach my $action ('display','dependency','discard') {
1.1056    raeburn  12369:         $offset ++;
1.1065    raeburn  12370:         if ($action ne 'display') {
                   12371:             $offset ++;
                   12372:         }  
1.1055    raeburn  12373:         $output .= '<td><span class="LC_nobreak">'.
                   12374:                    '<label><input type="radio" name="archive_'.$count.
                   12375:                    '" id="archive_'.$action.'_'.$count.'" value="'.$action.'"';
                   12376:         my $text = $choices{$action};
                   12377:         if ($is_dir) {
                   12378:             $output .= ' onclick="javascript:propagateCheck(this.form,'."'$count'".');"';
                   12379:             if ($action eq 'display') {
1.1059    raeburn  12380:                 $text = &mt('Add as folder');
1.1055    raeburn  12381:             }
1.1056    raeburn  12382:         } else {
                   12383:             $output .= ' onclick="javascript:dependencyCheck(this.form,'."$count,$offset".');"';
                   12384: 
                   12385:         }
                   12386:         $output .= ' />&nbsp;'.$choices{$action}.'</label></span>';
                   12387:         if ($action eq 'dependency') {
                   12388:             $output .= '<div id="arc_depon_'.$count.'" style="display:none;">'."\n".
                   12389:                        &mt('Used by:').'&nbsp;<select name="archive_dependent_on_'.$count.'" '.
                   12390:                        'onchange="propagateSelect(this.form,'."$count,$offset".')">'."\n".
                   12391:                        '<option value=""></option>'."\n".
                   12392:                        '</select>'."\n".
                   12393:                        '</div>';
1.1059    raeburn  12394:         } elsif ($action eq 'display') {
                   12395:             $output .= '<div id="arc_title_'.$count.'" style="display:none;">'."\n".
                   12396:                        &mt('Title:').'&nbsp;<input type="text" name="archive_title_'.$count.'" id="archive_title_'.$count.'" />'."\n".
                   12397:                        '</div>';
1.1055    raeburn  12398:         }
1.1056    raeburn  12399:         $output .= '</td>';
1.1055    raeburn  12400:     }
                   12401:     $output .= '<td><input type="hidden" name="archive_content_'.$count.'" value="'.
                   12402:                &HTML::Entities::encode("$currdir/$item",'"<>&').'" />'.('&nbsp;' x 2);
                   12403:     for (my $i=0; $i<$depth; $i++) {
                   12404:         $output .= ('<img src="/adm/lonIcons/whitespace1.gif" class="LC_docs_spacer" alt="" />' x2)."\n";
                   12405:     }
                   12406:     if ($is_dir) {
                   12407:         $output .= '<img src="/adm/lonIcons/navmap.folder.open.gif" alt="" />&nbsp;'."\n".
                   12408:                    '<input type="hidden" name="archive_directory" value="'.$count.'" />'."\n";
                   12409:     } else {
                   12410:         $output .= '<input type="hidden" name="archive_file" value="'.$count.'" />'."\n";
                   12411:     }
                   12412:     $output .= '&nbsp;'.$name.'</td>'."\n".
                   12413:                &end_data_table_row();
                   12414:     return $output;
                   12415: }
                   12416: 
                   12417: sub archive_options_form {
1.1065    raeburn  12418:     my ($form,$display,$count,$hiddenelem) = @_;
                   12419:     my %lt = &Apache::lonlocal::texthash(
                   12420:                perm => 'Permanently remove archive file?',
                   12421:                hows => 'How should each extracted item be incorporated in the course?',
                   12422:                cont => 'Content actions for all',
                   12423:                addf => 'Add as folder/file',
                   12424:                incd => 'Include as dependency for a displayed file',
                   12425:                disc => 'Discard',
                   12426:                no   => 'No',
                   12427:                yes  => 'Yes',
                   12428:                save => 'Save',
                   12429:     );
                   12430:     my $output = <<"END";
                   12431: <form name="$form" method="post" action="">
                   12432: <p><span class="LC_nobreak">$lt{'perm'}&nbsp;
                   12433: <label>
                   12434:   <input type="radio" name="archivedelete" value="0" checked="checked" />$lt{'no'}
                   12435: </label>
                   12436: &nbsp;
                   12437: <label>
                   12438:   <input type="radio" name="archivedelete" value="1" />$lt{'yes'}</label>
                   12439: </span>
                   12440: </p>
                   12441: <input type="hidden" name="phase" value="decompress_cleanup" />
                   12442: <br />$lt{'hows'}
                   12443: <div class="LC_columnSection">
                   12444:   <fieldset>
                   12445:     <legend>$lt{'cont'}</legend>
                   12446:     <input type="button" value="$lt{'addf'}" onclick="javascript:checkAll(document.$form,'display');" /> 
                   12447:     &nbsp;&nbsp;<input type="button" value="$lt{'incd'}" onclick="javascript:checkAll(document.$form,'dependency');" />
                   12448:     &nbsp;&nbsp;<input type="button" value="$lt{'disc'}" onclick="javascript:checkAll(document.$form,'discard');" />
                   12449:   </fieldset>
                   12450: </div>
                   12451: END
                   12452:     return $output.
1.1055    raeburn  12453:            &start_data_table()."\n".
1.1065    raeburn  12454:            $display."\n".
1.1055    raeburn  12455:            &end_data_table()."\n".
                   12456:            '<input type="hidden" name="archive_count" value="'.$count.'" />'.
                   12457:            $hiddenelem.
1.1065    raeburn  12458:            '<br /><input type="submit" name="archive_submit" value="'.$lt{'save'}.'" />'.
1.1055    raeburn  12459:            '</form>';
                   12460: }
                   12461: 
                   12462: sub archive_javascript {
1.1056    raeburn  12463:     my ($startcount,$numitems,$titles,$children) = @_;
                   12464:     return unless ((ref($titles) eq 'HASH') && (ref($children) eq 'HASH'));
1.1059    raeburn  12465:     my $maintitle = $env{'form.comment'};
1.1055    raeburn  12466:     my $scripttag = <<START;
                   12467: <script type="text/javascript">
                   12468: // <![CDATA[
                   12469: 
                   12470: function checkAll(form,prefix) {
                   12471:     var idstr =  new RegExp("^archive_"+prefix+"_\\\\d+\$");
                   12472:     for (var i=0; i < form.elements.length; i++) {
                   12473:         var id = form.elements[i].id;
                   12474:         if ((id != '') && (id != undefined)) {
                   12475:             if (idstr.test(id)) {
                   12476:                 if (form.elements[i].type == 'radio') {
                   12477:                     form.elements[i].checked = true;
1.1056    raeburn  12478:                     var nostart = i-$startcount;
1.1059    raeburn  12479:                     var offset = nostart%7;
                   12480:                     var count = (nostart-offset)/7;    
1.1056    raeburn  12481:                     dependencyCheck(form,count,offset);
1.1055    raeburn  12482:                 }
                   12483:             }
                   12484:         }
                   12485:     }
                   12486: }
                   12487: 
                   12488: function propagateCheck(form,count) {
                   12489:     if (count > 0) {
1.1059    raeburn  12490:         var startelement = $startcount + ((count-1) * 7);
                   12491:         for (var j=1; j<6; j++) {
                   12492:             if ((j != 2) && (j != 4)) {
1.1056    raeburn  12493:                 var item = startelement + j; 
                   12494:                 if (form.elements[item].type == 'radio') {
                   12495:                     if (form.elements[item].checked) {
                   12496:                         containerCheck(form,count,j);
                   12497:                         break;
                   12498:                     }
1.1055    raeburn  12499:                 }
                   12500:             }
                   12501:         }
                   12502:     }
                   12503: }
                   12504: 
                   12505: numitems = $numitems
1.1056    raeburn  12506: var titles = new Array(numitems);
                   12507: var parents = new Array(numitems);
1.1055    raeburn  12508: for (var i=0; i<numitems; i++) {
1.1056    raeburn  12509:     parents[i] = new Array;
1.1055    raeburn  12510: }
1.1059    raeburn  12511: var maintitle = '$maintitle';
1.1055    raeburn  12512: 
                   12513: START
                   12514: 
1.1056    raeburn  12515:     foreach my $container (sort { $a <=> $b } (keys(%{$children}))) {
                   12516:         my @contents = split(/:/,$children->{$container});
1.1055    raeburn  12517:         for (my $i=0; $i<@contents; $i ++) {
                   12518:             $scripttag .= 'parents['.$container.']['.$i.'] = '.$contents[$i]."\n";
                   12519:         }
                   12520:     }
                   12521: 
1.1056    raeburn  12522:     foreach my $key (sort { $a <=> $b } (keys(%{$titles}))) {
                   12523:         $scripttag .= "titles[$key] = '".$titles->{$key}."';\n";
                   12524:     }
                   12525: 
1.1055    raeburn  12526:     $scripttag .= <<END;
                   12527: 
                   12528: function containerCheck(form,count,offset) {
                   12529:     if (count > 0) {
1.1056    raeburn  12530:         dependencyCheck(form,count,offset);
1.1059    raeburn  12531:         var item = (offset+$startcount)+7*(count-1);
1.1055    raeburn  12532:         form.elements[item].checked = true;
                   12533:         if(Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12534:             if (parents[count].length > 0) {
                   12535:                 for (var j=0; j<parents[count].length; j++) {
1.1056    raeburn  12536:                     containerCheck(form,parents[count][j],offset);
                   12537:                 }
                   12538:             }
                   12539:         }
                   12540:     }
                   12541: }
                   12542: 
                   12543: function dependencyCheck(form,count,offset) {
                   12544:     if (count > 0) {
1.1059    raeburn  12545:         var chosen = (offset+$startcount)+7*(count-1);
                   12546:         var depitem = $startcount + ((count-1) * 7) + 4;
1.1056    raeburn  12547:         var currtype = form.elements[depitem].type;
                   12548:         if (form.elements[chosen].value == 'dependency') {
                   12549:             document.getElementById('arc_depon_'+count).style.display='block'; 
                   12550:             form.elements[depitem].options.length = 0;
                   12551:             form.elements[depitem].options[0] = new Option('Select','',true,true);
1.1075.2.11  raeburn  12552:             for (var i=1; i<=numitems; i++) {
                   12553:                 if (i == count) {
                   12554:                     continue;
                   12555:                 }
1.1059    raeburn  12556:                 var startelement = $startcount + (i-1) * 7;
                   12557:                 for (var j=1; j<6; j++) {
                   12558:                     if ((j != 2) && (j!= 4)) {
1.1056    raeburn  12559:                         var item = startelement + j;
                   12560:                         if (form.elements[item].type == 'radio') {
                   12561:                             if (form.elements[item].checked) {
                   12562:                                 if (form.elements[item].value == 'display') {
                   12563:                                     var n = form.elements[depitem].options.length;
                   12564:                                     form.elements[depitem].options[n] = new Option(titles[i],i,false,false);
                   12565:                                 }
                   12566:                             }
                   12567:                         }
                   12568:                     }
                   12569:                 }
                   12570:             }
                   12571:         } else {
                   12572:             document.getElementById('arc_depon_'+count).style.display='none';
                   12573:             form.elements[depitem].options.length = 0;
                   12574:             form.elements[depitem].options[0] = new Option('Select','',true,true);
                   12575:         }
1.1059    raeburn  12576:         titleCheck(form,count,offset);
1.1056    raeburn  12577:     }
                   12578: }
                   12579: 
                   12580: function propagateSelect(form,count,offset) {
                   12581:     if (count > 0) {
1.1065    raeburn  12582:         var item = (1+offset+$startcount)+7*(count-1);
1.1056    raeburn  12583:         var picked = form.elements[item].options[form.elements[item].selectedIndex].value; 
                   12584:         if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12585:             if (parents[count].length > 0) {
                   12586:                 for (var j=0; j<parents[count].length; j++) {
                   12587:                     containerSelect(form,parents[count][j],offset,picked);
1.1055    raeburn  12588:                 }
                   12589:             }
                   12590:         }
                   12591:     }
                   12592: }
1.1056    raeburn  12593: 
                   12594: function containerSelect(form,count,offset,picked) {
                   12595:     if (count > 0) {
1.1065    raeburn  12596:         var item = (offset+$startcount)+7*(count-1);
1.1056    raeburn  12597:         if (form.elements[item].type == 'radio') {
                   12598:             if (form.elements[item].value == 'dependency') {
                   12599:                 if (form.elements[item+1].type == 'select-one') {
                   12600:                     for (var i=0; i<form.elements[item+1].options.length; i++) {
                   12601:                         if (form.elements[item+1].options[i].value == picked) {
                   12602:                             form.elements[item+1].selectedIndex = i;
                   12603:                             break;
                   12604:                         }
                   12605:                     }
                   12606:                 }
                   12607:                 if (Object.prototype.toString.call(parents[count]) === '[object Array]') {
                   12608:                     if (parents[count].length > 0) {
                   12609:                         for (var j=0; j<parents[count].length; j++) {
                   12610:                             containerSelect(form,parents[count][j],offset,picked);
                   12611:                         }
                   12612:                     }
                   12613:                 }
                   12614:             }
                   12615:         }
                   12616:     }
                   12617: }
                   12618: 
1.1059    raeburn  12619: function titleCheck(form,count,offset) {
                   12620:     if (count > 0) {
                   12621:         var chosen = (offset+$startcount)+7*(count-1);
                   12622:         var depitem = $startcount + ((count-1) * 7) + 2;
                   12623:         var currtype = form.elements[depitem].type;
                   12624:         if (form.elements[chosen].value == 'display') {
                   12625:             document.getElementById('arc_title_'+count).style.display='block';
                   12626:             if ((count==1) && ((parents[count].length > 0) || (numitems == 1))) {
                   12627:                 document.getElementById('archive_title_'+count).value=maintitle;
                   12628:             }
                   12629:         } else {
                   12630:             document.getElementById('arc_title_'+count).style.display='none';
                   12631:             if (currtype == 'text') { 
                   12632:                 document.getElementById('archive_title_'+count).value='';
                   12633:             }
                   12634:         }
                   12635:     }
                   12636:     return;
                   12637: }
                   12638: 
1.1055    raeburn  12639: // ]]>
                   12640: </script>
                   12641: END
                   12642:     return $scripttag;
                   12643: }
                   12644: 
                   12645: sub process_extracted_files {
1.1067    raeburn  12646:     my ($context,$docudom,$docuname,$destination,$dir_root,$hiddenelem) = @_;
1.1055    raeburn  12647:     my $numitems = $env{'form.archive_count'};
1.1075.2.128  raeburn  12648:     return if ((!$numitems) || ($numitems =~ /\D/));
1.1055    raeburn  12649:     my @ids=&Apache::lonnet::current_machine_ids();
                   12650:     my ($prefix,$pathtocheck,$dir,$ishome,$error,$warning,%toplevelitems,%is_dir,
1.1067    raeburn  12651:         %folders,%containers,%mapinner,%prompttofetch);
1.1055    raeburn  12652:     my $docuhome = &Apache::lonnet::homeserver($docuname,$docudom);
                   12653:     if (grep(/^\Q$docuhome\E$/,@ids)) {
                   12654:         $prefix = &LONCAPA::propath($docudom,$docuname);
                   12655:         $pathtocheck = "$dir_root/$destination";
                   12656:         $dir = $dir_root;
                   12657:         $ishome = 1;
                   12658:     } else {
                   12659:         $prefix = $Apache::lonnet::perlvar{'lonDocRoot'};
                   12660:         $pathtocheck = "$dir_root/$docudom/$docuname/$destination";
1.1075.2.128  raeburn  12661:         $dir = "$dir_root/$docudom/$docuname";
1.1055    raeburn  12662:     }
                   12663:     my $currdir = "$dir_root/$destination";
                   12664:     (my $docstype,$mapinner{'0'}) = ($destination =~ m{^(docs|supplemental)/(\w+)/});
                   12665:     if ($env{'form.folderpath'}) {
                   12666:         my @items = split('&',$env{'form.folderpath'});
                   12667:         $folders{'0'} = $items[-2];
1.1075.2.17  raeburn  12668:         if ($env{'form.folderpath'} =~ /\:1$/) {
                   12669:             $containers{'0'}='page';
                   12670:         } else {
                   12671:             $containers{'0'}='sequence';
                   12672:         }
1.1055    raeburn  12673:     }
                   12674:     my @archdirs = &get_env_multiple('form.archive_directory');
                   12675:     if ($numitems) {
                   12676:         for (my $i=1; $i<=$numitems; $i++) {
                   12677:             my $path = $env{'form.archive_content_'.$i};
                   12678:             if ($path =~ m{^\Q$pathtocheck\E/([^/]+)$}) {
                   12679:                 my $item = $1;
                   12680:                 $toplevelitems{$item} = $i;
                   12681:                 if (grep(/^\Q$i\E$/,@archdirs)) {
                   12682:                     $is_dir{$item} = 1;
                   12683:                 }
                   12684:             }
                   12685:         }
                   12686:     }
1.1067    raeburn  12687:     my ($output,%children,%parent,%titles,%dirorder,$result);
1.1055    raeburn  12688:     if (keys(%toplevelitems) > 0) {
                   12689:         my @contents = sort(keys(%toplevelitems));
1.1056    raeburn  12690:         (my $count,undef) = &get_extracted($docudom,$docuname,$currdir,\%is_dir,\%children,
                   12691:                                            \%parent,\@contents,\%dirorder,\%titles);
1.1055    raeburn  12692:     }
1.1066    raeburn  12693:     my (%referrer,%orphaned,%todelete,%todeletedir,%newdest,%newseqid);
1.1055    raeburn  12694:     if ($numitems) {
                   12695:         for (my $i=1; $i<=$numitems; $i++) {
1.1075.2.11  raeburn  12696:             next if ($env{'form.archive_'.$i} eq 'dependency');
1.1055    raeburn  12697:             my $path = $env{'form.archive_content_'.$i};
                   12698:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12699:                 if ($env{'form.archive_'.$i} eq 'discard') {
                   12700:                     if ($prefix ne '' && $path ne '') {
                   12701:                         if (-e $prefix.$path) {
1.1066    raeburn  12702:                             if ((@archdirs > 0) && 
                   12703:                                 (grep(/^\Q$i\E$/,@archdirs))) {
                   12704:                                 $todeletedir{$prefix.$path} = 1;
                   12705:                             } else {
                   12706:                                 $todelete{$prefix.$path} = 1;
                   12707:                             }
1.1055    raeburn  12708:                         }
                   12709:                     }
                   12710:                 } elsif ($env{'form.archive_'.$i} eq 'display') {
1.1059    raeburn  12711:                     my ($docstitle,$title,$url,$outer);
1.1055    raeburn  12712:                     ($title) = ($path =~ m{/([^/]+)$});
1.1059    raeburn  12713:                     $docstitle = $env{'form.archive_title_'.$i};
                   12714:                     if ($docstitle eq '') {
                   12715:                         $docstitle = $title;
                   12716:                     }
1.1055    raeburn  12717:                     $outer = 0;
1.1056    raeburn  12718:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12719:                         if (@{$dirorder{$i}} > 0) {
                   12720:                             foreach my $item (reverse(@{$dirorder{$i}})) {
1.1055    raeburn  12721:                                 if ($env{'form.archive_'.$item} eq 'display') {
                   12722:                                     $outer = $item;
                   12723:                                     last;
                   12724:                                 }
                   12725:                             }
                   12726:                         }
                   12727:                     }
                   12728:                     my ($errtext,$fatal) = 
                   12729:                         &LONCAPA::map::mapread('/uploaded/'.$docudom.'/'.$docuname.
                   12730:                                                '/'.$folders{$outer}.'.'.
                   12731:                                                $containers{$outer});
                   12732:                     next if ($fatal);
                   12733:                     if ((@archdirs > 0) && (grep(/^\Q$i\E$/,@archdirs))) {
                   12734:                         if ($context eq 'coursedocs') {
1.1056    raeburn  12735:                             $mapinner{$i} = time;
1.1055    raeburn  12736:                             $folders{$i} = 'default_'.$mapinner{$i};
                   12737:                             $containers{$i} = 'sequence';
                   12738:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12739:                                       $folders{$i}.'.'.$containers{$i};
                   12740:                             my $newidx = &LONCAPA::map::getresidx();
                   12741:                             $LONCAPA::map::resources[$newidx]=
1.1059    raeburn  12742:                                 $docstitle.':'.$url.':false:normal:res';
1.1055    raeburn  12743:                             push(@LONCAPA::map::order,$newidx);
                   12744:                             my ($outtext,$errtext) =
                   12745:                                 &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12746:                                                         $docuname.'/'.$folders{$outer}.
1.1075.2.11  raeburn  12747:                                                         '.'.$containers{$outer},1,1);
1.1056    raeburn  12748:                             $newseqid{$i} = $newidx;
1.1067    raeburn  12749:                             unless ($errtext) {
1.1075.2.128  raeburn  12750:                                 $result .=  '<li>'.&mt('Folder: [_1] added to course',
                   12751:                                                        &HTML::Entities::encode($docstitle,'<>&"'))..
                   12752:                                             '</li>'."\n";
1.1067    raeburn  12753:                             }
1.1055    raeburn  12754:                         }
                   12755:                     } else {
                   12756:                         if ($context eq 'coursedocs') {
                   12757:                             my $newidx=&LONCAPA::map::getresidx();
                   12758:                             my $url = '/uploaded/'.$docudom.'/'.$docuname.'/'.
                   12759:                                       $docstype.'/'.$mapinner{$outer}.'/'.$newidx.'/'.
                   12760:                                       $title;
1.1075.2.128  raeburn  12761:                             if (($outer !~ /\D/) && ($mapinner{$outer} !~ /\D/) && ($newidx !~ /\D/)) {
                   12762:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}") {
                   12763:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}",0755);
1.1067    raeburn  12764:                                 }
1.1075.2.128  raeburn  12765:                                 if (!-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12766:                                     mkdir("$prefix$dir/$docstype/$mapinner{$outer}/$newidx");
                   12767:                                 }
                   12768:                                 if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx") {
                   12769:                                     if (rename("$prefix$path","$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title")) {
                   12770:                                         $newdest{$i} = "$prefix$dir/$docstype/$mapinner{$outer}/$newidx";
                   12771:                                         unless ($ishome) {
                   12772:                                             my $fetch = "$newdest{$i}/$title";
                   12773:                                             $fetch =~ s/^\Q$prefix$dir\E//;
                   12774:                                             $prompttofetch{$fetch} = 1;
                   12775:                                         }
                   12776:                                    }
                   12777:                                 }
                   12778:                                 $LONCAPA::map::resources[$newidx]=
                   12779:                                     $docstitle.':'.$url.':false:normal:res';
                   12780:                                 push(@LONCAPA::map::order, $newidx);
                   12781:                                 my ($outtext,$errtext)=
                   12782:                                     &LONCAPA::map::storemap('/uploaded/'.$docudom.'/'.
                   12783:                                                             $docuname.'/'.$folders{$outer}.
                   12784:                                                             '.'.$containers{$outer},1,1);
                   12785:                                 unless ($errtext) {
                   12786:                                     if (-e "$prefix$dir/$docstype/$mapinner{$outer}/$newidx/$title") {
                   12787:                                         $result .= '<li>'.&mt('File: [_1] added to course',
                   12788:                                                               &HTML::Entities::encode($docstitle,'<>&"')).
                   12789:                                                    '</li>'."\n";
                   12790:                                     }
1.1067    raeburn  12791:                                 }
1.1075.2.128  raeburn  12792:                             } else {
                   12793:                                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12794:                                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1067    raeburn  12795:                             }
1.1055    raeburn  12796:                         }
                   12797:                     }
1.1075.2.11  raeburn  12798:                 }
                   12799:             } else {
1.1075.2.128  raeburn  12800:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12801:                                 &HTML::Entities::encode($path,'<>&"')).'<br />';
1.1075.2.11  raeburn  12802:             }
                   12803:         }
                   12804:         for (my $i=1; $i<=$numitems; $i++) {
                   12805:             next unless ($env{'form.archive_'.$i} eq 'dependency');
                   12806:             my $path = $env{'form.archive_content_'.$i};
                   12807:             if ($path =~ /^\Q$pathtocheck\E/) {
                   12808:                 my ($title) = ($path =~ m{/([^/]+)$});
                   12809:                 $referrer{$i} = $env{'form.archive_dependent_on_'.$i};
                   12810:                 if ($env{'form.archive_'.$referrer{$i}} eq 'display') {
                   12811:                     if (ref($dirorder{$i}) eq 'ARRAY') {
                   12812:                         my ($itemidx,$fullpath,$relpath);
                   12813:                         if (ref($dirorder{$referrer{$i}}) eq 'ARRAY') {
                   12814:                             my $container = $dirorder{$referrer{$i}}->[-1];
1.1056    raeburn  12815:                             for (my $j=0; $j<@{$dirorder{$i}}; $j++) {
1.1075.2.11  raeburn  12816:                                 if ($dirorder{$i}->[$j] eq $container) {
                   12817:                                     $itemidx = $j;
1.1056    raeburn  12818:                                 }
                   12819:                             }
1.1075.2.11  raeburn  12820:                         }
                   12821:                         if ($itemidx eq '') {
                   12822:                             $itemidx =  0;
                   12823:                         }
                   12824:                         if (grep(/^\Q$referrer{$i}\E$/,@archdirs)) {
                   12825:                             if ($mapinner{$referrer{$i}}) {
                   12826:                                 $fullpath = "$prefix$dir/$docstype/$mapinner{$referrer{$i}}";
                   12827:                                 for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12828:                                     if (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12829:                                         unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12830:                                             $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12831:                                             $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12832:                                             if (!-e $fullpath) {
                   12833:                                                 mkdir($fullpath,0755);
1.1056    raeburn  12834:                                             }
                   12835:                                         }
1.1075.2.11  raeburn  12836:                                     } else {
                   12837:                                         last;
1.1056    raeburn  12838:                                     }
1.1075.2.11  raeburn  12839:                                 }
                   12840:                             }
                   12841:                         } elsif ($newdest{$referrer{$i}}) {
                   12842:                             $fullpath = $newdest{$referrer{$i}};
                   12843:                             for (my $j=$itemidx; $j<@{$dirorder{$i}}; $j++) {
                   12844:                                 if ($env{'form.archive_'.$dirorder{$i}->[$j]} eq 'discard') {
                   12845:                                     $orphaned{$i} = $env{'form.archive_'.$dirorder{$i}->[$j]};
                   12846:                                     last;
                   12847:                                 } elsif (grep(/^\Q$dirorder{$i}->[$j]\E$/,@archdirs)) {
                   12848:                                     unless (defined($newseqid{$dirorder{$i}->[$j]})) {
                   12849:                                         $fullpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12850:                                         $relpath .= '/'.$titles{$dirorder{$i}->[$j]};
                   12851:                                         if (!-e $fullpath) {
                   12852:                                             mkdir($fullpath,0755);
1.1056    raeburn  12853:                                         }
                   12854:                                     }
1.1075.2.11  raeburn  12855:                                 } else {
                   12856:                                     last;
1.1056    raeburn  12857:                                 }
1.1075.2.11  raeburn  12858:                             }
                   12859:                         }
                   12860:                         if ($fullpath ne '') {
                   12861:                             if (-e "$prefix$path") {
1.1075.2.128  raeburn  12862:                                 unless (rename("$prefix$path","$fullpath/$title")) {
                   12863:                                      $warning .= &mt('Failed to rename dependency').'<br />';
                   12864:                                 }
1.1075.2.11  raeburn  12865:                             }
                   12866:                             if (-e "$fullpath/$title") {
                   12867:                                 my $showpath;
                   12868:                                 if ($relpath ne '') {
                   12869:                                     $showpath = "$relpath/$title";
                   12870:                                 } else {
                   12871:                                     $showpath = "/$title";
1.1056    raeburn  12872:                                 }
1.1075.2.128  raeburn  12873:                                 $result .= '<li>'.&mt('[_1] included as a dependency',
                   12874:                                                       &HTML::Entities::encode($showpath,'<>&"')).
                   12875:                                            '</li>'."\n";
                   12876:                                 unless ($ishome) {
                   12877:                                     my $fetch = "$fullpath/$title";
                   12878:                                     $fetch =~ s/^\Q$prefix$dir\E//;
                   12879:                                     $prompttofetch{$fetch} = 1;
                   12880:                                 }
1.1055    raeburn  12881:                             }
                   12882:                         }
                   12883:                     }
1.1075.2.11  raeburn  12884:                 } elsif ($env{'form.archive_'.$referrer{$i}} eq 'discard') {
                   12885:                     $warning .= &mt('[_1] is a dependency of [_2], which was discarded.',
1.1075.2.128  raeburn  12886:                                     &HTML::Entities::encode($path,'<>&"'),
                   12887:                                     &HTML::Entities::encode($env{'form.archive_content_'.$referrer{$i}},'<>&"')).
                   12888:                                 '<br />';
1.1055    raeburn  12889:                 }
                   12890:             } else {
1.1075.2.128  raeburn  12891:                 $warning .= &mt('Item extracted from archive: [_1] has unexpected path.',
                   12892:                                 &HTML::Entities::encode($path)).'<br />';
1.1055    raeburn  12893:             }
                   12894:         }
                   12895:         if (keys(%todelete)) {
                   12896:             foreach my $key (keys(%todelete)) {
                   12897:                 unlink($key);
1.1066    raeburn  12898:             }
                   12899:         }
                   12900:         if (keys(%todeletedir)) {
                   12901:             foreach my $key (keys(%todeletedir)) {
                   12902:                 rmdir($key);
                   12903:             }
                   12904:         }
                   12905:         foreach my $dir (sort(keys(%is_dir))) {
                   12906:             if (($pathtocheck ne '') && ($dir ne ''))  {
                   12907:                 &cleanup_empty_dirs($prefix."$pathtocheck/$dir");
1.1055    raeburn  12908:             }
                   12909:         }
1.1067    raeburn  12910:         if ($result ne '') {
                   12911:             $output .= '<ul>'."\n".
                   12912:                        $result."\n".
                   12913:                        '</ul>';
                   12914:         }
                   12915:         unless ($ishome) {
                   12916:             my $replicationfail;
                   12917:             foreach my $item (keys(%prompttofetch)) {
                   12918:                 my $fetchresult= &Apache::lonnet::reply('fetchuserfile:'.$item,$docuhome);
                   12919:                 unless ($fetchresult eq 'ok') {
                   12920:                     $replicationfail .= '<li>'.$item.'</li>'."\n";
                   12921:                 }
                   12922:             }
                   12923:             if ($replicationfail) {
                   12924:                 $output .= '<p class="LC_error">'.
                   12925:                            &mt('Course home server failed to retrieve:').'<ul>'.
                   12926:                            $replicationfail.
                   12927:                            '</ul></p>';
                   12928:             }
                   12929:         }
1.1055    raeburn  12930:     } else {
                   12931:         $warning = &mt('No items found in archive.');
                   12932:     }
                   12933:     if ($error) {
                   12934:         $output .= '<p class="LC_error">'.&mt('Not extracted.').'<br />'.
                   12935:                    $error.'</p>'."\n";
                   12936:     }
                   12937:     if ($warning) {
                   12938:         $output .= '<p class="LC_warning">'.$warning.'</p>'."\n";
                   12939:     }
                   12940:     return $output;
                   12941: }
                   12942: 
1.1066    raeburn  12943: sub cleanup_empty_dirs {
                   12944:     my ($path) = @_;
                   12945:     if (($path ne '') && (-d $path)) {
                   12946:         if (opendir(my $dirh,$path)) {
                   12947:             my @dircontents = grep(!/^\./,readdir($dirh));
                   12948:             my $numitems = 0;
                   12949:             foreach my $item (@dircontents) {
                   12950:                 if (-d "$path/$item") {
1.1075.2.28  raeburn  12951:                     &cleanup_empty_dirs("$path/$item");
1.1066    raeburn  12952:                     if (-e "$path/$item") {
                   12953:                         $numitems ++;
                   12954:                     }
                   12955:                 } else {
                   12956:                     $numitems ++;
                   12957:                 }
                   12958:             }
                   12959:             if ($numitems == 0) {
                   12960:                 rmdir($path);
                   12961:             }
                   12962:             closedir($dirh);
                   12963:         }
                   12964:     }
                   12965:     return;
                   12966: }
                   12967: 
1.41      ng       12968: =pod
1.45      matthew  12969: 
1.1075.2.56  raeburn  12970: =item * &get_folder_hierarchy()
1.1068    raeburn  12971: 
                   12972: Provides hierarchy of names of folders/sub-folders containing the current
                   12973: item,
                   12974: 
                   12975: Inputs: 3
                   12976:      - $navmap - navmaps object
                   12977: 
                   12978:      - $map - url for map (either the trigger itself, or map containing
                   12979:                            the resource, which is the trigger).
                   12980: 
                   12981:      - $showitem - 1 => show title for map itself; 0 => do not show.
                   12982: 
                   12983: Outputs: 1 @pathitems - array of folder/subfolder names.
                   12984: 
                   12985: =cut
                   12986: 
                   12987: sub get_folder_hierarchy {
                   12988:     my ($navmap,$map,$showitem) = @_;
                   12989:     my @pathitems;
                   12990:     if (ref($navmap)) {
                   12991:         my $mapres = $navmap->getResourceByUrl($map);
                   12992:         if (ref($mapres)) {
                   12993:             my $pcslist = $mapres->map_hierarchy();
                   12994:             if ($pcslist ne '') {
                   12995:                 my @pcs = split(/,/,$pcslist);
                   12996:                 foreach my $pc (@pcs) {
                   12997:                     if ($pc == 1) {
1.1075.2.38  raeburn  12998:                         push(@pathitems,&mt('Main Content'));
1.1068    raeburn  12999:                     } else {
                   13000:                         my $res = $navmap->getByMapPc($pc);
                   13001:                         if (ref($res)) {
                   13002:                             my $title = $res->compTitle();
                   13003:                             $title =~ s/\W+/_/g;
                   13004:                             if ($title ne '') {
                   13005:                                 push(@pathitems,$title);
                   13006:                             }
                   13007:                         }
                   13008:                     }
                   13009:                 }
                   13010:             }
1.1071    raeburn  13011:             if ($showitem) {
                   13012:                 if ($mapres->{ID} eq '0.0') {
1.1075.2.38  raeburn  13013:                     push(@pathitems,&mt('Main Content'));
1.1071    raeburn  13014:                 } else {
                   13015:                     my $maptitle = $mapres->compTitle();
                   13016:                     $maptitle =~ s/\W+/_/g;
                   13017:                     if ($maptitle ne '') {
                   13018:                         push(@pathitems,$maptitle);
                   13019:                     }
1.1068    raeburn  13020:                 }
                   13021:             }
                   13022:         }
                   13023:     }
                   13024:     return @pathitems;
                   13025: }
                   13026: 
                   13027: =pod
                   13028: 
1.1015    raeburn  13029: =item * &get_turnedin_filepath()
                   13030: 
                   13031: Determines path in a user's portfolio file for storage of files uploaded
                   13032: to a specific essayresponse or dropbox item.
                   13033: 
                   13034: Inputs: 3 required + 1 optional.
                   13035: $symb is symb for resource, $uname and $udom are for current user (required).
                   13036: $caller is optional (can be "submission", if routine is called when storing
                   13037: an upoaded file when "Submit Answer" button was pressed).
                   13038: 
                   13039: Returns array containing $path and $multiresp. 
                   13040: $path is path in portfolio.  $multiresp is 1 if this resource contains more
                   13041: than one file upload item.  Callers of routine should append partid as a 
                   13042: subdirectory to $path in cases where $multiresp is 1.
                   13043: 
                   13044: Called by: homework/essayresponse.pm and homework/structuretags.pm
                   13045: 
                   13046: =cut
                   13047: 
                   13048: sub get_turnedin_filepath {
                   13049:     my ($symb,$uname,$udom,$caller) = @_;
                   13050:     my ($map,$resid,$resurl)=&Apache::lonnet::decode_symb($symb);
                   13051:     my $turnindir;
                   13052:     my %userhash = &Apache::lonnet::userenvironment($udom,$uname,'turnindir');
                   13053:     $turnindir = $userhash{'turnindir'};
                   13054:     my ($path,$multiresp);
                   13055:     if ($turnindir eq '') {
                   13056:         if ($caller eq 'submission') {
                   13057:             $turnindir = &mt('turned in');
                   13058:             $turnindir =~ s/\W+/_/g;
                   13059:             my %newhash = (
                   13060:                             'turnindir' => $turnindir,
                   13061:                           );
                   13062:             &Apache::lonnet::put('environment',\%newhash,$udom,$uname);
                   13063:         }
                   13064:     }
                   13065:     if ($turnindir ne '') {
                   13066:         $path = '/'.$turnindir.'/';
                   13067:         my ($multipart,$turnin,@pathitems);
                   13068:         my $navmap = Apache::lonnavmaps::navmap->new();
                   13069:         if (defined($navmap)) {
                   13070:             my $mapres = $navmap->getResourceByUrl($map);
                   13071:             if (ref($mapres)) {
                   13072:                 my $pcslist = $mapres->map_hierarchy();
                   13073:                 if ($pcslist ne '') {
                   13074:                     foreach my $pc (split(/,/,$pcslist)) {
                   13075:                         my $res = $navmap->getByMapPc($pc);
                   13076:                         if (ref($res)) {
                   13077:                             my $title = $res->compTitle();
                   13078:                             $title =~ s/\W+/_/g;
                   13079:                             if ($title ne '') {
1.1075.2.48  raeburn  13080:                                 if (($pc > 1) && (length($title) > 12)) {
                   13081:                                     $title = substr($title,0,12);
                   13082:                                 }
1.1015    raeburn  13083:                                 push(@pathitems,$title);
                   13084:                             }
                   13085:                         }
                   13086:                     }
                   13087:                 }
                   13088:                 my $maptitle = $mapres->compTitle();
                   13089:                 $maptitle =~ s/\W+/_/g;
                   13090:                 if ($maptitle ne '') {
1.1075.2.48  raeburn  13091:                     if (length($maptitle) > 12) {
                   13092:                         $maptitle = substr($maptitle,0,12);
                   13093:                     }
1.1015    raeburn  13094:                     push(@pathitems,$maptitle);
                   13095:                 }
                   13096:                 unless ($env{'request.state'} eq 'construct') {
                   13097:                     my $res = $navmap->getBySymb($symb);
                   13098:                     if (ref($res)) {
                   13099:                         my $partlist = $res->parts();
                   13100:                         my $totaluploads = 0;
                   13101:                         if (ref($partlist) eq 'ARRAY') {
                   13102:                             foreach my $part (@{$partlist}) {
                   13103:                                 my @types = $res->responseType($part);
                   13104:                                 my @ids = $res->responseIds($part);
                   13105:                                 for (my $i=0; $i < scalar(@ids); $i++) {
                   13106:                                     if ($types[$i] eq 'essay') {
                   13107:                                         my $partid = $part.'_'.$ids[$i];
                   13108:                                         if (&Apache::lonnet::EXT("resource.$partid.uploadedfiletypes") ne '') {
                   13109:                                             $totaluploads ++;
                   13110:                                         }
                   13111:                                     }
                   13112:                                 }
                   13113:                             }
                   13114:                             if ($totaluploads > 1) {
                   13115:                                 $multiresp = 1;
                   13116:                             }
                   13117:                         }
                   13118:                     }
                   13119:                 }
                   13120:             } else {
                   13121:                 return;
                   13122:             }
                   13123:         } else {
                   13124:             return;
                   13125:         }
                   13126:         my $restitle=&Apache::lonnet::gettitle($symb);
                   13127:         $restitle =~ s/\W+/_/g;
                   13128:         if ($restitle eq '') {
                   13129:             $restitle = ($resurl =~ m{/[^/]+$});
                   13130:             if ($restitle eq '') {
                   13131:                 $restitle = time;
                   13132:             }
                   13133:         }
1.1075.2.48  raeburn  13134:         if (length($restitle) > 12) {
                   13135:             $restitle = substr($restitle,0,12);
                   13136:         }
1.1015    raeburn  13137:         push(@pathitems,$restitle);
                   13138:         $path .= join('/',@pathitems);
                   13139:     }
                   13140:     return ($path,$multiresp);
                   13141: }
                   13142: 
                   13143: =pod
                   13144: 
1.464     albertel 13145: =back
1.41      ng       13146: 
1.112     bowersj2 13147: =head1 CSV Upload/Handling functions
1.38      albertel 13148: 
1.41      ng       13149: =over 4
                   13150: 
1.648     raeburn  13151: =item * &upfile_store($r)
1.41      ng       13152: 
                   13153: Store uploaded file, $r should be the HTTP Request object,
1.258     albertel 13154: needs $env{'form.upfile'}
1.41      ng       13155: returns $datatoken to be put into hidden field
                   13156: 
                   13157: =cut
1.31      albertel 13158: 
                   13159: sub upfile_store {
                   13160:     my $r=shift;
1.258     albertel 13161:     $env{'form.upfile'}=~s/\r/\n/gs;
                   13162:     $env{'form.upfile'}=~s/\f/\n/gs;
                   13163:     $env{'form.upfile'}=~s/\n+/\n/gs;
                   13164:     $env{'form.upfile'}=~s/\n+$//gs;
1.31      albertel 13165: 
1.1075.2.128  raeburn  13166:     my $datatoken = &valid_datatoken($env{'user.name'}.'_'.$env{'user.domain'}.
                   13167:                                      '_enroll_'.$env{'request.course.id'}.'_'.
                   13168:                                      time.'_'.$$);
                   13169:     return if ($datatoken eq '');
                   13170: 
1.31      albertel 13171:     {
1.158     raeburn  13172:         my $datafile = $r->dir_config('lonDaemons').
                   13173:                            '/tmp/'.$datatoken.'.tmp';
1.1075.2.128  raeburn  13174:         if ( open(my $fh,'>',$datafile) ) {
1.258     albertel 13175:             print $fh $env{'form.upfile'};
1.158     raeburn  13176:             close($fh);
                   13177:         }
1.31      albertel 13178:     }
                   13179:     return $datatoken;
                   13180: }
                   13181: 
1.56      matthew  13182: =pod
                   13183: 
1.1075.2.128  raeburn  13184: =item * &load_tmp_file($r,$datatoken)
1.41      ng       13185: 
                   13186: Load uploaded file from tmp, $r should be the HTTP Request object,
1.1075.2.128  raeburn  13187: $datatoken is the name to assign to the temporary file.
1.258     albertel 13188: sets $env{'form.upfile'} to the contents of the file
1.41      ng       13189: 
                   13190: =cut
1.31      albertel 13191: 
                   13192: sub load_tmp_file {
1.1075.2.128  raeburn  13193:     my ($r,$datatoken) = @_;
                   13194:     return if ($datatoken eq '');
1.31      albertel 13195:     my @studentdata=();
                   13196:     {
1.158     raeburn  13197:         my $studentfile = $r->dir_config('lonDaemons').
1.1075.2.128  raeburn  13198:                               '/tmp/'.$datatoken.'.tmp';
                   13199:         if ( open(my $fh,'<',$studentfile) ) {
1.158     raeburn  13200:             @studentdata=<$fh>;
                   13201:             close($fh);
                   13202:         }
1.31      albertel 13203:     }
1.258     albertel 13204:     $env{'form.upfile'}=join('',@studentdata);
1.31      albertel 13205: }
                   13206: 
1.1075.2.128  raeburn  13207: sub valid_datatoken {
                   13208:     my ($datatoken) = @_;
1.1075.2.131  raeburn  13209:     if ($datatoken =~ /^$match_username\_$match_domain\_enroll_(|$match_domain\_$match_courseid)\_\d+_\d+$/) {
1.1075.2.128  raeburn  13210:         return $datatoken;
                   13211:     }
                   13212:     return;
                   13213: }
                   13214: 
1.56      matthew  13215: =pod
                   13216: 
1.648     raeburn  13217: =item * &upfile_record_sep()
1.41      ng       13218: 
                   13219: Separate uploaded file into records
                   13220: returns array of records,
1.258     albertel 13221: needs $env{'form.upfile'} and $env{'form.upfiletype'}
1.41      ng       13222: 
                   13223: =cut
1.31      albertel 13224: 
                   13225: sub upfile_record_sep {
1.258     albertel 13226:     if ($env{'form.upfiletype'} eq 'xml') {
1.31      albertel 13227:     } else {
1.248     albertel 13228: 	my @records;
1.258     albertel 13229: 	foreach my $line (split(/\n/,$env{'form.upfile'})) {
1.248     albertel 13230: 	    if ($line=~/^\s*$/) { next; }
                   13231: 	    push(@records,$line);
                   13232: 	}
                   13233: 	return @records;
1.31      albertel 13234:     }
                   13235: }
                   13236: 
1.56      matthew  13237: =pod
                   13238: 
1.648     raeburn  13239: =item * &record_sep($record)
1.41      ng       13240: 
1.258     albertel 13241: Separate a record into fields $record should be an item from the upfile_record_sep(), needs $env{'form.upfiletype'}
1.41      ng       13242: 
                   13243: =cut
                   13244: 
1.263     www      13245: sub takeleft {
                   13246:     my $index=shift;
                   13247:     return substr('0000'.$index,-4,4);
                   13248: }
                   13249: 
1.31      albertel 13250: sub record_sep {
                   13251:     my $record=shift;
                   13252:     my %components=();
1.258     albertel 13253:     if ($env{'form.upfiletype'} eq 'xml') {
                   13254:     } elsif ($env{'form.upfiletype'} eq 'space') {
1.31      albertel 13255:         my $i=0;
1.356     albertel 13256:         foreach my $field (split(/\s+/,$record)) {
1.31      albertel 13257:             $field=~s/^(\"|\')//;
                   13258:             $field=~s/(\"|\')$//;
1.263     www      13259:             $components{&takeleft($i)}=$field;
1.31      albertel 13260:             $i++;
                   13261:         }
1.258     albertel 13262:     } elsif ($env{'form.upfiletype'} eq 'tab') {
1.31      albertel 13263:         my $i=0;
1.356     albertel 13264:         foreach my $field (split(/\t/,$record)) {
1.31      albertel 13265:             $field=~s/^(\"|\')//;
                   13266:             $field=~s/(\"|\')$//;
1.263     www      13267:             $components{&takeleft($i)}=$field;
1.31      albertel 13268:             $i++;
                   13269:         }
                   13270:     } else {
1.561     www      13271:         my $separator=',';
1.480     banghart 13272:         if ($env{'form.upfiletype'} eq 'semisv') {
1.561     www      13273:             $separator=';';
1.480     banghart 13274:         }
1.31      albertel 13275:         my $i=0;
1.561     www      13276: # the character we are looking for to indicate the end of a quote or a record 
                   13277:         my $looking_for=$separator;
                   13278: # do not add the characters to the fields
                   13279:         my $ignore=0;
                   13280: # we just encountered a separator (or the beginning of the record)
                   13281:         my $just_found_separator=1;
                   13282: # store the field we are working on here
                   13283:         my $field='';
                   13284: # work our way through all characters in record
                   13285:         foreach my $character ($record=~/(.)/g) {
                   13286:             if ($character eq $looking_for) {
                   13287:                if ($character ne $separator) {
                   13288: # Found the end of a quote, again looking for separator
                   13289:                   $looking_for=$separator;
                   13290:                   $ignore=1;
                   13291:                } else {
                   13292: # Found a separator, store away what we got
                   13293:                   $components{&takeleft($i)}=$field;
                   13294: 	          $i++;
                   13295:                   $just_found_separator=1;
                   13296:                   $ignore=0;
                   13297:                   $field='';
                   13298:                }
                   13299:                next;
                   13300:             }
                   13301: # single or double quotation marks after a separator indicate beginning of a quote
                   13302: # we are now looking for the end of the quote and need to ignore separators
                   13303:             if ((($character eq '"') || ($character eq "'")) && ($just_found_separator))  {
                   13304:                $looking_for=$character;
                   13305:                next;
                   13306:             }
                   13307: # ignore would be true after we reached the end of a quote
                   13308:             if ($ignore) { next; }
                   13309:             if (($just_found_separator) && ($character=~/\s/)) { next; }
                   13310:             $field.=$character;
                   13311:             $just_found_separator=0; 
1.31      albertel 13312:         }
1.561     www      13313: # catch the very last entry, since we never encountered the separator
                   13314:         $components{&takeleft($i)}=$field;
1.31      albertel 13315:     }
                   13316:     return %components;
                   13317: }
                   13318: 
1.144     matthew  13319: ######################################################
                   13320: ######################################################
                   13321: 
1.56      matthew  13322: =pod
                   13323: 
1.648     raeburn  13324: =item * &upfile_select_html()
1.41      ng       13325: 
1.144     matthew  13326: Return HTML code to select a file from the users machine and specify 
                   13327: the file type.
1.41      ng       13328: 
                   13329: =cut
                   13330: 
1.144     matthew  13331: ######################################################
                   13332: ######################################################
1.31      albertel 13333: sub upfile_select_html {
1.144     matthew  13334:     my %Types = (
                   13335:                  csv   => &mt('CSV (comma separated values, spreadsheet)'),
1.480     banghart 13336:                  semisv => &mt('Semicolon separated values'),
1.144     matthew  13337:                  space => &mt('Space separated'),
                   13338:                  tab   => &mt('Tabulator separated'),
                   13339: #                 xml   => &mt('HTML/XML'),
                   13340:                  );
                   13341:     my $Str = '<input type="file" name="upfile" size="50" />'.
1.727     riegler  13342:         '<br />'.&mt('Type').': <select name="upfiletype">';
1.144     matthew  13343:     foreach my $type (sort(keys(%Types))) {
                   13344:         $Str .= '<option value="'.$type.'" >'.$Types{$type}."</option>\n";
                   13345:     }
                   13346:     $Str .= "</select>\n";
                   13347:     return $Str;
1.31      albertel 13348: }
                   13349: 
1.301     albertel 13350: sub get_samples {
                   13351:     my ($records,$toget) = @_;
                   13352:     my @samples=({});
                   13353:     my $got=0;
                   13354:     foreach my $rec (@$records) {
                   13355: 	my %temp = &record_sep($rec);
                   13356: 	if (! grep(/\S/, values(%temp))) { next; }
                   13357: 	if (%temp) {
                   13358: 	    $samples[$got]=\%temp;
                   13359: 	    $got++;
                   13360: 	    if ($got == $toget) { last; }
                   13361: 	}
                   13362:     }
                   13363:     return \@samples;
                   13364: }
                   13365: 
1.144     matthew  13366: ######################################################
                   13367: ######################################################
                   13368: 
1.56      matthew  13369: =pod
                   13370: 
1.648     raeburn  13371: =item * &csv_print_samples($r,$records)
1.41      ng       13372: 
                   13373: Prints a table of sample values from each column uploaded $r is an
                   13374: Apache Request ref, $records is an arrayref from
                   13375: &Apache::loncommon::upfile_record_sep
                   13376: 
                   13377: =cut
                   13378: 
1.144     matthew  13379: ######################################################
                   13380: ######################################################
1.31      albertel 13381: sub csv_print_samples {
                   13382:     my ($r,$records) = @_;
1.662     bisitz   13383:     my $samples = &get_samples($records,5);
1.301     albertel 13384: 
1.594     raeburn  13385:     $r->print(&mt('Samples').'<br />'.&start_data_table().
                   13386:               &start_data_table_header_row());
1.356     albertel 13387:     foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) { 
1.845     bisitz   13388:         $r->print('<th>'.&mt('Column [_1]',($sample+1)).'</th>'); }
1.594     raeburn  13389:     $r->print(&end_data_table_header_row());
1.301     albertel 13390:     foreach my $hash (@$samples) {
1.594     raeburn  13391: 	$r->print(&start_data_table_row());
1.356     albertel 13392: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
1.31      albertel 13393: 	    $r->print('<td>');
1.356     albertel 13394: 	    if (defined($$hash{$sample})) { $r->print($$hash{$sample}); }
1.31      albertel 13395: 	    $r->print('</td>');
                   13396: 	}
1.594     raeburn  13397: 	$r->print(&end_data_table_row());
1.31      albertel 13398:     }
1.594     raeburn  13399:     $r->print(&end_data_table().'<br />'."\n");
1.31      albertel 13400: }
                   13401: 
1.144     matthew  13402: ######################################################
                   13403: ######################################################
                   13404: 
1.56      matthew  13405: =pod
                   13406: 
1.648     raeburn  13407: =item * &csv_print_select_table($r,$records,$d)
1.41      ng       13408: 
                   13409: Prints a table to create associations between values and table columns.
1.144     matthew  13410: 
1.41      ng       13411: $r is an Apache Request ref,
                   13412: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
1.174     matthew  13413: $d is an array of 2 element arrays (internal name, displayed name,defaultcol)
1.41      ng       13414: 
                   13415: =cut
                   13416: 
1.144     matthew  13417: ######################################################
                   13418: ######################################################
1.31      albertel 13419: sub csv_print_select_table {
                   13420:     my ($r,$records,$d) = @_;
1.301     albertel 13421:     my $i=0;
                   13422:     my $samples = &get_samples($records,1);
1.144     matthew  13423:     $r->print(&mt('Associate columns with student attributes.')."\n".
1.594     raeburn  13424: 	      &start_data_table().&start_data_table_header_row().
1.144     matthew  13425:               '<th>'.&mt('Attribute').'</th>'.
1.594     raeburn  13426:               '<th>'.&mt('Column').'</th>'.
                   13427:               &end_data_table_header_row()."\n");
1.356     albertel 13428:     foreach my $array_ref (@$d) {
                   13429: 	my ($value,$display,$defaultcol)=@{ $array_ref };
1.729     raeburn  13430: 	$r->print(&start_data_table_row().'<td>'.$display.'</td>');
1.31      albertel 13431: 
1.875     bisitz   13432: 	$r->print('<td><select name="f'.$i.'"'.
1.32      matthew  13433: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.31      albertel 13434: 	$r->print('<option value="none"></option>');
1.356     albertel 13435: 	foreach my $sample (sort({$a <=> $b} keys(%{ $samples->[0] }))) {
                   13436: 	    $r->print('<option value="'.$sample.'"'.
                   13437:                       ($sample eq $defaultcol ? ' selected="selected" ' : '').
1.662     bisitz   13438:                       '>'.&mt('Column [_1]',($sample+1)).'</option>');
1.31      albertel 13439: 	}
1.594     raeburn  13440: 	$r->print('</select></td>'.&end_data_table_row()."\n");
1.31      albertel 13441: 	$i++;
                   13442:     }
1.594     raeburn  13443:     $r->print(&end_data_table());
1.31      albertel 13444:     $i--;
                   13445:     return $i;
                   13446: }
1.56      matthew  13447: 
1.144     matthew  13448: ######################################################
                   13449: ######################################################
                   13450: 
1.56      matthew  13451: =pod
1.31      albertel 13452: 
1.648     raeburn  13453: =item * &csv_samples_select_table($r,$records,$d)
1.41      ng       13454: 
                   13455: Prints a table of sample values from the upload and can make associate samples to internal names.
                   13456: 
                   13457: $r is an Apache Request ref,
                   13458: $records is an arrayref from &Apache::loncommon::upfile_record_sep,
                   13459: $d is an array of 2 element arrays (internal name, displayed name)
                   13460: 
                   13461: =cut
                   13462: 
1.144     matthew  13463: ######################################################
                   13464: ######################################################
1.31      albertel 13465: sub csv_samples_select_table {
                   13466:     my ($r,$records,$d) = @_;
                   13467:     my $i=0;
1.144     matthew  13468:     #
1.662     bisitz   13469:     my $max_samples = 5;
                   13470:     my $samples = &get_samples($records,$max_samples);
1.594     raeburn  13471:     $r->print(&start_data_table().
                   13472:               &start_data_table_header_row().'<th>'.
                   13473:               &mt('Field').'</th><th>'.&mt('Samples').'</th>'.
                   13474:               &end_data_table_header_row());
1.301     albertel 13475: 
                   13476:     foreach my $key (sort(keys(%{ $samples->[0] }))) {
1.594     raeburn  13477: 	$r->print(&start_data_table_row().'<td><select name="f'.$i.'"'.
1.32      matthew  13478: 		  ' onchange="javascript:flip(this.form,'.$i.');">');
1.301     albertel 13479: 	foreach my $option (@$d) {
                   13480: 	    my ($value,$display,$defaultcol)=@{ $option };
1.174     matthew  13481: 	    $r->print('<option value="'.$value.'"'.
1.253     albertel 13482:                       ($i eq $defaultcol ? ' selected="selected" ':'').'>'.
1.174     matthew  13483:                       $display.'</option>');
1.31      albertel 13484: 	}
                   13485: 	$r->print('</select></td><td>');
1.662     bisitz   13486: 	foreach my $line (0..($max_samples-1)) {
1.301     albertel 13487: 	    if (defined($samples->[$line]{$key})) { 
                   13488: 		$r->print($samples->[$line]{$key}."<br />\n"); 
                   13489: 	    }
                   13490: 	}
1.594     raeburn  13491: 	$r->print('</td>'.&end_data_table_row());
1.31      albertel 13492: 	$i++;
                   13493:     }
1.594     raeburn  13494:     $r->print(&end_data_table());
1.31      albertel 13495:     $i--;
                   13496:     return($i);
1.115     matthew  13497: }
                   13498: 
1.144     matthew  13499: ######################################################
                   13500: ######################################################
                   13501: 
1.115     matthew  13502: =pod
                   13503: 
1.648     raeburn  13504: =item * &clean_excel_name($name)
1.115     matthew  13505: 
                   13506: Returns a replacement for $name which does not contain any illegal characters.
                   13507: 
                   13508: =cut
                   13509: 
1.144     matthew  13510: ######################################################
                   13511: ######################################################
1.115     matthew  13512: sub clean_excel_name {
                   13513:     my ($name) = @_;
                   13514:     $name =~ s/[:\*\?\/\\]//g;
                   13515:     if (length($name) > 31) {
                   13516:         $name = substr($name,0,31);
                   13517:     }
                   13518:     return $name;
1.25      albertel 13519: }
1.84      albertel 13520: 
1.85      albertel 13521: =pod
                   13522: 
1.648     raeburn  13523: =item * &check_if_partid_hidden($id,$symb,$udom,$uname)
1.85      albertel 13524: 
                   13525: Returns either 1 or undef
                   13526: 
                   13527: 1 if the part is to be hidden, undef if it is to be shown
                   13528: 
                   13529: Arguments are:
                   13530: 
                   13531: $id the id of the part to be checked
                   13532: $symb, optional the symb of the resource to check
                   13533: $udom, optional the domain of the user to check for
                   13534: $uname, optional the username of the user to check for
                   13535: 
                   13536: =cut
1.84      albertel 13537: 
                   13538: sub check_if_partid_hidden {
                   13539:     my ($id,$symb,$udom,$uname) = @_;
1.133     albertel 13540:     my $hiddenparts=&Apache::lonnet::EXT('resource.0.hiddenparts',
1.84      albertel 13541: 					 $symb,$udom,$uname);
1.141     albertel 13542:     my $truth=1;
                   13543:     #if the string starts with !, then the list is the list to show not hide
                   13544:     if ($hiddenparts=~s/^\s*!//) { $truth=undef; }
1.84      albertel 13545:     my @hiddenlist=split(/,/,$hiddenparts);
                   13546:     foreach my $checkid (@hiddenlist) {
1.141     albertel 13547: 	if ($checkid =~ /^\s*\Q$id\E\s*$/) { return $truth; }
1.84      albertel 13548:     }
1.141     albertel 13549:     return !$truth;
1.84      albertel 13550: }
1.127     matthew  13551: 
1.138     matthew  13552: 
                   13553: ############################################################
                   13554: ############################################################
                   13555: 
                   13556: =pod
                   13557: 
1.157     matthew  13558: =back 
                   13559: 
1.138     matthew  13560: =head1 cgi-bin script and graphing routines
                   13561: 
1.157     matthew  13562: =over 4
                   13563: 
1.648     raeburn  13564: =item * &get_cgi_id()
1.138     matthew  13565: 
                   13566: Inputs: none
                   13567: 
                   13568: Returns an id which can be used to pass environment variables
                   13569: to various cgi-bin scripts.  These environment variables will
                   13570: be removed from the users environment after a given time by
                   13571: the routine &Apache::lonnet::transfer_profile_to_env.
                   13572: 
                   13573: =cut
                   13574: 
                   13575: ############################################################
                   13576: ############################################################
1.152     albertel 13577: my $uniq=0;
1.136     matthew  13578: sub get_cgi_id {
1.154     albertel 13579:     $uniq=($uniq+1)%100000;
1.280     albertel 13580:     return (time.'_'.$$.'_'.$uniq);
1.136     matthew  13581: }
                   13582: 
1.127     matthew  13583: ############################################################
                   13584: ############################################################
                   13585: 
                   13586: =pod
                   13587: 
1.648     raeburn  13588: =item * &DrawBarGraph()
1.127     matthew  13589: 
1.138     matthew  13590: Facilitates the plotting of data in a (stacked) bar graph.
                   13591: Puts plot definition data into the users environment in order for 
                   13592: graph.png to plot it.  Returns an <img> tag for the plot.
                   13593: The bars on the plot are labeled '1','2',...,'n'.
                   13594: 
                   13595: Inputs:
                   13596: 
                   13597: =over 4
                   13598: 
                   13599: =item $Title: string, the title of the plot
                   13600: 
                   13601: =item $xlabel: string, text describing the X-axis of the plot
                   13602: 
                   13603: =item $ylabel: string, text describing the Y-axis of the plot
                   13604: 
                   13605: =item $Max: scalar, the maximum Y value to use in the plot
                   13606: If $Max is < any data point, the graph will not be rendered.
                   13607: 
1.140     matthew  13608: =item $colors: array ref holding the colors to be used for the data sets when
1.138     matthew  13609: they are plotted.  If undefined, default values will be used.
                   13610: 
1.178     matthew  13611: =item $labels: array ref holding the labels to use on the x-axis for the bars.
                   13612: 
1.138     matthew  13613: =item @Values: An array of array references.  Each array reference holds data
                   13614: to be plotted in a stacked bar chart.
                   13615: 
1.239     matthew  13616: =item If the final element of @Values is a hash reference the key/value
                   13617: pairs will be added to the graph definition.
                   13618: 
1.138     matthew  13619: =back
                   13620: 
                   13621: Returns:
                   13622: 
                   13623: An <img> tag which references graph.png and the appropriate identifying
                   13624: information for the plot.
                   13625: 
1.127     matthew  13626: =cut
                   13627: 
                   13628: ############################################################
                   13629: ############################################################
1.134     matthew  13630: sub DrawBarGraph {
1.178     matthew  13631:     my ($Title,$xlabel,$ylabel,$Max,$colors,$labels,@Values)=@_;
1.134     matthew  13632:     #
                   13633:     if (! defined($colors)) {
                   13634:         $colors = ['#33ff00', 
                   13635:                   '#0033cc', '#990000', '#aaaa66', '#663399', '#ff9933',
                   13636:                   '#66ccff', '#ff9999', '#cccc33', '#660000', '#33cc66',
                   13637:                   ]; 
                   13638:     }
1.228     matthew  13639:     my $extra_settings = {};
                   13640:     if (ref($Values[-1]) eq 'HASH') {
                   13641:         $extra_settings = pop(@Values);
                   13642:     }
1.127     matthew  13643:     #
1.136     matthew  13644:     my $identifier = &get_cgi_id();
                   13645:     my $id = 'cgi.'.$identifier;        
1.129     matthew  13646:     if (! @Values || ref($Values[0]) ne 'ARRAY') {
1.127     matthew  13647:         return '';
                   13648:     }
1.225     matthew  13649:     #
                   13650:     my @Labels;
                   13651:     if (defined($labels)) {
                   13652:         @Labels = @$labels;
                   13653:     } else {
                   13654:         for (my $i=0;$i<@{$Values[0]};$i++) {
1.1075.2.119  raeburn  13655:             push(@Labels,$i+1);
1.225     matthew  13656:         }
                   13657:     }
                   13658:     #
1.129     matthew  13659:     my $NumBars = scalar(@{$Values[0]});
1.225     matthew  13660:     if ($NumBars < scalar(@Labels)) { $NumBars = scalar(@Labels); }
1.129     matthew  13661:     my %ValuesHash;
                   13662:     my $NumSets=1;
                   13663:     foreach my $array (@Values) {
                   13664:         next if (! ref($array));
1.136     matthew  13665:         $ValuesHash{$id.'.data.'.$NumSets++} = 
1.132     matthew  13666:             join(',',@$array);
1.129     matthew  13667:     }
1.127     matthew  13668:     #
1.136     matthew  13669:     my ($height,$width,$xskip,$bar_width) = (200,120,1,15);
1.225     matthew  13670:     if ($NumBars < 3) {
                   13671:         $width = 120+$NumBars*32;
1.220     matthew  13672:         $xskip = 1;
1.225     matthew  13673:         $bar_width = 30;
                   13674:     } elsif ($NumBars < 5) {
                   13675:         $width = 120+$NumBars*20;
                   13676:         $xskip = 1;
                   13677:         $bar_width = 20;
1.220     matthew  13678:     } elsif ($NumBars < 10) {
1.136     matthew  13679:         $width = 120+$NumBars*15;
                   13680:         $xskip = 1;
                   13681:         $bar_width = 15;
                   13682:     } elsif ($NumBars <= 25) {
                   13683:         $width = 120+$NumBars*11;
                   13684:         $xskip = 5;
                   13685:         $bar_width = 8;
                   13686:     } elsif ($NumBars <= 50) {
                   13687:         $width = 120+$NumBars*8;
                   13688:         $xskip = 5;
                   13689:         $bar_width = 4;
                   13690:     } else {
                   13691:         $width = 120+$NumBars*8;
                   13692:         $xskip = 5;
                   13693:         $bar_width = 4;
                   13694:     }
                   13695:     #
1.137     matthew  13696:     $Max = 1 if ($Max < 1);
                   13697:     if ( int($Max) < $Max ) {
                   13698:         $Max++;
                   13699:         $Max = int($Max);
                   13700:     }
1.127     matthew  13701:     $Title  = '' if (! defined($Title));
                   13702:     $xlabel = '' if (! defined($xlabel));
                   13703:     $ylabel = '' if (! defined($ylabel));
1.369     www      13704:     $ValuesHash{$id.'.title'}    = &escape($Title);
                   13705:     $ValuesHash{$id.'.xlabel'}   = &escape($xlabel);
                   13706:     $ValuesHash{$id.'.ylabel'}   = &escape($ylabel);
1.137     matthew  13707:     $ValuesHash{$id.'.y_max_value'} = $Max;
1.136     matthew  13708:     $ValuesHash{$id.'.NumBars'}  = $NumBars;
                   13709:     $ValuesHash{$id.'.NumSets'}  = $NumSets;
                   13710:     $ValuesHash{$id.'.PlotType'} = 'bar';
                   13711:     $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13712:     $ValuesHash{$id.'.height'}   = $height;
                   13713:     $ValuesHash{$id.'.width'}    = $width;
                   13714:     $ValuesHash{$id.'.xskip'}    = $xskip;
                   13715:     $ValuesHash{$id.'.bar_width'} = $bar_width;
                   13716:     $ValuesHash{$id.'.labels'} = join(',',@Labels);
1.127     matthew  13717:     #
1.228     matthew  13718:     # Deal with other parameters
                   13719:     while (my ($key,$value) = each(%$extra_settings)) {
                   13720:         $ValuesHash{$id.'.'.$key} = $value;
                   13721:     }
                   13722:     #
1.646     raeburn  13723:     &Apache::lonnet::appenv(\%ValuesHash);
1.137     matthew  13724:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13725: }
                   13726: 
                   13727: ############################################################
                   13728: ############################################################
                   13729: 
                   13730: =pod
                   13731: 
1.648     raeburn  13732: =item * &DrawXYGraph()
1.137     matthew  13733: 
1.138     matthew  13734: Facilitates the plotting of data in an XY graph.
                   13735: Puts plot definition data into the users environment in order for 
                   13736: graph.png to plot it.  Returns an <img> tag for the plot.
                   13737: 
                   13738: Inputs:
                   13739: 
                   13740: =over 4
                   13741: 
                   13742: =item $Title: string, the title of the plot
                   13743: 
                   13744: =item $xlabel: string, text describing the X-axis of the plot
                   13745: 
                   13746: =item $ylabel: string, text describing the Y-axis of the plot
                   13747: 
                   13748: =item $Max: scalar, the maximum Y value to use in the plot
                   13749: If $Max is < any data point, the graph will not be rendered.
                   13750: 
                   13751: =item $colors: Array ref containing the hex color codes for the data to be 
                   13752: plotted in.  If undefined, default values will be used.
                   13753: 
                   13754: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13755: 
                   13756: =item $Ydata: Array ref containing Array refs.  
1.185     www      13757: Each of the contained arrays will be plotted as a separate curve.
1.138     matthew  13758: 
                   13759: =item %Values: hash indicating or overriding any default values which are 
                   13760: passed to graph.png.  
                   13761: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13762: 
                   13763: =back
                   13764: 
                   13765: Returns:
                   13766: 
                   13767: An <img> tag which references graph.png and the appropriate identifying
                   13768: information for the plot.
                   13769: 
1.137     matthew  13770: =cut
                   13771: 
                   13772: ############################################################
                   13773: ############################################################
                   13774: sub DrawXYGraph {
                   13775:     my ($Title,$xlabel,$ylabel,$Max,$colors,$Xlabels,$Ydata,%Values)=@_;
                   13776:     #
                   13777:     # Create the identifier for the graph
                   13778:     my $identifier = &get_cgi_id();
                   13779:     my $id = 'cgi.'.$identifier;
                   13780:     #
                   13781:     $Title  = '' if (! defined($Title));
                   13782:     $xlabel = '' if (! defined($xlabel));
                   13783:     $ylabel = '' if (! defined($ylabel));
                   13784:     my %ValuesHash = 
                   13785:         (
1.369     www      13786:          $id.'.title'  => &escape($Title),
                   13787:          $id.'.xlabel' => &escape($xlabel),
                   13788:          $id.'.ylabel' => &escape($ylabel),
1.137     matthew  13789:          $id.'.y_max_value'=> $Max,
                   13790:          $id.'.labels'     => join(',',@$Xlabels),
                   13791:          $id.'.PlotType'   => 'XY',
                   13792:          );
                   13793:     #
                   13794:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13795:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13796:     }
                   13797:     #
                   13798:     if (! ref($Ydata) || ref($Ydata) ne 'ARRAY') {
                   13799:         return '';
                   13800:     }
                   13801:     my $NumSets=1;
1.138     matthew  13802:     foreach my $array (@{$Ydata}){
1.137     matthew  13803:         next if (! ref($array));
                   13804:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
                   13805:     }
1.138     matthew  13806:     $ValuesHash{$id.'.NumSets'} = $NumSets-1;
1.137     matthew  13807:     #
                   13808:     # Deal with other parameters
                   13809:     while (my ($key,$value) = each(%Values)) {
                   13810:         $ValuesHash{$id.'.'.$key} = $value;
1.127     matthew  13811:     }
                   13812:     #
1.646     raeburn  13813:     &Apache::lonnet::appenv(\%ValuesHash);
1.136     matthew  13814:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
                   13815: }
                   13816: 
                   13817: ############################################################
                   13818: ############################################################
                   13819: 
                   13820: =pod
                   13821: 
1.648     raeburn  13822: =item * &DrawXYYGraph()
1.138     matthew  13823: 
                   13824: Facilitates the plotting of data in an XY graph with two Y axes.
                   13825: Puts plot definition data into the users environment in order for 
                   13826: graph.png to plot it.  Returns an <img> tag for the plot.
                   13827: 
                   13828: Inputs:
                   13829: 
                   13830: =over 4
                   13831: 
                   13832: =item $Title: string, the title of the plot
                   13833: 
                   13834: =item $xlabel: string, text describing the X-axis of the plot
                   13835: 
                   13836: =item $ylabel: string, text describing the Y-axis of the plot
                   13837: 
                   13838: =item $colors: Array ref containing the hex color codes for the data to be 
                   13839: plotted in.  If undefined, default values will be used.
                   13840: 
                   13841: =item $Xlabels: Array ref containing the labels to be used for the X-axis.
                   13842: 
                   13843: =item $Ydata1: The first data set
                   13844: 
                   13845: =item $Min1: The minimum value of the left Y-axis
                   13846: 
                   13847: =item $Max1: The maximum value of the left Y-axis
                   13848: 
                   13849: =item $Ydata2: The second data set
                   13850: 
                   13851: =item $Min2: The minimum value of the right Y-axis
                   13852: 
                   13853: =item $Max2: The maximum value of the left Y-axis
                   13854: 
                   13855: =item %Values: hash indicating or overriding any default values which are 
                   13856: passed to graph.png.  
                   13857: Possible values are: width, xskip, x_ticks, x_tick_offset, among others.
                   13858: 
                   13859: =back
                   13860: 
                   13861: Returns:
                   13862: 
                   13863: An <img> tag which references graph.png and the appropriate identifying
                   13864: information for the plot.
1.136     matthew  13865: 
                   13866: =cut
                   13867: 
                   13868: ############################################################
                   13869: ############################################################
1.137     matthew  13870: sub DrawXYYGraph {
                   13871:     my ($Title,$xlabel,$ylabel,$colors,$Xlabels,$Ydata1,$Min1,$Max1,
                   13872:                                         $Ydata2,$Min2,$Max2,%Values)=@_;
1.136     matthew  13873:     #
                   13874:     # Create the identifier for the graph
                   13875:     my $identifier = &get_cgi_id();
                   13876:     my $id = 'cgi.'.$identifier;
                   13877:     #
                   13878:     $Title  = '' if (! defined($Title));
                   13879:     $xlabel = '' if (! defined($xlabel));
                   13880:     $ylabel = '' if (! defined($ylabel));
                   13881:     my %ValuesHash = 
                   13882:         (
1.369     www      13883:          $id.'.title'  => &escape($Title),
                   13884:          $id.'.xlabel' => &escape($xlabel),
                   13885:          $id.'.ylabel' => &escape($ylabel),
1.136     matthew  13886:          $id.'.labels' => join(',',@$Xlabels),
                   13887:          $id.'.PlotType' => 'XY',
                   13888:          $id.'.NumSets' => 2,
1.137     matthew  13889:          $id.'.two_axes' => 1,
                   13890:          $id.'.y1_max_value' => $Max1,
                   13891:          $id.'.y1_min_value' => $Min1,
                   13892:          $id.'.y2_max_value' => $Max2,
                   13893:          $id.'.y2_min_value' => $Min2,
1.136     matthew  13894:          );
                   13895:     #
1.137     matthew  13896:     if (defined($colors) && ref($colors) eq 'ARRAY') {
                   13897:         $ValuesHash{$id.'.Colors'}   = join(',',@{$colors});
                   13898:     }
                   13899:     #
                   13900:     if (! ref($Ydata1) || ref($Ydata1) ne 'ARRAY' ||
                   13901:         ! ref($Ydata2) || ref($Ydata2) ne 'ARRAY'){
1.136     matthew  13902:         return '';
                   13903:     }
                   13904:     my $NumSets=1;
1.137     matthew  13905:     foreach my $array ($Ydata1,$Ydata2){
1.136     matthew  13906:         next if (! ref($array));
                   13907:         $ValuesHash{$id.'.data.'.$NumSets++} = join(',',@$array);
1.137     matthew  13908:     }
                   13909:     #
                   13910:     # Deal with other parameters
                   13911:     while (my ($key,$value) = each(%Values)) {
                   13912:         $ValuesHash{$id.'.'.$key} = $value;
1.136     matthew  13913:     }
                   13914:     #
1.646     raeburn  13915:     &Apache::lonnet::appenv(\%ValuesHash);
1.130     albertel 13916:     return '<img src="/cgi-bin/graph.png?'.$identifier.'" border="1" />';
1.139     matthew  13917: }
                   13918: 
                   13919: ############################################################
                   13920: ############################################################
                   13921: 
                   13922: =pod
                   13923: 
1.157     matthew  13924: =back 
                   13925: 
1.139     matthew  13926: =head1 Statistics helper routines?  
                   13927: 
                   13928: Bad place for them but what the hell.
                   13929: 
1.157     matthew  13930: =over 4
                   13931: 
1.648     raeburn  13932: =item * &chartlink()
1.139     matthew  13933: 
                   13934: Returns a link to the chart for a specific student.  
                   13935: 
                   13936: Inputs:
                   13937: 
                   13938: =over 4
                   13939: 
                   13940: =item $linktext: The text of the link
                   13941: 
                   13942: =item $sname: The students username
                   13943: 
                   13944: =item $sdomain: The students domain
                   13945: 
                   13946: =back
                   13947: 
1.157     matthew  13948: =back
                   13949: 
1.139     matthew  13950: =cut
                   13951: 
                   13952: ############################################################
                   13953: ############################################################
                   13954: sub chartlink {
                   13955:     my ($linktext, $sname, $sdomain) = @_;
                   13956:     my $link = '<a href="/adm/statistics?reportSelected=student_assessment'.
1.369     www      13957:         '&amp;SelectedStudent='.&escape($sname.':'.$sdomain).
1.219     albertel 13958:         '&amp;chartoutputmode='.HTML::Entities::encode('html, with all links').
1.139     matthew  13959:        '">'.$linktext.'</a>';
1.153     matthew  13960: }
                   13961: 
                   13962: #######################################################
                   13963: #######################################################
                   13964: 
                   13965: =pod
                   13966: 
                   13967: =head1 Course Environment Routines
1.157     matthew  13968: 
                   13969: =over 4
1.153     matthew  13970: 
1.648     raeburn  13971: =item * &restore_course_settings()
1.153     matthew  13972: 
1.648     raeburn  13973: =item * &store_course_settings()
1.153     matthew  13974: 
                   13975: Restores/Store indicated form parameters from the course environment.
                   13976: Will not overwrite existing values of the form parameters.
                   13977: 
                   13978: Inputs: 
                   13979: a scalar describing the data (e.g. 'chart', 'problem_analysis')
                   13980: 
                   13981: a hash ref describing the data to be stored.  For example:
                   13982:    
                   13983: %Save_Parameters = ('Status' => 'scalar',
                   13984:     'chartoutputmode' => 'scalar',
                   13985:     'chartoutputdata' => 'scalar',
                   13986:     'Section' => 'array',
1.373     raeburn  13987:     'Group' => 'array',
1.153     matthew  13988:     'StudentData' => 'array',
                   13989:     'Maps' => 'array');
                   13990: 
                   13991: Returns: both routines return nothing
                   13992: 
1.631     raeburn  13993: =back
                   13994: 
1.153     matthew  13995: =cut
                   13996: 
                   13997: #######################################################
                   13998: #######################################################
                   13999: sub store_course_settings {
1.496     albertel 14000:     return &store_settings($env{'request.course.id'},@_);
                   14001: }
                   14002: 
                   14003: sub store_settings {
1.153     matthew  14004:     # save to the environment
                   14005:     # appenv the same items, just to be safe
1.300     albertel 14006:     my $udom  = $env{'user.domain'};
                   14007:     my $uname = $env{'user.name'};
1.496     albertel 14008:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14009:     my %SaveHash;
                   14010:     my %AppHash;
                   14011:     while (my ($setting,$type) = each(%$Settings)) {
1.496     albertel 14012:         my $basename = join('.','internal',$context,$prefix,$setting);
1.300     albertel 14013:         my $envname = 'environment.'.$basename;
1.258     albertel 14014:         if (exists($env{'form.'.$setting})) {
1.153     matthew  14015:             # Save this value away
                   14016:             if ($type eq 'scalar' &&
1.258     albertel 14017:                 (! exists($env{$envname}) || 
                   14018:                  $env{$envname} ne $env{'form.'.$setting})) {
                   14019:                 $SaveHash{$basename} = $env{'form.'.$setting};
                   14020:                 $AppHash{$envname}   = $env{'form.'.$setting};
1.153     matthew  14021:             } elsif ($type eq 'array') {
                   14022:                 my $stored_form;
1.258     albertel 14023:                 if (ref($env{'form.'.$setting})) {
1.153     matthew  14024:                     $stored_form = join(',',
                   14025:                                         map {
1.369     www      14026:                                             &escape($_);
1.258     albertel 14027:                                         } sort(@{$env{'form.'.$setting}}));
1.153     matthew  14028:                 } else {
                   14029:                     $stored_form = 
1.369     www      14030:                         &escape($env{'form.'.$setting});
1.153     matthew  14031:                 }
                   14032:                 # Determine if the array contents are the same.
1.258     albertel 14033:                 if ($stored_form ne $env{$envname}) {
1.153     matthew  14034:                     $SaveHash{$basename} = $stored_form;
                   14035:                     $AppHash{$envname}   = $stored_form;
                   14036:                 }
                   14037:             }
                   14038:         }
                   14039:     }
                   14040:     my $put_result = &Apache::lonnet::put('environment',\%SaveHash,
1.300     albertel 14041:                                           $udom,$uname);
1.153     matthew  14042:     if ($put_result !~ /^(ok|delayed)/) {
                   14043:         &Apache::lonnet::logthis('unable to save form parameters, '.
                   14044:                                  'got error:'.$put_result);
                   14045:     }
                   14046:     # Make sure these settings stick around in this session, too
1.646     raeburn  14047:     &Apache::lonnet::appenv(\%AppHash);
1.153     matthew  14048:     return;
                   14049: }
                   14050: 
                   14051: sub restore_course_settings {
1.499     albertel 14052:     return &restore_settings($env{'request.course.id'},@_);
1.496     albertel 14053: }
                   14054: 
                   14055: sub restore_settings {
                   14056:     my ($context,$prefix,$Settings) = @_;
1.153     matthew  14057:     while (my ($setting,$type) = each(%$Settings)) {
1.258     albertel 14058:         next if (exists($env{'form.'.$setting}));
1.496     albertel 14059:         my $envname = 'environment.internal.'.$context.'.'.$prefix.
1.153     matthew  14060:             '.'.$setting;
1.258     albertel 14061:         if (exists($env{$envname})) {
1.153     matthew  14062:             if ($type eq 'scalar') {
1.258     albertel 14063:                 $env{'form.'.$setting} = $env{$envname};
1.153     matthew  14064:             } elsif ($type eq 'array') {
1.258     albertel 14065:                 $env{'form.'.$setting} = [ 
1.153     matthew  14066:                                            map { 
1.369     www      14067:                                                &unescape($_); 
1.258     albertel 14068:                                            } split(',',$env{$envname})
1.153     matthew  14069:                                            ];
                   14070:             }
                   14071:         }
                   14072:     }
1.127     matthew  14073: }
                   14074: 
1.618     raeburn  14075: #######################################################
                   14076: #######################################################
                   14077: 
                   14078: =pod
                   14079: 
                   14080: =head1 Domain E-mail Routines  
                   14081: 
                   14082: =over 4
                   14083: 
1.648     raeburn  14084: =item * &build_recipient_list()
1.618     raeburn  14085: 
1.1075.2.44  raeburn  14086: Build recipient lists for following types of e-mail:
1.766     raeburn  14087: (a) Error Reports, (b) Package Updates, (c) lonstatus warnings/errors
1.1075.2.44  raeburn  14088: (d) Help requests, (e) Course requests needing approval, (f) loncapa
                   14089: module change checking, student/employee ID conflict checks, as
                   14090: generated by lonerrorhandler.pm, CHECKRPMS, loncron,
                   14091: lonsupportreq.pm, loncoursequeueadmin.pm, searchcat.pl respectively.
1.618     raeburn  14092: 
                   14093: Inputs:
1.1075.2.44  raeburn  14094: defmail (scalar - email address of default recipient),
                   14095: mailing type (scalar: errormail, packagesmail, helpdeskmail,
                   14096: requestsmail, updatesmail, or idconflictsmail).
                   14097: 
1.619     raeburn  14098: defdom (domain for which to retrieve configuration settings),
1.1075.2.44  raeburn  14099: 
                   14100: origmail (scalar - email address of recipient from loncapa.conf,
                   14101: i.e., predates configuration by DC via domainprefs.pm
1.618     raeburn  14102: 
1.655     raeburn  14103: Returns: comma separated list of addresses to which to send e-mail.
                   14104: 
                   14105: =back
1.618     raeburn  14106: 
                   14107: =cut
                   14108: 
                   14109: ############################################################
                   14110: ############################################################
                   14111: sub build_recipient_list {
1.619     raeburn  14112:     my ($defmail,$mailing,$defdom,$origmail) = @_;
1.618     raeburn  14113:     my @recipients;
1.1075.2.122  raeburn  14114:     my ($otheremails,$lastresort,$allbcc,$addtext);
1.618     raeburn  14115:     my %domconfig =
1.1075.2.122  raeburn  14116:         &Apache::lonnet::get_dom('configuration',['contacts'],$defdom);
1.618     raeburn  14117:     if (ref($domconfig{'contacts'}) eq 'HASH') {
1.766     raeburn  14118:         if (exists($domconfig{'contacts'}{$mailing})) {
                   14119:             if (ref($domconfig{'contacts'}{$mailing}) eq 'HASH') {
                   14120:                 my @contacts = ('adminemail','supportemail');
                   14121:                 foreach my $item (@contacts) {
                   14122:                     if ($domconfig{'contacts'}{$mailing}{$item}) {
                   14123:                         my $addr = $domconfig{'contacts'}{$item}; 
                   14124:                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14125:                             push(@recipients,$addr);
                   14126:                         }
1.619     raeburn  14127:                     }
1.1075.2.122  raeburn  14128:                 }
                   14129:                 $otheremails = $domconfig{'contacts'}{$mailing}{'others'};
                   14130:                 if ($mailing eq 'helpdeskmail') {
                   14131:                     if ($domconfig{'contacts'}{$mailing}{'bcc'}) {
                   14132:                         my @bccs = split(/,/,$domconfig{'contacts'}{$mailing}{'bcc'});
                   14133:                         my @ok_bccs;
                   14134:                         foreach my $bcc (@bccs) {
                   14135:                             $bcc =~ s/^\s+//g;
                   14136:                             $bcc =~ s/\s+$//g;
                   14137:                             if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14138:                                 if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14139:                                     push(@ok_bccs,$bcc);
                   14140:                                 }
                   14141:                             }
                   14142:                         }
                   14143:                         if (@ok_bccs > 0) {
                   14144:                             $allbcc = join(', ',@ok_bccs);
                   14145:                         }
                   14146:                     }
                   14147:                     $addtext = $domconfig{'contacts'}{$mailing}{'include'};
1.618     raeburn  14148:                 }
                   14149:             }
1.766     raeburn  14150:         } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14151:             $lastresort = $origmail;
1.618     raeburn  14152:         }
1.619     raeburn  14153:     } elsif ($origmail ne '') {
1.1075.2.122  raeburn  14154:         $lastresort = $origmail;
                   14155:     }
                   14156: 
1.1075.2.128  raeburn  14157:     if (($mailing eq 'helpdeskmail') && ($lastresort ne '')) {
1.1075.2.122  raeburn  14158:         unless (grep(/^\Q$defdom\E$/,&Apache::lonnet::current_machine_domains())) {
                   14159:             my $lonhost = $Apache::lonnet::perlvar{'lonHostID'};
                   14160:             my $machinedom = $Apache::lonnet::perlvar{'lonDefDomain'};
                   14161:             my %what = (
                   14162:                           perlvar => 1,
                   14163:                        );
                   14164:             my $primary = &Apache::lonnet::domain($defdom,'primary');
                   14165:             if ($primary) {
                   14166:                 my $gotaddr;
                   14167:                 my ($result,$returnhash) =
                   14168:                     &Apache::lonnet::get_remote_globals($primary,{ perlvar => 1 });
                   14169:                 if (($result eq 'ok') && (ref($returnhash) eq 'HASH')) {
                   14170:                     if ($returnhash->{'lonSupportEMail'} =~ /^[^\@]+\@[^\@]+$/) {
                   14171:                         $lastresort = $returnhash->{'lonSupportEMail'};
                   14172:                         $gotaddr = 1;
                   14173:                     }
                   14174:                 }
                   14175:                 unless ($gotaddr) {
                   14176:                     my $uintdom = &Apache::lonnet::internet_dom($primary);
                   14177:                     my $intdom = &Apache::lonnet::internet_dom($lonhost);
                   14178:                     unless ($uintdom eq $intdom) {
                   14179:                         my %domconfig =
                   14180:                             &Apache::lonnet::get_dom('configuration',['contacts'],$machinedom);
                   14181:                         if (ref($domconfig{'contacts'}) eq 'HASH') {
                   14182:                             if (ref($domconfig{'contacts'}{'otherdomsmail'}) eq 'HASH') {
                   14183:                                 my @contacts = ('adminemail','supportemail');
                   14184:                                 foreach my $item (@contacts) {
                   14185:                                     if ($domconfig{'contacts'}{'otherdomsmail'}{$item}) {
                   14186:                                         my $addr = $domconfig{'contacts'}{$item};
                   14187:                                         if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14188:                                             push(@recipients,$addr);
                   14189:                                         }
                   14190:                                     }
                   14191:                                 }
                   14192:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'others'}) {
                   14193:                                     $otheremails = $domconfig{'contacts'}{'otherdomsmail'}{'others'};
                   14194:                                 }
                   14195:                                 if ($domconfig{'contacts'}{'otherdomsmail'}{'bcc'}) {
                   14196:                                     my @bccs = split(/,/,$domconfig{'contacts'}{'otherdomsmail'}{'bcc'});
                   14197:                                     my @ok_bccs;
                   14198:                                     foreach my $bcc (@bccs) {
                   14199:                                         $bcc =~ s/^\s+//g;
                   14200:                                         $bcc =~ s/\s+$//g;
                   14201:                                         if ($bcc =~ m/^[^\@]+\@[^\@]+$/) {
                   14202:                                             if (!(grep(/^\Q$bcc\E$/,@ok_bccs))) {
                   14203:                                                 push(@ok_bccs,$bcc);
                   14204:                                             }
                   14205:                                         }
                   14206:                                     }
                   14207:                                     if (@ok_bccs > 0) {
                   14208:                                         $allbcc = join(', ',@ok_bccs);
                   14209:                                     }
                   14210:                                 }
                   14211:                                 $addtext = $domconfig{'contacts'}{'otherdomsmail'}{'include'};
                   14212:                             }
                   14213:                         }
                   14214:                     }
                   14215:                 }
                   14216:             }
                   14217:         }
1.618     raeburn  14218:     }
1.688     raeburn  14219:     if (defined($defmail)) {
                   14220:         if ($defmail ne '') {
                   14221:             push(@recipients,$defmail);
                   14222:         }
1.618     raeburn  14223:     }
                   14224:     if ($otheremails) {
1.619     raeburn  14225:         my @others;
                   14226:         if ($otheremails =~ /,/) {
                   14227:             @others = split(/,/,$otheremails);
1.618     raeburn  14228:         } else {
1.619     raeburn  14229:             push(@others,$otheremails);
                   14230:         }
                   14231:         foreach my $addr (@others) {
                   14232:             if (!grep(/^\Q$addr\E$/,@recipients)) {
                   14233:                 push(@recipients,$addr);
                   14234:             }
1.618     raeburn  14235:         }
                   14236:     }
1.1075.2.128  raeburn  14237:     if ($mailing eq 'helpdeskmail') {
1.1075.2.122  raeburn  14238:         if ((!@recipients) && ($lastresort ne '')) {
                   14239:             push(@recipients,$lastresort);
                   14240:         }
                   14241:     } elsif ($lastresort ne '') {
                   14242:         if (!grep(/^\Q$lastresort\E$/,@recipients)) {
                   14243:             push(@recipients,$lastresort);
                   14244:         }
                   14245:     }
                   14246:     my $recipientlist = join(',',@recipients);
                   14247:     if (wantarray) {
                   14248:         return ($recipientlist,$allbcc,$addtext);
                   14249:     } else {
                   14250:         return $recipientlist;
                   14251:     }
1.618     raeburn  14252: }
                   14253: 
1.127     matthew  14254: ############################################################
                   14255: ############################################################
1.154     albertel 14256: 
1.655     raeburn  14257: =pod
                   14258: 
                   14259: =head1 Course Catalog Routines
                   14260: 
                   14261: =over 4
                   14262: 
                   14263: =item * &gather_categories()
                   14264: 
                   14265: Converts category definitions - keys of categories hash stored in  
                   14266: coursecategories in configuration.db on the primary library server in a 
                   14267: domain - to an array.  Also generates javascript and idx hash used to 
                   14268: generate Domain Coordinator interface for editing Course Categories.
                   14269: 
                   14270: Inputs:
1.663     raeburn  14271: 
1.655     raeburn  14272: categories (reference to hash of category definitions).
1.663     raeburn  14273: 
1.655     raeburn  14274: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14275:       categories and subcategories).
1.663     raeburn  14276: 
1.655     raeburn  14277: idx (reference to hash of counters used in Domain Coordinator interface for 
                   14278:       editing Course Categories).
1.663     raeburn  14279: 
1.655     raeburn  14280: jsarray (reference to array of categories used to create Javascript arrays for
                   14281:          Domain Coordinator interface for editing Course Categories).
                   14282: 
                   14283: Returns: nothing
                   14284: 
                   14285: Side effects: populates cats, idx and jsarray. 
                   14286: 
                   14287: =cut
                   14288: 
                   14289: sub gather_categories {
                   14290:     my ($categories,$cats,$idx,$jsarray) = @_;
                   14291:     my %counters;
                   14292:     my $num = 0;
                   14293:     foreach my $item (keys(%{$categories})) {
                   14294:         my ($cat,$container,$depth) = map { &unescape($_); } split(/:/,$item);
                   14295:         if ($container eq '' && $depth == 0) {
                   14296:             $cats->[$depth][$categories->{$item}] = $cat;
                   14297:         } else {
                   14298:             $cats->[$depth]{$container}[$categories->{$item}] = $cat;
                   14299:         }
                   14300:         my ($escitem,$tail) = split(/:/,$item,2);
                   14301:         if ($counters{$tail} eq '') {
                   14302:             $counters{$tail} = $num;
                   14303:             $num ++;
                   14304:         }
                   14305:         if (ref($idx) eq 'HASH') {
                   14306:             $idx->{$item} = $counters{$tail};
                   14307:         }
                   14308:         if (ref($jsarray) eq 'ARRAY') {
                   14309:             push(@{$jsarray->[$counters{$tail}]},$item);
                   14310:         }
                   14311:     }
                   14312:     return;
                   14313: }
                   14314: 
                   14315: =pod
                   14316: 
                   14317: =item * &extract_categories()
                   14318: 
                   14319: Used to generate breadcrumb trails for course categories.
                   14320: 
                   14321: Inputs:
1.663     raeburn  14322: 
1.655     raeburn  14323: categories (reference to hash of category definitions).
1.663     raeburn  14324: 
1.655     raeburn  14325: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14326:       categories and subcategories).
1.663     raeburn  14327: 
1.655     raeburn  14328: trails (reference to array of breacrumb trails for each category).
1.663     raeburn  14329: 
1.655     raeburn  14330: allitems (reference to hash - key is category key 
                   14331:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14332: 
1.655     raeburn  14333: idx (reference to hash of counters used in Domain Coordinator interface for
                   14334:       editing Course Categories).
1.663     raeburn  14335: 
1.655     raeburn  14336: jsarray (reference to array of categories used to create Javascript arrays for
                   14337:          Domain Coordinator interface for editing Course Categories).
                   14338: 
1.665     raeburn  14339: subcats (reference to hash of arrays containing all subcategories within each 
                   14340:          category, -recursive)
                   14341: 
1.1075.2.132  raeburn  14342: maxd (reference to hash used to hold max depth for all top-level categories).
                   14343: 
1.655     raeburn  14344: Returns: nothing
                   14345: 
                   14346: Side effects: populates trails and allitems hash references.
                   14347: 
                   14348: =cut
                   14349: 
                   14350: sub extract_categories {
1.1075.2.132  raeburn  14351:     my ($categories,$cats,$trails,$allitems,$idx,$jsarray,$subcats,$maxd) = @_;
1.655     raeburn  14352:     if (ref($categories) eq 'HASH') {
                   14353:         &gather_categories($categories,$cats,$idx,$jsarray);
                   14354:         if (ref($cats->[0]) eq 'ARRAY') {
                   14355:             for (my $i=0; $i<@{$cats->[0]}; $i++) {
                   14356:                 my $name = $cats->[0][$i];
                   14357:                 my $item = &escape($name).'::0';
                   14358:                 my $trailstr;
                   14359:                 if ($name eq 'instcode') {
                   14360:                     $trailstr = &mt('Official courses (with institutional codes)');
1.919     raeburn  14361:                 } elsif ($name eq 'communities') {
                   14362:                     $trailstr = &mt('Communities');
1.655     raeburn  14363:                 } else {
                   14364:                     $trailstr = $name;
                   14365:                 }
                   14366:                 if ($allitems->{$item} eq '') {
                   14367:                     push(@{$trails},$trailstr);
                   14368:                     $allitems->{$item} = scalar(@{$trails})-1;
                   14369:                 }
                   14370:                 my @parents = ($name);
                   14371:                 if (ref($cats->[1]{$name}) eq 'ARRAY') {
                   14372:                     for (my $j=0; $j<@{$cats->[1]{$name}}; $j++) {
                   14373:                         my $category = $cats->[1]{$name}[$j];
1.665     raeburn  14374:                         if (ref($subcats) eq 'HASH') {
                   14375:                             push(@{$subcats->{$item}},&escape($category).':'.&escape($name).':1');
                   14376:                         }
1.1075.2.132  raeburn  14377:                         &recurse_categories($cats,2,$category,$trails,$allitems,\@parents,$subcats,$maxd);
1.665     raeburn  14378:                     }
                   14379:                 } else {
                   14380:                     if (ref($subcats) eq 'HASH') {
                   14381:                         $subcats->{$item} = [];
1.655     raeburn  14382:                     }
1.1075.2.132  raeburn  14383:                     if (ref($maxd) eq 'HASH') {
                   14384:                         $maxd->{$name} = 1;
                   14385:                     }
1.655     raeburn  14386:                 }
                   14387:             }
                   14388:         }
                   14389:     }
                   14390:     return;
                   14391: }
                   14392: 
                   14393: =pod
                   14394: 
1.1075.2.56  raeburn  14395: =item * &recurse_categories()
1.655     raeburn  14396: 
                   14397: Recursively used to generate breadcrumb trails for course categories.
                   14398: 
                   14399: Inputs:
1.663     raeburn  14400: 
1.655     raeburn  14401: cats (reference to array of arrays/hashes which encapsulates hierarchy of
                   14402:       categories and subcategories).
1.663     raeburn  14403: 
1.655     raeburn  14404: depth (current depth in hierarchy of categories and sub-categories - 0 indexed).
1.663     raeburn  14405: 
                   14406: category (current course category, for which breadcrumb trail is being generated).
                   14407: 
                   14408: trails (reference to array of breadcrumb trails for each category).
                   14409: 
1.655     raeburn  14410: allitems (reference to hash - key is category key
                   14411:          (format: escaped(name):escaped(parent category):depth in hierarchy).
1.663     raeburn  14412: 
1.655     raeburn  14413: parents (array containing containers directories for current category, 
                   14414:          back to top level). 
                   14415: 
                   14416: Returns: nothing
                   14417: 
                   14418: Side effects: populates trails and allitems hash references
                   14419: 
                   14420: =cut
                   14421: 
                   14422: sub recurse_categories {
1.1075.2.132  raeburn  14423:     my ($cats,$depth,$category,$trails,$allitems,$parents,$subcats,$maxd) = @_;
1.655     raeburn  14424:     my $shallower = $depth - 1;
                   14425:     if (ref($cats->[$depth]{$category}) eq 'ARRAY') {
                   14426:         for (my $k=0; $k<@{$cats->[$depth]{$category}}; $k++) {
                   14427:             my $name = $cats->[$depth]{$category}[$k];
                   14428:             my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
                   14429:             my $trailstr = join(' -&gt; ',(@{$parents},$category));
                   14430:             if ($allitems->{$item} eq '') {
                   14431:                 push(@{$trails},$trailstr);
                   14432:                 $allitems->{$item} = scalar(@{$trails})-1;
                   14433:             }
                   14434:             my $deeper = $depth+1;
                   14435:             push(@{$parents},$category);
1.665     raeburn  14436:             if (ref($subcats) eq 'HASH') {
                   14437:                 my $subcat = &escape($name).':'.$category.':'.$depth;
                   14438:                 for (my $j=@{$parents}; $j>=0; $j--) {
                   14439:                     my $higher;
                   14440:                     if ($j > 0) {
                   14441:                         $higher = &escape($parents->[$j]).':'.
                   14442:                                   &escape($parents->[$j-1]).':'.$j;
                   14443:                     } else {
                   14444:                         $higher = &escape($parents->[$j]).'::'.$j;
                   14445:                     }
                   14446:                     push(@{$subcats->{$higher}},$subcat);
                   14447:                 }
                   14448:             }
                   14449:             &recurse_categories($cats,$deeper,$name,$trails,$allitems,$parents,
1.1075.2.132  raeburn  14450:                                 $subcats,$maxd);
1.655     raeburn  14451:             pop(@{$parents});
                   14452:         }
                   14453:     } else {
                   14454:         my $item = &escape($category).':'.&escape($parents->[-1]).':'.$shallower;
1.1075.2.132  raeburn  14455:         my $trailstr = join(' &raquo; ',(@{$parents},$category));
1.655     raeburn  14456:         if ($allitems->{$item} eq '') {
                   14457:             push(@{$trails},$trailstr);
                   14458:             $allitems->{$item} = scalar(@{$trails})-1;
                   14459:         }
1.1075.2.132  raeburn  14460:         if (ref($maxd) eq 'HASH') {
                   14461:             if ($depth > $maxd->{$parents->[0]}) {
                   14462:                 $maxd->{$parents->[0]} = $depth;
                   14463:             }
                   14464:         }
1.655     raeburn  14465:     }
                   14466:     return;
                   14467: }
                   14468: 
1.663     raeburn  14469: =pod
                   14470: 
1.1075.2.56  raeburn  14471: =item * &assign_categories_table()
1.663     raeburn  14472: 
                   14473: Create a datatable for display of hierarchical categories in a domain,
                   14474: with checkboxes to allow a course to be categorized. 
                   14475: 
                   14476: Inputs:
                   14477: 
                   14478: cathash - reference to hash of categories defined for the domain (from
                   14479:           configuration.db)
                   14480: 
                   14481: currcat - scalar with an & separated list of categories assigned to a course. 
                   14482: 
1.919     raeburn  14483: type    - scalar contains course type (Course or Community).
                   14484: 
1.1075.2.117  raeburn  14485: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14486:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14487: 
1.663     raeburn  14488: Returns: $output (markup to be displayed) 
                   14489: 
                   14490: =cut
                   14491: 
                   14492: sub assign_categories_table {
1.1075.2.117  raeburn  14493:     my ($cathash,$currcat,$type,$disabled) = @_;
1.663     raeburn  14494:     my $output;
                   14495:     if (ref($cathash) eq 'HASH') {
1.1075.2.132  raeburn  14496:         my (@cats,@trails,%allitems,%idx,@jsarray,%maxd,@path,$maxdepth);
                   14497:         &extract_categories($cathash,\@cats,\@trails,\%allitems,\%idx,\@jsarray,\%maxd);
1.663     raeburn  14498:         $maxdepth = scalar(@cats);
                   14499:         if (@cats > 0) {
                   14500:             my $itemcount = 0;
                   14501:             if (ref($cats[0]) eq 'ARRAY') {
                   14502:                 my @currcategories;
                   14503:                 if ($currcat ne '') {
                   14504:                     @currcategories = split('&',$currcat);
                   14505:                 }
1.919     raeburn  14506:                 my $table;
1.663     raeburn  14507:                 for (my $i=0; $i<@{$cats[0]}; $i++) {
                   14508:                     my $parent = $cats[0][$i];
1.919     raeburn  14509:                     next if ($parent eq 'instcode');
                   14510:                     if ($type eq 'Community') {
                   14511:                         next unless ($parent eq 'communities');
                   14512:                     } else {
                   14513:                         next if ($parent eq 'communities');
                   14514:                     }
1.663     raeburn  14515:                     my $css_class = $itemcount%2?' class="LC_odd_row"':'';
                   14516:                     my $item = &escape($parent).'::0';
                   14517:                     my $checked = '';
                   14518:                     if (@currcategories > 0) {
                   14519:                         if (grep(/^\Q$item\E$/,@currcategories)) {
1.772     bisitz   14520:                             $checked = ' checked="checked"';
1.663     raeburn  14521:                         }
                   14522:                     }
1.919     raeburn  14523:                     my $parent_title = $parent;
                   14524:                     if ($parent eq 'communities') {
                   14525:                         $parent_title = &mt('Communities');
                   14526:                     }
                   14527:                     $table .= '<tr '.$css_class.'><td><span class="LC_nobreak">'.
                   14528:                               '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14529:                               $item.'"'.$checked.$disabled.' />'.$parent_title.'</span>'.
1.919     raeburn  14530:                               '<input type="hidden" name="catname" value="'.$parent.'" /></td>';
1.663     raeburn  14531:                     my $depth = 1;
                   14532:                     push(@path,$parent);
1.1075.2.117  raeburn  14533:                     $table .= &assign_category_rows($itemcount,\@cats,$depth,$parent,\@path,\@currcategories,$disabled);
1.663     raeburn  14534:                     pop(@path);
1.919     raeburn  14535:                     $table .= '</tr><tr><td colspan="'.$maxdepth.'" class="LC_row_separator"></td></tr>';
1.663     raeburn  14536:                     $itemcount ++;
                   14537:                 }
1.919     raeburn  14538:                 if ($itemcount) {
                   14539:                     $output = &Apache::loncommon::start_data_table().
                   14540:                               $table.
                   14541:                               &Apache::loncommon::end_data_table();
                   14542:                 }
1.663     raeburn  14543:             }
                   14544:         }
                   14545:     }
                   14546:     return $output;
                   14547: }
                   14548: 
                   14549: =pod
                   14550: 
1.1075.2.56  raeburn  14551: =item * &assign_category_rows()
1.663     raeburn  14552: 
                   14553: Create a datatable row for display of nested categories in a domain,
                   14554: with checkboxes to allow a course to be categorized,called recursively.
                   14555: 
                   14556: Inputs:
                   14557: 
                   14558: itemcount - track row number for alternating colors
                   14559: 
                   14560: cats - reference to array of arrays/hashes which encapsulates hierarchy of
                   14561:       categories and subcategories.
                   14562: 
                   14563: depth - current depth in hierarchy of categories and sub-categories - 0 indexed.
                   14564: 
                   14565: parent - parent of current category item
                   14566: 
                   14567: path - Array containing all categories back up through the hierarchy from the
                   14568:        current category to the top level.
                   14569: 
                   14570: currcategories - reference to array of current categories assigned to the course
                   14571: 
1.1075.2.117  raeburn  14572: disabled - scalar (optional) contains disabled="disabled" if input elements are
                   14573:            to be readonly (e.g., Domain Helpdesk role viewing course settings).
                   14574: 
1.663     raeburn  14575: Returns: $output (markup to be displayed).
                   14576: 
                   14577: =cut
                   14578: 
                   14579: sub assign_category_rows {
1.1075.2.117  raeburn  14580:     my ($itemcount,$cats,$depth,$parent,$path,$currcategories,$disabled) = @_;
1.663     raeburn  14581:     my ($text,$name,$item,$chgstr);
                   14582:     if (ref($cats) eq 'ARRAY') {
                   14583:         my $maxdepth = scalar(@{$cats});
                   14584:         if (ref($cats->[$depth]) eq 'HASH') {
                   14585:             if (ref($cats->[$depth]{$parent}) eq 'ARRAY') {
                   14586:                 my $numchildren = @{$cats->[$depth]{$parent}};
                   14587:                 my $css_class = $itemcount%2?' class="LC_odd_row"':'';
1.1075.2.45  raeburn  14588:                 $text .= '<td><table class="LC_data_table">';
1.663     raeburn  14589:                 for (my $j=0; $j<$numchildren; $j++) {
                   14590:                     $name = $cats->[$depth]{$parent}[$j];
                   14591:                     $item = &escape($name).':'.&escape($parent).':'.$depth;
                   14592:                     my $deeper = $depth+1;
                   14593:                     my $checked = '';
                   14594:                     if (ref($currcategories) eq 'ARRAY') {
                   14595:                         if (@{$currcategories} > 0) {
                   14596:                             if (grep(/^\Q$item\E$/,@{$currcategories})) {
1.772     bisitz   14597:                                 $checked = ' checked="checked"';
1.663     raeburn  14598:                             }
                   14599:                         }
                   14600:                     }
1.664     raeburn  14601:                     $text .= '<tr><td><span class="LC_nobreak"><label>'.
                   14602:                              '<input type="checkbox" name="usecategory" value="'.
1.1075.2.117  raeburn  14603:                              $item.'"'.$checked.$disabled.' />'.$name.'</label></span>'.
1.675     raeburn  14604:                              '<input type="hidden" name="catname" value="'.$name.'" />'.
                   14605:                              '</td><td>';
1.663     raeburn  14606:                     if (ref($path) eq 'ARRAY') {
                   14607:                         push(@{$path},$name);
1.1075.2.117  raeburn  14608:                         $text .= &assign_category_rows($itemcount,$cats,$deeper,$name,$path,$currcategories,$disabled);
1.663     raeburn  14609:                         pop(@{$path});
                   14610:                     }
                   14611:                     $text .= '</td></tr>';
                   14612:                 }
                   14613:                 $text .= '</table></td>';
                   14614:             }
                   14615:         }
                   14616:     }
                   14617:     return $text;
                   14618: }
                   14619: 
1.1075.2.69  raeburn  14620: =pod
                   14621: 
                   14622: =back
                   14623: 
                   14624: =cut
                   14625: 
1.655     raeburn  14626: ############################################################
                   14627: ############################################################
                   14628: 
                   14629: 
1.443     albertel 14630: sub commit_customrole {
1.664     raeburn  14631:     my ($udom,$uname,$url,$three,$four,$five,$start,$end,$context) = @_;
1.630     raeburn  14632:     my $output = &mt('Assigning custom role').' "'.$five.'" by '.$four.':'.$three.' in '.$url.
1.443     albertel 14633:                          ($start?', '.&mt('starting').' '.localtime($start):'').
                   14634:                          ($end?', ending '.localtime($end):'').': <b>'.
                   14635:               &Apache::lonnet::assigncustomrole(
1.664     raeburn  14636:                  $udom,$uname,$url,$three,$four,$five,$end,$start,undef,undef,$context).
1.443     albertel 14637:                  '</b><br />';
                   14638:     return $output;
                   14639: }
                   14640: 
                   14641: sub commit_standardrole {
1.1075.2.31  raeburn  14642:     my ($udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,$credits) = @_;
1.541     raeburn  14643:     my ($output,$logmsg,$linefeed);
                   14644:     if ($context eq 'auto') {
                   14645:         $linefeed = "\n";
                   14646:     } else {
                   14647:         $linefeed = "<br />\n";
                   14648:     }  
1.443     albertel 14649:     if ($three eq 'st') {
1.541     raeburn  14650:         my $result = &commit_studentrole(\$logmsg,$udom,$uname,$url,$three,$start,$end,
1.1075.2.31  raeburn  14651:                                          $one,$two,$sec,$context,$credits);
1.541     raeburn  14652:         if (($result =~ /^error/) || ($result eq 'not_in_class') || 
1.626     raeburn  14653:             ($result eq 'unknown_course') || ($result eq 'refused')) {
                   14654:             $output = $logmsg.' '.&mt('Error: ').$result."\n"; 
1.443     albertel 14655:         } else {
1.541     raeburn  14656:             $output = $logmsg.$linefeed.&mt('Assigning').' '.$three.' in '.$url.
1.443     albertel 14657:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14658:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
                   14659:             if ($context eq 'auto') {
                   14660:                 $output .= $result.$linefeed.&mt('Add to classlist').': ok';
                   14661:             } else {
                   14662:                $output .= '<b>'.$result.'</b>'.$linefeed.
                   14663:                &mt('Add to classlist').': <b>ok</b>';
                   14664:             }
                   14665:             $output .= $linefeed;
1.443     albertel 14666:         }
                   14667:     } else {
                   14668:         $output = &mt('Assigning').' '.$three.' in '.$url.
                   14669:                ($start?', '.&mt('starting').' '.localtime($start):'').
1.541     raeburn  14670:                ($end?', '.&mt('ending').' '.localtime($end):'').': ';
1.652     raeburn  14671:         my $result = &Apache::lonnet::assignrole($udom,$uname,$url,$three,$end,$start,'','',$context);
1.541     raeburn  14672:         if ($context eq 'auto') {
                   14673:             $output .= $result.$linefeed;
                   14674:         } else {
                   14675:             $output .= '<b>'.$result.'</b>'.$linefeed;
                   14676:         }
1.443     albertel 14677:     }
                   14678:     return $output;
                   14679: }
                   14680: 
                   14681: sub commit_studentrole {
1.1075.2.31  raeburn  14682:     my ($logmsg,$udom,$uname,$url,$three,$start,$end,$one,$two,$sec,$context,
                   14683:         $credits) = @_;
1.626     raeburn  14684:     my ($result,$linefeed,$oldsecurl,$newsecurl);
1.541     raeburn  14685:     if ($context eq 'auto') {
                   14686:         $linefeed = "\n";
                   14687:     } else {
                   14688:         $linefeed = '<br />'."\n";
                   14689:     }
1.443     albertel 14690:     if (defined($one) && defined($two)) {
                   14691:         my $cid=$one.'_'.$two;
                   14692:         my $oldsec=&Apache::lonnet::getsection($udom,$uname,$cid);
                   14693:         my $secchange = 0;
                   14694:         my $expire_role_result;
                   14695:         my $modify_section_result;
1.628     raeburn  14696:         if ($oldsec ne '-1') { 
                   14697:             if ($oldsec ne $sec) {
1.443     albertel 14698:                 $secchange = 1;
1.628     raeburn  14699:                 my $now = time;
1.443     albertel 14700:                 my $uurl='/'.$cid;
                   14701:                 $uurl=~s/\_/\//g;
                   14702:                 if ($oldsec) {
                   14703:                     $uurl.='/'.$oldsec;
                   14704:                 }
1.626     raeburn  14705:                 $oldsecurl = $uurl;
1.628     raeburn  14706:                 $expire_role_result = 
1.652     raeburn  14707:                     &Apache::lonnet::assignrole($udom,$uname,$uurl,'st',$now,'','',$context);
1.628     raeburn  14708:                 if ($env{'request.course.sec'} ne '') { 
                   14709:                     if ($expire_role_result eq 'refused') {
                   14710:                         my @roles = ('st');
                   14711:                         my @statuses = ('previous');
                   14712:                         my @roledoms = ($one);
                   14713:                         my $withsec = 1;
                   14714:                         my %roleshash = 
                   14715:                             &Apache::lonnet::get_my_roles($uname,$udom,'userroles',
                   14716:                                               \@statuses,\@roles,\@roledoms,$withsec);
                   14717:                         if (defined ($roleshash{$two.':'.$one.':st:'.$oldsec})) {
                   14718:                             my ($oldstart,$oldend) = 
                   14719:                                 split(':',$roleshash{$two.':'.$one.':st:'.$oldsec});
                   14720:                             if ($oldend > 0 && $oldend <= $now) {
                   14721:                                 $expire_role_result = 'ok';
                   14722:                             }
                   14723:                         }
                   14724:                     }
                   14725:                 }
1.443     albertel 14726:                 $result = $expire_role_result;
                   14727:             }
                   14728:         }
                   14729:         if (($expire_role_result eq 'ok') || ($secchange == 0)) {
1.1075.2.31  raeburn  14730:             $modify_section_result = 
                   14731:                 &Apache::lonnet::modify_student_enrollment($udom,$uname,undef,undef,
                   14732:                                                            undef,undef,undef,$sec,
                   14733:                                                            $end,$start,'','',$cid,
                   14734:                                                            '',$context,$credits);
1.443     albertel 14735:             if ($modify_section_result =~ /^ok/) {
                   14736:                 if ($secchange == 1) {
1.628     raeburn  14737:                     if ($sec eq '') {
                   14738:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to student role without a section.',$uname,$oldsec).$linefeed;
                   14739:                     } else {
                   14740:                         $$logmsg .= &mt('Section for [_1] switched from (possibly expired) old section: [_2] to new section: [_3].',$uname,$oldsec,$sec).$linefeed;
                   14741:                     }
1.443     albertel 14742:                 } elsif ($oldsec eq '-1') {
1.628     raeburn  14743:                     if ($sec eq '') {
                   14744:                         $$logmsg .= &mt('New student role without a section for [_1] in course [_2].',$uname,$cid).$linefeed;
                   14745:                     } else {
                   14746:                         $$logmsg .= &mt('New student role for [_1] in section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14747:                     }
1.443     albertel 14748:                 } else {
1.628     raeburn  14749:                     if ($sec eq '') {
                   14750:                         $$logmsg .= &mt('Student [_1] assigned to course [_2] without a section.',$uname,$cid).$linefeed;
                   14751:                     } else {
                   14752:                         $$logmsg .= &mt('Student [_1] assigned to section [_2] in course [_3].',$uname,$sec,$cid).$linefeed;
                   14753:                     }
1.443     albertel 14754:                 }
                   14755:             } else {
1.628     raeburn  14756:                 if ($secchange) {       
                   14757:                     $$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;
                   14758:                 } else {
                   14759:                     $$logmsg .= &mt('Error when attempting to modify role for [_1] for section: "[_2]" in course [_3] -error:',$uname,$sec,$cid).' '.$modify_section_result.$linefeed;
                   14760:                 }
1.443     albertel 14761:             }
                   14762:             $result = $modify_section_result;
                   14763:         } elsif ($secchange == 1) {
1.628     raeburn  14764:             if ($oldsec eq '') {
1.1075.2.20  raeburn  14765:                 $$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  14766:             } else {
                   14767:                 $$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;
                   14768:             }
1.626     raeburn  14769:             if ($expire_role_result eq 'refused') {
                   14770:                 my $newsecurl = '/'.$cid;
                   14771:                 $newsecurl =~ s/\_/\//g;
                   14772:                 if ($sec ne '') {
                   14773:                     $newsecurl.='/'.$sec;
                   14774:                 }
                   14775:                 if (&Apache::lonnet::allowed('cst',$newsecurl) && !(&Apache::lonnet::allowed('cst',$oldsecurl))) {
                   14776:                     if ($sec eq '') {
                   14777:                         $$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;
                   14778:                     } else {
                   14779:                         $$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;
                   14780:                     }
                   14781:                 }
                   14782:             }
1.443     albertel 14783:         }
                   14784:     } else {
1.626     raeburn  14785:         $$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 14786:         $result = "error: incomplete course id\n";
                   14787:     }
                   14788:     return $result;
                   14789: }
                   14790: 
1.1075.2.25  raeburn  14791: sub show_role_extent {
                   14792:     my ($scope,$context,$role) = @_;
                   14793:     $scope =~ s{^/}{};
                   14794:     my @courseroles = &Apache::lonuserutils::roles_by_context('course',1);
                   14795:     push(@courseroles,'co');
                   14796:     my @authorroles = &Apache::lonuserutils::roles_by_context('author');
                   14797:     if (($context eq 'course') || (grep(/^\Q$role\E/,@courseroles))) {
                   14798:         $scope =~ s{/}{_};
                   14799:         return '<span class="LC_cusr_emph">'.$env{'course.'.$scope.'.description'}.'</span>';
                   14800:     } elsif (($context eq 'author') || (grep(/^\Q$role\E/,@authorroles))) {
                   14801:         my ($audom,$auname) = split(/\//,$scope);
                   14802:         return &mt('[_1] Author Space','<span class="LC_cusr_emph">'.
                   14803:                    &Apache::loncommon::plainname($auname,$audom).'</span>');
                   14804:     } else {
                   14805:         $scope =~ s{/$}{};
                   14806:         return &mt('Domain: [_1]','<span class="LC_cusr_emph">'.
                   14807:                    &Apache::lonnet::domain($scope,'description').'</span>');
                   14808:     }
                   14809: }
                   14810: 
1.443     albertel 14811: ############################################################
                   14812: ############################################################
                   14813: 
1.566     albertel 14814: sub check_clone {
1.578     raeburn  14815:     my ($args,$linefeed) = @_;
1.566     albertel 14816:     my $cloneid='/'.$args->{'clonedomain'}.'/'.$args->{'clonecourse'};
                   14817:     my ($clonecrsudom,$clonecrsunum)= &LONCAPA::split_courseid($cloneid);
                   14818:     my $clonehome=&Apache::lonnet::homeserver($clonecrsunum,$clonecrsudom);
                   14819:     my $clonemsg;
                   14820:     my $can_clone = 0;
1.944     raeburn  14821:     my $lctype = lc($args->{'crstype'});
1.908     raeburn  14822:     if ($lctype ne 'community') {
                   14823:         $lctype = 'course';
                   14824:     }
1.566     albertel 14825:     if ($clonehome eq 'no_host') {
1.944     raeburn  14826:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14827:             $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'});
                   14828:         } else {
                   14829:             $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'});
                   14830:         }     
1.566     albertel 14831:     } else {
                   14832: 	my %clonedesc = &Apache::lonnet::coursedescription($cloneid,{'one_time' => 1});
1.944     raeburn  14833:         if ($args->{'crstype'} eq 'Community') {
1.908     raeburn  14834:             if ($clonedesc{'type'} ne 'Community') {
                   14835:                  $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'});
                   14836:                 return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14837:             }
                   14838:         }
1.1075.2.119  raeburn  14839: 	if (($env{'request.role.domain'} eq $args->{'clonedomain'}) &&
1.882     raeburn  14840:             (&Apache::lonnet::allowed('ccc',$env{'request.role.domain'}))) {
1.566     albertel 14841: 	    $can_clone = 1;
                   14842: 	} else {
1.1075.2.95  raeburn  14843: 	    my %clonehash = &Apache::lonnet::get('environment',['cloners','internal.coursecode'],
1.566     albertel 14844: 						 $args->{'clonedomain'},$args->{'clonecourse'});
1.1075.2.95  raeburn  14845:             if ($clonehash{'cloners'} eq '') {
                   14846:                 my %domdefs = &Apache::lonnet::get_domain_defaults($args->{'course_domain'});
                   14847:                 if ($domdefs{'canclone'}) {
                   14848:                     unless ($domdefs{'canclone'} eq 'none') {
                   14849:                         if ($domdefs{'canclone'} eq 'domain') {
                   14850:                             if ($args->{'ccdomain'} eq $args->{'clonedomain'}) {
                   14851:                                 $can_clone = 1;
                   14852:                             }
                   14853:                         } elsif (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14854:                                  ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
                   14855:                             if (&Apache::lonnet::default_instcode_cloning($args->{'clonedomain'},$domdefs{'canclone'},
                   14856:                                                                           $clonehash{'internal.coursecode'},$args->{'crscode'})) {
                   14857:                                 $can_clone = 1;
                   14858:                             }
                   14859:                         }
                   14860:                     }
1.908     raeburn  14861:                 }
1.1075.2.95  raeburn  14862:             } else {
                   14863: 	        my @cloners = split(/,/,$clonehash{'cloners'});
                   14864:                 if (grep(/^\*$/,@cloners)) {
1.942     raeburn  14865:                     $can_clone = 1;
1.1075.2.95  raeburn  14866:                 } elsif (grep(/^\*\:\Q$args->{'ccdomain'}\E$/,@cloners)) {
1.942     raeburn  14867:                     $can_clone = 1;
1.1075.2.96  raeburn  14868:                 } elsif (grep(/^\Q$args->{'ccuname'}\E:\Q$args->{'ccdomain'}\E$/,@cloners)) {
                   14869:                     $can_clone = 1;
1.1075.2.95  raeburn  14870:                 }
                   14871:                 unless ($can_clone) {
1.1075.2.96  raeburn  14872:                     if (($clonehash{'internal.coursecode'}) && ($args->{'crscode'}) &&
                   14873:                         ($args->{'clonedomain'} eq  $args->{'course_domain'})) {
1.1075.2.95  raeburn  14874:                         my (%gotdomdefaults,%gotcodedefaults);
                   14875:                         foreach my $cloner (@cloners) {
                   14876:                             if (($cloner ne '*') && ($cloner !~ /^\*\:$match_domain$/) &&
                   14877:                                 ($cloner !~ /^$match_username\:$match_domain$/) && ($cloner ne '')) {
                   14878:                                 my (%codedefaults,@code_order);
                   14879:                                 if (ref($gotcodedefaults{$args->{'clonedomain'}}) eq 'HASH') {
                   14880:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'defaults'}) eq 'HASH') {
                   14881:                                         %codedefaults = %{$gotcodedefaults{$args->{'clonedomain'}}{'defaults'}};
                   14882:                                     }
                   14883:                                     if (ref($gotcodedefaults{$args->{'clonedomain'}}{'order'}) eq 'ARRAY') {
                   14884:                                         @code_order = @{$gotcodedefaults{$args->{'clonedomain'}}{'order'}};
                   14885:                                     }
                   14886:                                 } else {
                   14887:                                     &Apache::lonnet::auto_instcode_defaults($args->{'clonedomain'},
                   14888:                                                                             \%codedefaults,
                   14889:                                                                             \@code_order);
                   14890:                                     $gotcodedefaults{$args->{'clonedomain'}}{'defaults'} = \%codedefaults;
                   14891:                                     $gotcodedefaults{$args->{'clonedomain'}}{'order'} = \@code_order;
                   14892:                                 }
                   14893:                                 if (@code_order > 0) {
                   14894:                                     if (&Apache::lonnet::check_instcode_cloning(\%codedefaults,\@code_order,
                   14895:                                                                                 $cloner,$clonehash{'internal.coursecode'},
                   14896:                                                                                 $args->{'crscode'})) {
                   14897:                                         $can_clone = 1;
                   14898:                                         last;
                   14899:                                     }
                   14900:                                 }
                   14901:                             }
                   14902:                         }
                   14903:                     }
1.1075.2.96  raeburn  14904:                 }
                   14905:             }
                   14906:             unless ($can_clone) {
                   14907:                 my $ccrole = 'cc';
                   14908:                 if ($args->{'crstype'} eq 'Community') {
                   14909:                     $ccrole = 'co';
                   14910:                 }
                   14911:                 my %roleshash =
                   14912:                     &Apache::lonnet::get_my_roles($args->{'ccuname'},
                   14913:                                                   $args->{'ccdomain'},
                   14914:                                                   'userroles',['active'],[$ccrole],
                   14915:                                                   [$args->{'clonedomain'}]);
                   14916:                 if ($roleshash{$args->{'clonecourse'}.':'.$args->{'clonedomain'}.':'.$ccrole}) {
                   14917:                     $can_clone = 1;
                   14918:                 } elsif (&Apache::lonnet::is_course_owner($args->{'clonedomain'},$args->{'clonecourse'},
                   14919:                                                           $args->{'ccuname'},$args->{'ccdomain'})) {
                   14920:                     $can_clone = 1;
1.1075.2.95  raeburn  14921:                 }
                   14922:             }
                   14923:             unless ($can_clone) {
                   14924:                 if ($args->{'crstype'} eq 'Community') {
                   14925:                     $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'});
                   14926:                 } else {
                   14927:                     $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  14928: 	        }
1.566     albertel 14929: 	    }
1.578     raeburn  14930:         }
1.566     albertel 14931:     }
                   14932:     return ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14933: }
                   14934: 
1.444     albertel 14935: sub construct_course {
1.1075.2.119  raeburn  14936:     my ($args,$logmsg,$courseid,$crsudom,$crsunum,$udom,$uname,$context,
                   14937:         $cnum,$category,$coderef) = @_;
1.444     albertel 14938:     my $outcome;
1.541     raeburn  14939:     my $linefeed =  '<br />'."\n";
                   14940:     if ($context eq 'auto') {
                   14941:         $linefeed = "\n";
                   14942:     }
1.566     albertel 14943: 
                   14944: #
                   14945: # Are we cloning?
                   14946: #
                   14947:     my ($can_clone, $clonemsg, $cloneid, $clonehome);
                   14948:     if (($args->{'clonecourse'}) && ($args->{'clonedomain'})) {
1.578     raeburn  14949: 	($can_clone, $clonemsg, $cloneid, $clonehome) = &check_clone($args,$linefeed);
1.566     albertel 14950: 	if ($context ne 'auto') {
1.578     raeburn  14951:             if ($clonemsg ne '') {
                   14952: 	        $clonemsg = '<span class="LC_error">'.$clonemsg.'</span>';
                   14953:             }
1.566     albertel 14954: 	}
                   14955: 	$outcome .= $clonemsg.$linefeed;
                   14956: 
                   14957:         if (!$can_clone) {
                   14958: 	    return (0,$outcome);
                   14959: 	}
                   14960:     }
                   14961: 
1.444     albertel 14962: #
                   14963: # Open course
                   14964: #
                   14965:     my $crstype = lc($args->{'crstype'});
                   14966:     my %cenv=();
                   14967:     $$courseid=&Apache::lonnet::createcourse($args->{'course_domain'},
                   14968:                                              $args->{'cdescr'},
                   14969:                                              $args->{'curl'},
                   14970:                                              $args->{'course_home'},
                   14971:                                              $args->{'nonstandard'},
                   14972:                                              $args->{'crscode'},
                   14973:                                              $args->{'ccuname'}.':'.
                   14974:                                              $args->{'ccdomain'},
1.882     raeburn  14975:                                              $args->{'crstype'},
1.885     raeburn  14976:                                              $cnum,$context,$category);
1.444     albertel 14977: 
                   14978:     # Note: The testing routines depend on this being output; see 
                   14979:     # Utils::Course. This needs to at least be output as a comment
                   14980:     # if anyone ever decides to not show this, and Utils::Course::new
                   14981:     # will need to be suitably modified.
1.541     raeburn  14982:     $outcome .= &mt('New LON-CAPA [_1] ID: [_2]',$crstype,$$courseid).$linefeed;
1.943     raeburn  14983:     if ($$courseid =~ /^error:/) {
                   14984:         return (0,$outcome);
                   14985:     }
                   14986: 
1.444     albertel 14987: #
                   14988: # Check if created correctly
                   14989: #
1.479     albertel 14990:     ($$crsudom,$$crsunum)= &LONCAPA::split_courseid($$courseid);
1.444     albertel 14991:     my $crsuhome=&Apache::lonnet::homeserver($$crsunum,$$crsudom);
1.943     raeburn  14992:     if ($crsuhome eq 'no_host') {
                   14993:         $outcome .= &mt('Course creation failed, unrecognized course home server.').$linefeed;
                   14994:         return (0,$outcome);
                   14995:     }
1.541     raeburn  14996:     $outcome .= &mt('Created on').': '.$crsuhome.$linefeed;
1.566     albertel 14997: 
1.444     albertel 14998: #
1.566     albertel 14999: # Do the cloning
                   15000: #   
                   15001:     if ($can_clone && $cloneid) {
                   15002: 	$clonemsg = &mt('Cloning [_1] from [_2]',$crstype,$clonehome);
                   15003: 	if ($context ne 'auto') {
                   15004: 	    $clonemsg = '<span class="LC_success">'.$clonemsg.'</span>';
                   15005: 	}
                   15006: 	$outcome .= $clonemsg.$linefeed;
                   15007: 	my %oldcenv=&Apache::lonnet::dump('environment',$$crsudom,$$crsunum);
1.444     albertel 15008: # Copy all files
1.637     www      15009: 	&Apache::lonclonecourse::copycoursefiles($cloneid,$$courseid,$args->{'datemode'},$args->{'dateshift'});
1.444     albertel 15010: # Restore URL
1.566     albertel 15011: 	$cenv{'url'}=$oldcenv{'url'};
1.444     albertel 15012: # Restore title
1.566     albertel 15013: 	$cenv{'description'}=$oldcenv{'description'};
1.955     raeburn  15014: # Restore creation date, creator and creation context.
                   15015:         $cenv{'internal.created'}=$oldcenv{'internal.created'};
                   15016:         $cenv{'internal.creator'}=$oldcenv{'internal.creator'};
                   15017:         $cenv{'internal.creationcontext'}=$oldcenv{'internal.creationcontext'};
1.444     albertel 15018: # Mark as cloned
1.566     albertel 15019: 	$cenv{'clonedfrom'}=$cloneid;
1.638     www      15020: # Need to clone grading mode
                   15021:         my %newenv=&Apache::lonnet::get('environment',['grading'],$$crsudom,$$crsunum);
                   15022:         $cenv{'grading'}=$newenv{'grading'};
                   15023: # Do not clone these environment entries
                   15024:         &Apache::lonnet::del('environment',
                   15025:                   ['default_enrollment_start_date',
                   15026:                    'default_enrollment_end_date',
                   15027:                    'question.email',
                   15028:                    'policy.email',
                   15029:                    'comment.email',
                   15030:                    'pch.users.denied',
1.725     raeburn  15031:                    'plc.users.denied',
                   15032:                    'hidefromcat',
1.1075.2.36  raeburn  15033:                    'checkforpriv',
1.1075.2.59  raeburn  15034:                    'categories',
                   15035:                    'internal.uniquecode'],
1.638     www      15036:                    $$crsudom,$$crsunum);
1.1075.2.63  raeburn  15037:         if ($args->{'textbook'}) {
                   15038:             $cenv{'internal.textbook'} = $args->{'textbook'};
                   15039:         }
1.444     albertel 15040:     }
1.566     albertel 15041: 
1.444     albertel 15042: #
                   15043: # Set environment (will override cloned, if existing)
                   15044: #
                   15045:     my @sections = ();
                   15046:     my @xlists = ();
                   15047:     if ($args->{'crstype'}) {
                   15048:         $cenv{'type'}=$args->{'crstype'};
                   15049:     }
                   15050:     if ($args->{'crsid'}) {
                   15051:         $cenv{'courseid'}=$args->{'crsid'};
                   15052:     }
                   15053:     if ($args->{'crscode'}) {
                   15054:         $cenv{'internal.coursecode'}=$args->{'crscode'};
                   15055:     }
                   15056:     if ($args->{'crsquota'} ne '') {
                   15057:         $cenv{'internal.coursequota'}=$args->{'crsquota'};
                   15058:     } else {
                   15059:         $cenv{'internal.coursequota'}=$args->{'crsquota'} = 20;
                   15060:     }
                   15061:     if ($args->{'ccuname'}) {
                   15062:         $cenv{'internal.courseowner'} = $args->{'ccuname'}.
                   15063:                                         ':'.$args->{'ccdomain'};
                   15064:     } else {
                   15065:         $cenv{'internal.courseowner'} = $args->{'curruser'};
                   15066:     }
1.1075.2.31  raeburn  15067:     if ($args->{'defaultcredits'}) {
                   15068:         $cenv{'internal.defaultcredits'} = $args->{'defaultcredits'};
                   15069:     }
1.444     albertel 15070:     my @badclasses = (); # Used to accumulate sections/crosslistings that did not pass classlist access check for course owner.
                   15071:     if ($args->{'crssections'}) {
                   15072:         $cenv{'internal.sectionnums'} = '';
                   15073:         if ($args->{'crssections'} =~ m/,/) {
                   15074:             @sections = split/,/,$args->{'crssections'};
                   15075:         } else {
                   15076:             $sections[0] = $args->{'crssections'};
                   15077:         }
                   15078:         if (@sections > 0) {
                   15079:             foreach my $item (@sections) {
                   15080:                 my ($sec,$gp) = split/:/,$item;
                   15081:                 my $class = $args->{'crscode'}.$sec;
                   15082:                 my $addcheck = &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$class,$cenv{'internal.courseowner'});
                   15083:                 $cenv{'internal.sectionnums'} .= $item.',';
                   15084:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15085:                     push(@badclasses,$class);
1.444     albertel 15086:                 }
                   15087:             }
                   15088:             $cenv{'internal.sectionnums'} =~ s/,$//;
                   15089:         }
                   15090:     }
                   15091: # do not hide course coordinator from staff listing, 
                   15092: # even if privileged
                   15093:     $cenv{'nothideprivileged'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
1.1075.2.36  raeburn  15094: # add course coordinator's domain to domains to check for privileged users
                   15095: # if different to course domain
                   15096:     if ($$crsudom ne $args->{'ccdomain'}) {
                   15097:         $cenv{'checkforpriv'} = $args->{'ccdomain'};
                   15098:     }
1.444     albertel 15099: # add crosslistings
                   15100:     if ($args->{'crsxlist'}) {
                   15101:         $cenv{'internal.crosslistings'}='';
                   15102:         if ($args->{'crsxlist'} =~ m/,/) {
                   15103:             @xlists = split/,/,$args->{'crsxlist'};
                   15104:         } else {
                   15105:             $xlists[0] = $args->{'crsxlist'};
                   15106:         }
                   15107:         if (@xlists > 0) {
                   15108:             foreach my $item (@xlists) {
                   15109:                 my ($xl,$gp) = split/:/,$item;
                   15110:                 my $addcheck =  &Apache::lonnet::auto_new_course($$crsunum,$$crsudom,$xl,$cenv{'internal.courseowner'});
                   15111:                 $cenv{'internal.crosslistings'} .= $item.',';
                   15112:                 unless ($addcheck eq 'ok') {
1.1075.2.119  raeburn  15113:                     push(@badclasses,$xl);
1.444     albertel 15114:                 }
                   15115:             }
                   15116:             $cenv{'internal.crosslistings'} =~ s/,$//;
                   15117:         }
                   15118:     }
                   15119:     if ($args->{'autoadds'}) {
                   15120:         $cenv{'internal.autoadds'}=$args->{'autoadds'};
                   15121:     }
                   15122:     if ($args->{'autodrops'}) {
                   15123:         $cenv{'internal.autodrops'}=$args->{'autodrops'};
                   15124:     }
                   15125: # check for notification of enrollment changes
                   15126:     my @notified = ();
                   15127:     if ($args->{'notify_owner'}) {
                   15128:         if ($args->{'ccuname'} ne '') {
                   15129:             push(@notified,$args->{'ccuname'}.':'.$args->{'ccdomain'});
                   15130:         }
                   15131:     }
                   15132:     if ($args->{'notify_dc'}) {
                   15133:         if ($uname ne '') { 
1.630     raeburn  15134:             push(@notified,$uname.':'.$udom);
1.444     albertel 15135:         }
                   15136:     }
                   15137:     if (@notified > 0) {
                   15138:         my $notifylist;
                   15139:         if (@notified > 1) {
                   15140:             $notifylist = join(',',@notified);
                   15141:         } else {
                   15142:             $notifylist = $notified[0];
                   15143:         }
                   15144:         $cenv{'internal.notifylist'} = $notifylist;
                   15145:     }
                   15146:     if (@badclasses > 0) {
                   15147:         my %lt=&Apache::lonlocal::texthash(
1.1075.2.119  raeburn  15148:                 'tclb' => 'The courses listed below were included as sections or crosslistings affiliated with your new LON-CAPA course.',
                   15149:                 'howi' => 'However, if automated course roster updates are enabled for this class, these particular sections/crosslistings are not guaranteed to contribute towards enrollment.',
                   15150:                 'itis' => 'It is possible that rights to access enrollment for these classes will be available through assignment of co-owners.',
1.444     albertel 15151:         );
1.1075.2.119  raeburn  15152:         my $badclass_msg = $lt{'tclb'}.$linefeed.$lt{'howi'}.$linefeed.
                   15153:                            &mt('That is because the user identified as the course owner ([_1]) does not have rights to access enrollment in these classes, as determined by the policies of your institution on access to official classlists',$cenv{'internal.courseowner'}).$linefeed.$lt{'itis'};
1.541     raeburn  15154:         if ($context eq 'auto') {
                   15155:             $outcome .= $badclass_msg.$linefeed;
1.1075.2.119  raeburn  15156:         } else {
1.566     albertel 15157:             $outcome .= '<div class="LC_warning">'.$badclass_msg.$linefeed.'<ul>'."\n";
1.1075.2.119  raeburn  15158:         }
                   15159:         foreach my $item (@badclasses) {
1.541     raeburn  15160:             if ($context eq 'auto') {
1.1075.2.119  raeburn  15161:                 $outcome .= " - $item\n";
1.541     raeburn  15162:             } else {
1.1075.2.119  raeburn  15163:                 $outcome .= "<li>$item</li>\n";
1.541     raeburn  15164:             }
1.1075.2.119  raeburn  15165:         }
                   15166:         if ($context eq 'auto') {
                   15167:             $outcome .= $linefeed;
                   15168:         } else {
                   15169:             $outcome .= "</ul><br /><br /></div>\n";
                   15170:         }
1.444     albertel 15171:     }
                   15172:     if ($args->{'no_end_date'}) {
                   15173:         $args->{'endaccess'} = 0;
                   15174:     }
                   15175:     $cenv{'internal.autostart'}=$args->{'enrollstart'};
                   15176:     $cenv{'internal.autoend'}=$args->{'enrollend'};
                   15177:     $cenv{'default_enrollment_start_date'}=$args->{'startaccess'};
                   15178:     $cenv{'default_enrollment_end_date'}=$args->{'endaccess'};
                   15179:     if ($args->{'showphotos'}) {
                   15180:       $cenv{'internal.showphotos'}=$args->{'showphotos'};
                   15181:     }
                   15182:     $cenv{'internal.authtype'} = $args->{'authtype'};
                   15183:     $cenv{'internal.autharg'} = $args->{'autharg'}; 
                   15184:     if ( ($cenv{'internal.authtype'} =~ /^krb/) && ($cenv{'internal.autoadds'} == 1)) {
                   15185:         if (! defined($cenv{'internal.autharg'}) || $cenv{'internal.autharg'}  eq '') {
1.541     raeburn  15186:             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'); 
                   15187:             if ($context eq 'auto') {
                   15188:                 $outcome .= $krb_msg;
                   15189:             } else {
1.566     albertel 15190:                 $outcome .= '<span class="LC_error">'.$krb_msg.'</span>';
1.541     raeburn  15191:             }
                   15192:             $outcome .= $linefeed;
1.444     albertel 15193:         }
                   15194:     }
                   15195:     if (($args->{'ccdomain'}) && ($args->{'ccuname'})) {
                   15196:        if ($args->{'setpolicy'}) {
                   15197:            $cenv{'policy.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15198:        }
                   15199:        if ($args->{'setcontent'}) {
                   15200:            $cenv{'question.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15201:        }
1.1075.2.110  raeburn  15202:        if ($args->{'setcomment'}) {
                   15203:            $cenv{'comment.email'}=$args->{'ccuname'}.':'.$args->{'ccdomain'};
                   15204:        }
1.444     albertel 15205:     }
                   15206:     if ($args->{'reshome'}) {
                   15207: 	$cenv{'reshome'}=$args->{'reshome'}.'/';
                   15208: 	$cenv{'reshome'}=~s/\/+$/\//;
                   15209:     }
                   15210: #
                   15211: # course has keyed access
                   15212: #
                   15213:     if ($args->{'setkeys'}) {
                   15214:        $cenv{'keyaccess'}='yes';
                   15215:     }
                   15216: # if specified, key authority is not course, but user
                   15217: # only active if keyaccess is yes
                   15218:     if ($args->{'keyauth'}) {
1.487     albertel 15219: 	my ($user,$domain) = split(':',$args->{'keyauth'});
                   15220: 	$user = &LONCAPA::clean_username($user);
                   15221: 	$domain = &LONCAPA::clean_username($domain);
1.488     foxr     15222: 	if ($user ne '' && $domain ne '') {
1.487     albertel 15223: 	    $cenv{'keyauth'}=$user.':'.$domain;
1.444     albertel 15224: 	}
                   15225:     }
                   15226: 
1.1075.2.59  raeburn  15227: #
                   15228: #  generate and store uniquecode (available to course requester), if course should have one.
                   15229: #
                   15230:     if ($args->{'uniquecode'}) {
                   15231:         my ($code,$error) = &make_unique_code($$crsudom,$$crsunum);
                   15232:         if ($code) {
                   15233:             $cenv{'internal.uniquecode'} = $code;
                   15234:             my %crsinfo =
                   15235:                 &Apache::lonnet::courseiddump($$crsudom,'.',1,'.','.',$$crsunum,undef,undef,'.');
                   15236:             if (ref($crsinfo{$$crsudom.'_'.$$crsunum}) eq 'HASH') {
                   15237:                 $crsinfo{$$crsudom.'_'.$$crsunum}{'uniquecode'} = $code;
                   15238:                 my $putres = &Apache::lonnet::courseidput($$crsudom,\%crsinfo,$crsuhome,'notime');
                   15239:             }
                   15240:             if (ref($coderef)) {
                   15241:                 $$coderef = $code;
                   15242:             }
                   15243:         }
                   15244:     }
                   15245: 
1.444     albertel 15246:     if ($args->{'disresdis'}) {
                   15247:         $cenv{'pch.roles.denied'}='st';
                   15248:     }
                   15249:     if ($args->{'disablechat'}) {
                   15250:         $cenv{'plc.roles.denied'}='st';
                   15251:     }
                   15252: 
                   15253:     # Record we've not yet viewed the Course Initialization Helper for this 
                   15254:     # course
                   15255:     $cenv{'course.helper.not.run'} = 1;
                   15256:     #
                   15257:     # Use new Randomseed
                   15258:     #
                   15259:     $cenv{'rndseed'}=&Apache::lonnet::latest_rnd_algorithm_id();;
                   15260:     $cenv{'receiptalg'}=&Apache::lonnet::latest_receipt_algorithm_id();;
                   15261:     #
                   15262:     # The encryption code and receipt prefix for this course
                   15263:     #
                   15264:     $cenv{'internal.encseed'}=$Apache::lonnet::perlvar{'lonReceipt'}.$$.time.int(rand(9999));
                   15265:     $cenv{'internal.encpref'}=100+int(9*rand(99));
                   15266:     #
                   15267:     # By default, use standard grading
                   15268:     if (!defined($cenv{'grading'})) { $cenv{'grading'} = 'standard'; }
                   15269: 
1.541     raeburn  15270:     $outcome .= $linefeed.&mt('Setting environment').': '.                 
                   15271:           &Apache::lonnet::put('environment',\%cenv,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15272: #
                   15273: # Open all assignments
                   15274: #
                   15275:     if ($args->{'openall'}) {
                   15276:        my $storeunder=$$crsudom.'_'.$$crsunum.'.0.opendate';
                   15277:        my %storecontent = ($storeunder         => time,
                   15278:                            $storeunder.'.type' => 'date_start');
                   15279:        
                   15280:        $outcome .= &mt('Opening all assignments').': '.&Apache::lonnet::cput
1.541     raeburn  15281:                  ('resourcedata',\%storecontent,$$crsudom,$$crsunum).$linefeed;
1.444     albertel 15282:    }
                   15283: #
                   15284: # Set first page
                   15285: #
                   15286:     unless (($args->{'nonstandard'}) || ($args->{'firstres'} eq 'blank')
                   15287: 	    || ($cloneid)) {
1.445     albertel 15288: 	use LONCAPA::map;
1.444     albertel 15289: 	$outcome .= &mt('Setting first resource').': ';
1.445     albertel 15290: 
                   15291: 	my $map = '/uploaded/'.$$crsudom.'/'.$$crsunum.'/default.sequence';
                   15292:         my ($errtext,$fatal)=&LONCAPA::map::mapread($map);
                   15293: 
1.444     albertel 15294:         $outcome .= ($fatal?$errtext:'read ok').' - ';
                   15295:         my $title; my $url;
                   15296:         if ($args->{'firstres'} eq 'syl') {
1.690     bisitz   15297: 	    $title=&mt('Syllabus');
1.444     albertel 15298:             $url='/public/'.$$crsudom.'/'.$$crsunum.'/syllabus';
                   15299:         } else {
1.963     raeburn  15300:             $title=&mt('Table of Contents');
1.444     albertel 15301:             $url='/adm/navmaps';
                   15302:         }
1.445     albertel 15303: 
                   15304:         $LONCAPA::map::resources[1]=$title.':'.$url.':false:start:res';
                   15305: 	(my $outtext,$errtext) = &LONCAPA::map::storemap($map,1);
                   15306: 
                   15307: 	if ($errtext) { $fatal=2; }
1.541     raeburn  15308:         $outcome .= ($fatal?$errtext:'write ok').$linefeed;
1.444     albertel 15309:     }
1.566     albertel 15310: 
                   15311:     return (1,$outcome);
1.444     albertel 15312: }
                   15313: 
1.1075.2.59  raeburn  15314: sub make_unique_code {
                   15315:     my ($cdom,$cnum) = @_;
                   15316:     # get lock on uniquecodes db
                   15317:     my $lockhash = {
                   15318:                       $cnum."\0".'uniquecodes' => $env{'user.name'}.
                   15319:                                                   ':'.$env{'user.domain'},
                   15320:                    };
                   15321:     my $tries = 0;
                   15322:     my $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15323:     my ($code,$error);
                   15324: 
                   15325:     while (($gotlock ne 'ok') && ($tries<3)) {
                   15326:         $tries ++;
                   15327:         sleep 1;
                   15328:         $gotlock = &Apache::lonnet::newput_dom('uniquecodes',$lockhash,$cdom);
                   15329:     }
                   15330:     if ($gotlock eq 'ok') {
                   15331:         my %currcodes = &Apache::lonnet::dump_dom('uniquecodes',$cdom);
                   15332:         my $gotcode;
                   15333:         my $attempts = 0;
                   15334:         while ((!$gotcode) && ($attempts < 100)) {
                   15335:             $code = &generate_code();
                   15336:             if (!exists($currcodes{$code})) {
                   15337:                 $gotcode = 1;
                   15338:                 unless (&Apache::lonnet::newput_dom('uniquecodes',{ $code => $cnum },$cdom) eq 'ok') {
                   15339:                     $error = 'nostore';
                   15340:                 }
                   15341:             }
                   15342:             $attempts ++;
                   15343:         }
                   15344:         my @del_lock = ($cnum."\0".'uniquecodes');
                   15345:         my $dellockoutcome = &Apache::lonnet::del_dom('uniquecodes',\@del_lock,$cdom);
                   15346:     } else {
                   15347:         $error = 'nolock';
                   15348:     }
                   15349:     return ($code,$error);
                   15350: }
                   15351: 
                   15352: sub generate_code {
                   15353:     my $code;
                   15354:     my @letts = qw(B C D G H J K M N P Q R S T V W X Z);
                   15355:     for (my $i=0; $i<6; $i++) {
                   15356:         my $lettnum = int (rand 2);
                   15357:         my $item = '';
                   15358:         if ($lettnum) {
                   15359:             $item = $letts[int( rand(18) )];
                   15360:         } else {
                   15361:             $item = 1+int( rand(8) );
                   15362:         }
                   15363:         $code .= $item;
                   15364:     }
                   15365:     return $code;
                   15366: }
                   15367: 
1.444     albertel 15368: ############################################################
                   15369: ############################################################
                   15370: 
1.953     droeschl 15371: #SD
                   15372: # only Community and Course, or anything else?
1.378     raeburn  15373: sub course_type {
                   15374:     my ($cid) = @_;
                   15375:     if (!defined($cid)) {
                   15376:         $cid = $env{'request.course.id'};
                   15377:     }
1.404     albertel 15378:     if (defined($env{'course.'.$cid.'.type'})) {
                   15379:         return $env{'course.'.$cid.'.type'};
1.378     raeburn  15380:     } else {
                   15381:         return 'Course';
1.377     raeburn  15382:     }
                   15383: }
1.156     albertel 15384: 
1.406     raeburn  15385: sub group_term {
                   15386:     my $crstype = &course_type();
                   15387:     my %names = (
                   15388:                   'Course' => 'group',
1.865     raeburn  15389:                   'Community' => 'group',
1.406     raeburn  15390:                 );
                   15391:     return $names{$crstype};
                   15392: }
                   15393: 
1.902     raeburn  15394: sub course_types {
1.1075.2.59  raeburn  15395:     my @types = ('official','unofficial','community','textbook');
1.902     raeburn  15396:     my %typename = (
                   15397:                          official   => 'Official course',
                   15398:                          unofficial => 'Unofficial course',
                   15399:                          community  => 'Community',
1.1075.2.59  raeburn  15400:                          textbook   => 'Textbook course',
1.902     raeburn  15401:                    );
                   15402:     return (\@types,\%typename);
                   15403: }
                   15404: 
1.156     albertel 15405: sub icon {
                   15406:     my ($file)=@_;
1.505     albertel 15407:     my $curfext = lc((split(/\./,$file))[-1]);
1.168     albertel 15408:     my $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/unknown.gif';
1.156     albertel 15409:     my $embstyle = &Apache::loncommon::fileembstyle($curfext);
1.168     albertel 15410:     if (!(!defined($embstyle) || $embstyle eq 'unk' || $embstyle eq 'hdn')) {
                   15411: 	if (-e  $Apache::lonnet::perlvar{'lonDocRoot'}.'/'.
                   15412: 	          $Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15413: 	            $curfext.".gif") {
                   15414: 	    $iconname=$Apache::lonnet::perlvar{'lonIconsURL'}.'/'.
                   15415: 		$curfext.".gif";
                   15416: 	}
                   15417:     }
1.249     albertel 15418:     return &lonhttpdurl($iconname);
1.154     albertel 15419: } 
1.84      albertel 15420: 
1.575     albertel 15421: sub lonhttpdurl {
1.692     www      15422: #
                   15423: # Had been used for "small fry" static images on separate port 8080.
                   15424: # Modify here if lightweight http functionality desired again.
                   15425: # Currently eliminated due to increasing firewall issues.
                   15426: #
1.575     albertel 15427:     my ($url)=@_;
1.692     www      15428:     return $url;
1.215     albertel 15429: }
                   15430: 
1.213     albertel 15431: sub connection_aborted {
                   15432:     my ($r)=@_;
                   15433:     $r->print(" ");$r->rflush();
                   15434:     my $c = $r->connection;
                   15435:     return $c->aborted();
                   15436: }
                   15437: 
1.221     foxr     15438: #    Escapes strings that may have embedded 's that will be put into
1.222     foxr     15439: #    strings as 'strings'.
                   15440: sub escape_single {
1.221     foxr     15441:     my ($input) = @_;
1.223     albertel 15442:     $input =~ s/\\/\\\\/g;	# Escape the \'s..(must be first)>
1.221     foxr     15443:     $input =~ s/\'/\\\'/g;	# Esacpe the 's....
                   15444:     return $input;
                   15445: }
1.223     albertel 15446: 
1.222     foxr     15447: #  Same as escape_single, but escape's "'s  This 
                   15448: #  can be used for  "strings"
                   15449: sub escape_double {
                   15450:     my ($input) = @_;
                   15451:     $input =~ s/\\/\\\\/g;	# Escape the /'s..(must be first)>
                   15452:     $input =~ s/\"/\\\"/g;	# Esacpe the "s....
                   15453:     return $input;
                   15454: }
1.223     albertel 15455:  
1.222     foxr     15456: #   Escapes the last element of a full URL.
                   15457: sub escape_url {
                   15458:     my ($url)   = @_;
1.238     raeburn  15459:     my @urlslices = split(/\//, $url,-1);
1.369     www      15460:     my $lastitem = &escape(pop(@urlslices));
1.1075.2.83  raeburn  15461:     return &HTML::Entities::encode(join('/',@urlslices),"'").'/'.$lastitem;
1.222     foxr     15462: }
1.462     albertel 15463: 
1.820     raeburn  15464: sub compare_arrays {
                   15465:     my ($arrayref1,$arrayref2) = @_;
                   15466:     my (@difference,%count);
                   15467:     @difference = ();
                   15468:     %count = ();
                   15469:     if ((ref($arrayref1) eq 'ARRAY') && (ref($arrayref2) eq 'ARRAY')) {
                   15470:         foreach my $element (@{$arrayref1}, @{$arrayref2}) { $count{$element}++; }
                   15471:         foreach my $element (keys(%count)) {
                   15472:             if ($count{$element} == 1) {
                   15473:                 push(@difference,$element);
                   15474:             }
                   15475:         }
                   15476:     }
                   15477:     return @difference;
                   15478: }
                   15479: 
1.817     bisitz   15480: # -------------------------------------------------------- Initialize user login
1.462     albertel 15481: sub init_user_environment {
1.463     albertel 15482:     my ($r, $username, $domain, $authhost, $form, $args) = @_;
1.462     albertel 15483:     my $lonids=$Apache::lonnet::perlvar{'lonIDsDir'};
                   15484: 
                   15485:     my $public=($username eq 'public' && $domain eq 'public');
                   15486: 
                   15487: # See if old ID present, if so, remove
                   15488: 
1.1062    raeburn  15489:     my ($filename,$cookie,$userroles,$firstaccenv,$timerintenv);
1.462     albertel 15490:     my $now=time;
                   15491: 
                   15492:     if ($public) {
                   15493: 	my $max_public=100;
                   15494: 	my $oldest;
                   15495: 	my $oldest_time=0;
                   15496: 	for(my $next=1;$next<=$max_public;$next++) {
                   15497: 	    if (-e $lonids."/publicuser_$next.id") {
                   15498: 		my $mtime=(stat($lonids."/publicuser_$next.id"))[9];
                   15499: 		if ($mtime<$oldest_time || !$oldest_time) {
                   15500: 		    $oldest_time=$mtime;
                   15501: 		    $oldest=$next;
                   15502: 		}
                   15503: 	    } else {
                   15504: 		$cookie="publicuser_$next";
                   15505: 		last;
                   15506: 	    }
                   15507: 	}
                   15508: 	if (!$cookie) { $cookie="publicuser_$oldest"; }
                   15509:     } else {
1.463     albertel 15510: 	# if this isn't a robot, kill any existing non-robot sessions
                   15511: 	if (!$args->{'robot'}) {
                   15512: 	    opendir(DIR,$lonids);
                   15513: 	    while ($filename=readdir(DIR)) {
                   15514: 		if ($filename=~/^$username\_\d+\_$domain\_$authhost\.id$/) {
                   15515: 		    unlink($lonids.'/'.$filename);
                   15516: 		}
1.462     albertel 15517: 	    }
1.463     albertel 15518: 	    closedir(DIR);
1.1075.2.84  raeburn  15519: # If there is a undeleted lockfile for the user's paste buffer remove it.
                   15520:             my $namespace = 'nohist_courseeditor';
                   15521:             my $lockingkey = 'paste'."\0".'locked_num';
                   15522:             my %lockhash = &Apache::lonnet::get($namespace,[$lockingkey],
                   15523:                                                 $domain,$username);
                   15524:             if (exists($lockhash{$lockingkey})) {
                   15525:                 my $delresult = &Apache::lonnet::del($namespace,[$lockingkey],$domain,$username);
                   15526:                 unless ($delresult eq 'ok') {
                   15527:                     &Apache::lonnet::logthis("Failed to delete paste buffer locking key in $namespace for ".$username.":".$domain." Result was: $delresult");
                   15528:                 }
                   15529:             }
1.462     albertel 15530: 	}
                   15531: # Give them a new cookie
1.463     albertel 15532: 	my $id = ($args->{'robot'} ? 'robot'.$args->{'robot'}
1.684     www      15533: 		                   : $now.$$.int(rand(10000)));
1.463     albertel 15534: 	$cookie="$username\_$id\_$domain\_$authhost";
1.462     albertel 15535:     
                   15536: # Initialize roles
                   15537: 
1.1062    raeburn  15538: 	($userroles,$firstaccenv,$timerintenv) = 
                   15539:             &Apache::lonnet::rolesinit($domain,$username,$authhost);
1.462     albertel 15540:     }
                   15541: # ------------------------------------ Check browser type and MathML capability
                   15542: 
1.1075.2.77  raeburn  15543:     my ($httpbrowser,$clientbrowser,$clientversion,$clientmathml,$clientunicode,
                   15544:         $clientos,$clientmobile,$clientinfo,$clientosversion) = &decode_user_agent($r);
1.462     albertel 15545: 
                   15546: # ------------------------------------------------------------- Get environment
                   15547: 
                   15548:     my %userenv = &Apache::lonnet::dump('environment',$domain,$username);
                   15549:     my ($tmp) = keys(%userenv);
                   15550:     if ($tmp !~ /^(con_lost|error|no_such_host)/i) {
                   15551:     } else {
                   15552: 	undef(%userenv);
                   15553:     }
                   15554:     if (($userenv{'interface'}) && (!$form->{'interface'})) {
                   15555: 	$form->{'interface'}=$userenv{'interface'};
                   15556:     }
                   15557:     if ($userenv{'texengine'} eq 'ttm') { $clientmathml=1; }
                   15558: 
                   15559: # --------------- Do not trust query string to be put directly into environment
1.817     bisitz   15560:     foreach my $option ('interface','localpath','localres') {
                   15561:         $form->{$option}=~s/[\n\r\=]//gs;
1.462     albertel 15562:     }
                   15563: # --------------------------------------------------------- Write first profile
                   15564: 
                   15565:     {
                   15566: 	my %initial_env = 
                   15567: 	    ("user.name"          => $username,
                   15568: 	     "user.domain"        => $domain,
                   15569: 	     "user.home"          => $authhost,
                   15570: 	     "browser.type"       => $clientbrowser,
                   15571: 	     "browser.version"    => $clientversion,
                   15572: 	     "browser.mathml"     => $clientmathml,
                   15573: 	     "browser.unicode"    => $clientunicode,
                   15574: 	     "browser.os"         => $clientos,
1.1075.2.42  raeburn  15575:              "browser.mobile"     => $clientmobile,
                   15576:              "browser.info"       => $clientinfo,
1.1075.2.77  raeburn  15577:              "browser.osversion"  => $clientosversion,
1.462     albertel 15578: 	     "server.domain"      => $Apache::lonnet::perlvar{'lonDefDomain'},
                   15579: 	     "request.course.fn"  => '',
                   15580: 	     "request.course.uri" => '',
                   15581: 	     "request.course.sec" => '',
                   15582: 	     "request.role"       => 'cm',
                   15583: 	     "request.role.adv"   => $env{'user.adv'},
                   15584: 	     "request.host"       => $ENV{'REMOTE_ADDR'},);
                   15585: 
                   15586:         if ($form->{'localpath'}) {
                   15587: 	    $initial_env{"browser.localpath"}  = $form->{'localpath'};
                   15588: 	    $initial_env{"browser.localres"}   = $form->{'localres'};
                   15589:         }
                   15590: 	
                   15591: 	if ($form->{'interface'}) {
                   15592: 	    $form->{'interface'}=~s/\W//gs;
                   15593: 	    $initial_env{"browser.interface"} = $form->{'interface'};
                   15594: 	    $env{'browser.interface'}=$form->{'interface'};
                   15595: 	}
                   15596: 
1.1075.2.54  raeburn  15597:         if ($form->{'iptoken'}) {
                   15598:             my $lonhost = $r->dir_config('lonHostID');
                   15599:             $initial_env{"user.noloadbalance"} = $lonhost;
                   15600:             $env{'user.noloadbalance'} = $lonhost;
                   15601:         }
                   15602: 
1.1075.2.120  raeburn  15603:         if ($form->{'noloadbalance'}) {
                   15604:             my @hosts = &Apache::lonnet::current_machine_ids();
                   15605:             my $hosthere = $form->{'noloadbalance'};
                   15606:             if (grep(/^\Q$hosthere\E$/,@hosts)) {
                   15607:                 $initial_env{"user.noloadbalance"} = $hosthere;
                   15608:                 $env{'user.noloadbalance'} = $hosthere;
                   15609:             }
                   15610:         }
                   15611: 
1.1016    raeburn  15612:         unless ($domain eq 'public') {
1.1075.2.125  raeburn  15613:             my %is_adv = ( is_adv => $env{'user.adv'} );
                   15614:             my %domdef = &Apache::lonnet::get_domain_defaults($domain);
1.980     raeburn  15615: 
1.1075.2.125  raeburn  15616:             foreach my $tool ('aboutme','blog','webdav','portfolio') {
                   15617:                 $userenv{'availabletools.'.$tool} = 
                   15618:                     &Apache::lonnet::usertools_access($username,$domain,$tool,'reload',
                   15619:                                                       undef,\%userenv,\%domdef,\%is_adv);
                   15620:             }
1.724     raeburn  15621: 
1.1075.2.125  raeburn  15622:             foreach my $crstype ('official','unofficial','community','textbook') {
                   15623:                 $userenv{'canrequest.'.$crstype} =
                   15624:                     &Apache::lonnet::usertools_access($username,$domain,$crstype,
                   15625:                                                       'reload','requestcourses',
                   15626:                                                       \%userenv,\%domdef,\%is_adv);
                   15627:             }
1.765     raeburn  15628: 
1.1075.2.125  raeburn  15629:             $userenv{'canrequest.author'} =
                   15630:                 &Apache::lonnet::usertools_access($username,$domain,'requestauthor',
                   15631:                                                   'reload','requestauthor',
                   15632:                                                   \%userenv,\%domdef,\%is_adv);
                   15633:             my %reqauthor = &Apache::lonnet::get('requestauthor',['author_status','author'],
                   15634:                                                  $domain,$username);
                   15635:             my $reqstatus = $reqauthor{'author_status'};
                   15636:             if ($reqstatus eq 'approval' || $reqstatus eq 'approved') {
                   15637:                 if (ref($reqauthor{'author'}) eq 'HASH') {
                   15638:                     $userenv{'requestauthorqueued'} = $reqstatus.':'.
                   15639:                                                       $reqauthor{'author'}{'timestamp'};
                   15640:                 }
1.1075.2.14  raeburn  15641:             }
                   15642:         }
                   15643: 
1.462     albertel 15644: 	$env{'user.environment'} = "$lonids/$cookie.id";
1.1062    raeburn  15645: 
1.462     albertel 15646: 	if (tie(my %disk_env,'GDBM_File',"$lonids/$cookie.id",
                   15647: 		 &GDBM_WRCREAT(),0640)) {
                   15648: 	    &_add_to_env(\%disk_env,\%initial_env);
                   15649: 	    &_add_to_env(\%disk_env,\%userenv,'environment.');
                   15650: 	    &_add_to_env(\%disk_env,$userroles);
1.1062    raeburn  15651:             if (ref($firstaccenv) eq 'HASH') {
                   15652:                 &_add_to_env(\%disk_env,$firstaccenv);
                   15653:             }
                   15654:             if (ref($timerintenv) eq 'HASH') {
                   15655:                 &_add_to_env(\%disk_env,$timerintenv);
                   15656:             }
1.463     albertel 15657: 	    if (ref($args->{'extra_env'})) {
                   15658: 		&_add_to_env(\%disk_env,$args->{'extra_env'});
                   15659: 	    }
1.462     albertel 15660: 	    untie(%disk_env);
                   15661: 	} else {
1.705     tempelho 15662: 	    &Apache::lonnet::logthis("<span style=\"color:blue;\">WARNING: ".
                   15663: 			   'Could not create environment storage in lonauth: '.$!.'</span>');
1.462     albertel 15664: 	    return 'error: '.$!;
                   15665: 	}
                   15666:     }
                   15667:     $env{'request.role'}='cm';
                   15668:     $env{'request.role.adv'}=$env{'user.adv'};
                   15669:     $env{'browser.type'}=$clientbrowser;
                   15670: 
                   15671:     return $cookie;
                   15672: 
                   15673: }
                   15674: 
                   15675: sub _add_to_env {
                   15676:     my ($idf,$env_data,$prefix) = @_;
1.676     raeburn  15677:     if (ref($env_data) eq 'HASH') {
                   15678:         while (my ($key,$value) = each(%$env_data)) {
                   15679: 	    $idf->{$prefix.$key} = $value;
                   15680: 	    $env{$prefix.$key}   = $value;
                   15681:         }
1.462     albertel 15682:     }
                   15683: }
                   15684: 
1.685     tempelho 15685: # --- Get the symbolic name of a problem and the url
                   15686: sub get_symb {
                   15687:     my ($request,$silent) = @_;
1.726     raeburn  15688:     (my $url=$env{'form.url'}) =~ s-^https?\://($ENV{'SERVER_NAME'}|$ENV{'HTTP_HOST'})--;
1.685     tempelho 15689:     my $symb=($env{'form.symb'} ne '' ? $env{'form.symb'} : (&Apache::lonnet::symbread($url)));
                   15690:     if ($symb eq '') {
                   15691:         if (!$silent) {
1.1071    raeburn  15692:             if (ref($request)) { 
                   15693:                 $request->print("Unable to handle ambiguous references:$url:.");
                   15694:             }
1.685     tempelho 15695:             return ();
                   15696:         }
                   15697:     }
                   15698:     &Apache::lonenc::check_decrypt(\$symb);
                   15699:     return ($symb);
                   15700: }
                   15701: 
                   15702: # --------------------------------------------------------------Get annotation
                   15703: 
                   15704: sub get_annotation {
                   15705:     my ($symb,$enc) = @_;
                   15706: 
                   15707:     my $key = $symb;
                   15708:     if (!$enc) {
                   15709:         $key =
                   15710:             &Apache::lonnet::clutter((&Apache::lonnet::decode_symb($symb))[2]);
                   15711:     }
                   15712:     my %annotation=&Apache::lonnet::get('nohist_annotations',[$key]);
                   15713:     return $annotation{$key};
                   15714: }
                   15715: 
                   15716: sub clean_symb {
1.731     raeburn  15717:     my ($symb,$delete_enc) = @_;
1.685     tempelho 15718: 
                   15719:     &Apache::lonenc::check_decrypt(\$symb);
                   15720:     my $enc = $env{'request.enc'};
1.731     raeburn  15721:     if ($delete_enc) {
1.730     raeburn  15722:         delete($env{'request.enc'});
                   15723:     }
1.685     tempelho 15724: 
                   15725:     return ($symb,$enc);
                   15726: }
1.462     albertel 15727: 
1.1075.2.69  raeburn  15728: ############################################################
                   15729: ############################################################
                   15730: 
                   15731: =pod
                   15732: 
                   15733: =head1 Routines for building display used to search for courses
                   15734: 
                   15735: 
                   15736: =over 4
                   15737: 
                   15738: =item * &build_filters()
                   15739: 
                   15740: Create markup for a table used to set filters to use when selecting
                   15741: courses in a domain.  Used by lonpickcourse.pm, lonmodifycourse.pm
                   15742: and quotacheck.pl
                   15743: 
                   15744: 
                   15745: Inputs:
                   15746: 
                   15747: filterlist - anonymous array of fields to include as potential filters
                   15748: 
                   15749: crstype - course type
                   15750: 
                   15751: roleelement - fifth arg in selectcourse_link() populates fifth arg in javascript: opencrsbrowser() function, used
                   15752:               to pop-open a course selector (will contain "extra element").
                   15753: 
                   15754: multelement - if multiple course selections will be allowed, this will be a hidden form element: name: multiple; value: 1
                   15755: 
                   15756: filter - anonymous hash of criteria and their values
                   15757: 
                   15758: action - form action
                   15759: 
                   15760: numfiltersref - ref to scalar (count of number of elements in institutional codes -- e.g., 4 for year, semester, department, and number)
                   15761: 
                   15762: caller - caller context (e.g., set to 'modifycourse' when routine is called from lonmodifycourse.pm)
                   15763: 
                   15764: cloneruname - username of owner of new course who wants to clone
                   15765: 
                   15766: clonerudom - domain of owner of new course who wants to clone
                   15767: 
                   15768: typeelem - text to use for left column in row containing course type (i.e., Course, Community or Course/Community)
                   15769: 
                   15770: codetitlesref - reference to array of titles of components in institutional codes (official courses)
                   15771: 
                   15772: codedom - domain
                   15773: 
                   15774: formname - value of form element named "form".
                   15775: 
                   15776: fixeddom - domain, if fixed.
                   15777: 
                   15778: prevphase - value to assign to form element named "phase" when going back to the previous screen
                   15779: 
                   15780: cnameelement - name of form element in form on opener page which will receive title of selected course
                   15781: 
                   15782: cnumelement - name of form element in form on opener page which will receive courseID  of selected course
                   15783: 
                   15784: cdomelement - name of form element in form on opener page which will receive domain of selected course
                   15785: 
                   15786: setroles - includes access constraint identifier when setting a roles-based condition for acces to a portfolio file
                   15787: 
                   15788: clonetext - hidden form elements containing list of courses cloneable by intended course owner when DC creates a course
                   15789: 
                   15790: clonewarning - warning message about missing information for intended course owner when DC creates a course
                   15791: 
                   15792: 
                   15793: Returns: $output - HTML for display of search criteria, and hidden form elements.
                   15794: 
                   15795: 
                   15796: Side Effects: None
                   15797: 
                   15798: =cut
                   15799: 
                   15800: # ---------------------------------------------- search for courses based on last activity etc.
                   15801: 
                   15802: sub build_filters {
                   15803:     my ($filterlist,$crstype,$roleelement,$multelement,$filter,$action,
                   15804:         $numtitlesref,$caller,$cloneruname,$clonerudom,$typeelement,
                   15805:         $codetitlesref,$codedom,$formname,$fixeddom,$prevphase,
                   15806:         $cnameelement,$cnumelement,$cdomelement,$setroles,
                   15807:         $clonetext,$clonewarning) = @_;
                   15808:     my ($list,$jscript);
                   15809:     my $onchange = 'javascript:updateFilters(this)';
                   15810:     my ($domainselectform,$sincefilterform,$createdfilterform,
                   15811:         $ownerdomselectform,$persondomselectform,$instcodeform,
                   15812:         $typeselectform,$instcodetitle);
                   15813:     if ($formname eq '') {
                   15814:         $formname = $caller;
                   15815:     }
                   15816:     foreach my $item (@{$filterlist}) {
                   15817:         unless (($item eq 'descriptfilter') || ($item eq 'instcodefilter') ||
                   15818:                 ($item eq 'sincefilter') || ($item eq 'createdfilter')) {
                   15819:             if ($item eq 'domainfilter') {
                   15820:                 $filter->{$item} = &LONCAPA::clean_domain($filter->{$item});
                   15821:             } elsif ($item eq 'coursefilter') {
                   15822:                 $filter->{$item} = &LONCAPA::clean_courseid($filter->{$item});
                   15823:             } elsif ($item eq 'ownerfilter') {
                   15824:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15825:             } elsif ($item eq 'ownerdomfilter') {
                   15826:                 $filter->{'ownerdomfilter'} =
                   15827:                     &LONCAPA::clean_domain($filter->{$item});
                   15828:                 $ownerdomselectform = &select_dom_form($filter->{'ownerdomfilter'},
                   15829:                                                        'ownerdomfilter',1);
                   15830:             } elsif ($item eq 'personfilter') {
                   15831:                 $filter->{$item} = &LONCAPA::clean_username($filter->{$item});
                   15832:             } elsif ($item eq 'persondomfilter') {
                   15833:                 $persondomselectform = &select_dom_form($filter->{'persondomfilter'},
                   15834:                                                         'persondomfilter',1);
                   15835:             } else {
                   15836:                 $filter->{$item} =~ s/\W//g;
                   15837:             }
                   15838:             if (!$filter->{$item}) {
                   15839:                 $filter->{$item} = '';
                   15840:             }
                   15841:         }
                   15842:         if ($item eq 'domainfilter') {
                   15843:             my $allow_blank = 1;
                   15844:             if ($formname eq 'portform') {
                   15845:                 $allow_blank=0;
                   15846:             } elsif ($formname eq 'studentform') {
                   15847:                 $allow_blank=0;
                   15848:             }
                   15849:             if ($fixeddom) {
                   15850:                 $domainselectform = '<input type="hidden" name="domainfilter"'.
                   15851:                                     ' value="'.$codedom.'" />'.
                   15852:                                     &Apache::lonnet::domain($codedom,'description');
                   15853:             } else {
                   15854:                 $domainselectform = &select_dom_form($filter->{$item},
                   15855:                                                      'domainfilter',
                   15856:                                                       $allow_blank,'',$onchange);
                   15857:             }
                   15858:         } else {
                   15859:             $list->{$item} = &HTML::Entities::encode($filter->{$item},'<>&"');
                   15860:         }
                   15861:     }
                   15862: 
                   15863:     # last course activity filter and selection
                   15864:     $sincefilterform = &timebased_select_form('sincefilter',$filter);
                   15865: 
                   15866:     # course created filter and selection
                   15867:     if (exists($filter->{'createdfilter'})) {
                   15868:         $createdfilterform = &timebased_select_form('createdfilter',$filter);
                   15869:     }
                   15870: 
                   15871:     my %lt = &Apache::lonlocal::texthash(
                   15872:                 'cac' => "$crstype Activity",
                   15873:                 'ccr' => "$crstype Created",
                   15874:                 'cde' => "$crstype Title",
                   15875:                 'cdo' => "$crstype Domain",
                   15876:                 'ins' => 'Institutional Code',
                   15877:                 'inc' => 'Institutional Categorization',
                   15878:                 'cow' => "$crstype Owner/Co-owner",
                   15879:                 'cop' => "$crstype Personnel Includes",
                   15880:                 'cog' => 'Type',
                   15881:              );
                   15882: 
                   15883:     if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   15884:         my $typeval = 'Course';
                   15885:         if ($crstype eq 'Community') {
                   15886:             $typeval = 'Community';
                   15887:         }
                   15888:         $typeselectform = '<input type="hidden" name="type" value="'.$typeval.'" />';
                   15889:     } else {
                   15890:         $typeselectform =  '<select name="type" size="1"';
                   15891:         if ($onchange) {
                   15892:             $typeselectform .= ' onchange="'.$onchange.'"';
                   15893:         }
                   15894:         $typeselectform .= '>'."\n";
                   15895:         foreach my $posstype ('Course','Community') {
                   15896:             $typeselectform.='<option value="'.$posstype.'"'.
                   15897:                 ($posstype eq $crstype ? ' selected="selected" ' : ''). ">".&mt($posstype)."</option>\n";
                   15898:         }
                   15899:         $typeselectform.="</select>";
                   15900:     }
                   15901: 
                   15902:     my ($cloneableonlyform,$cloneabletitle);
                   15903:     if (exists($filter->{'cloneableonly'})) {
                   15904:         my $cloneableon = '';
                   15905:         my $cloneableoff = ' checked="checked"';
                   15906:         if ($filter->{'cloneableonly'}) {
                   15907:             $cloneableon = $cloneableoff;
                   15908:             $cloneableoff = '';
                   15909:         }
                   15910:         $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>';
                   15911:         if ($formname eq 'ccrs') {
1.1075.2.71  raeburn  15912:             $cloneabletitle = &mt('Cloneable for [_1]',$cloneruname.':'.$clonerudom);
1.1075.2.69  raeburn  15913:         } else {
                   15914:             $cloneabletitle = &mt('Cloneable by you');
                   15915:         }
                   15916:     }
                   15917:     my $officialjs;
                   15918:     if ($crstype eq 'Course') {
                   15919:         if (exists($filter->{'instcodefilter'})) {
                   15920: #            if (($fixeddom) || ($formname eq 'requestcrs') ||
                   15921: #                ($formname eq 'modifycourse') || ($formname eq 'filterpicker')) {
                   15922:             if ($codedom) {
                   15923:                 $officialjs = 1;
                   15924:                 ($instcodeform,$jscript,$$numtitlesref) =
                   15925:                     &Apache::courseclassifier::instcode_selectors($codedom,'filterpicker',
                   15926:                                                                   $officialjs,$codetitlesref);
                   15927:                 if ($jscript) {
                   15928:                     $jscript = '<script type="text/javascript">'."\n".
                   15929:                                '// <![CDATA['."\n".
                   15930:                                $jscript."\n".
                   15931:                                '// ]]>'."\n".
                   15932:                                '</script>'."\n";
                   15933:                 }
                   15934:             }
                   15935:             if ($instcodeform eq '') {
                   15936:                 $instcodeform =
                   15937:                     '<input type="text" name="instcodefilter" size="10" value="'.
                   15938:                     $list->{'instcodefilter'}.'" />';
                   15939:                 $instcodetitle = $lt{'ins'};
                   15940:             } else {
                   15941:                 $instcodetitle = $lt{'inc'};
                   15942:             }
                   15943:             if ($fixeddom) {
                   15944:                 $instcodetitle .= '<br />('.$codedom.')';
                   15945:             }
                   15946:         }
                   15947:     }
                   15948:     my $output = qq|
                   15949: <form method="post" name="filterpicker" action="$action">
                   15950: <input type="hidden" name="form" value="$formname" />
                   15951: |;
                   15952:     if ($formname eq 'modifycourse') {
                   15953:         $output .= '<input type="hidden" name="phase" value="courselist" />'."\n".
                   15954:                    '<input type="hidden" name="prevphase" value="'.
                   15955:                    $prevphase.'" />'."\n";
1.1075.2.82  raeburn  15956:     } elsif ($formname eq 'quotacheck') {
                   15957:         $output .= qq|
                   15958: <input type="hidden" name="sortby" value="" />
                   15959: <input type="hidden" name="sortorder" value="" />
                   15960: |;
                   15961:     } else {
1.1075.2.69  raeburn  15962:         my $name_input;
                   15963:         if ($cnameelement ne '') {
                   15964:             $name_input = '<input type="hidden" name="cnameelement" value="'.
                   15965:                           $cnameelement.'" />';
                   15966:         }
                   15967:         $output .= qq|
                   15968: <input type="hidden" name="cnumelement" value="$cnumelement" />
                   15969: <input type="hidden" name="cdomelement" value="$cdomelement" />
                   15970: $name_input
                   15971: $roleelement
                   15972: $multelement
                   15973: $typeelement
                   15974: |;
                   15975:         if ($formname eq 'portform') {
                   15976:             $output .= '<input type="hidden" name="setroles" value="'.$setroles.'" />'."\n";
                   15977:         }
                   15978:     }
                   15979:     if ($fixeddom) {
                   15980:         $output .= '<input type="hidden" name="fixeddom" value="'.$fixeddom.'" />'."\n";
                   15981:     }
                   15982:     $output .= "<br />\n".&Apache::lonhtmlcommon::start_pick_box();
                   15983:     if ($sincefilterform) {
                   15984:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cac'})
                   15985:                   .$sincefilterform
                   15986:                   .&Apache::lonhtmlcommon::row_closure();
                   15987:     }
                   15988:     if ($createdfilterform) {
                   15989:         $output .= &Apache::lonhtmlcommon::row_title($lt{'ccr'})
                   15990:                   .$createdfilterform
                   15991:                   .&Apache::lonhtmlcommon::row_closure();
                   15992:     }
                   15993:     if ($domainselectform) {
                   15994:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cdo'})
                   15995:                   .$domainselectform
                   15996:                   .&Apache::lonhtmlcommon::row_closure();
                   15997:     }
                   15998:     if ($typeselectform) {
                   15999:         if (($formname eq 'ccrs') || ($formname eq 'requestcrs')) {
                   16000:             $output .= $typeselectform;
                   16001:         } else {
                   16002:             $output .= &Apache::lonhtmlcommon::row_title($lt{'cog'})
                   16003:                       .$typeselectform
                   16004:                       .&Apache::lonhtmlcommon::row_closure();
                   16005:         }
                   16006:     }
                   16007:     if ($instcodeform) {
                   16008:         $output .= &Apache::lonhtmlcommon::row_title($instcodetitle)
                   16009:                   .$instcodeform
                   16010:                   .&Apache::lonhtmlcommon::row_closure();
                   16011:     }
                   16012:     if (exists($filter->{'ownerfilter'})) {
                   16013:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cow'}).
                   16014:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16015:                    '<input type="text" name="ownerfilter" size="20" value="'.
                   16016:                    $list->{'ownerfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16017:                    $ownerdomselectform.'</td></tr></table>'.
                   16018:                    &Apache::lonhtmlcommon::row_closure();
                   16019:     }
                   16020:     if (exists($filter->{'personfilter'})) {
                   16021:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cop'}).
                   16022:                    '<table><tr><td>'.&mt('Username').'<br />'.
                   16023:                    '<input type="text" name="personfilter" size="20" value="'.
                   16024:                    $list->{'personfilter'}.'" /></td><td>'.&mt('Domain').'<br />'.
                   16025:                    $persondomselectform.'</td></tr></table>'.
                   16026:                    &Apache::lonhtmlcommon::row_closure();
                   16027:     }
                   16028:     if (exists($filter->{'coursefilter'})) {
                   16029:         $output .= &Apache::lonhtmlcommon::row_title(&mt('LON-CAPA course ID'))
                   16030:                   .'<input type="text" name="coursefilter" size="25" value="'
                   16031:                   .$list->{'coursefilter'}.'" />'
                   16032:                   .&Apache::lonhtmlcommon::row_closure();
                   16033:     }
                   16034:     if ($cloneableonlyform) {
                   16035:         $output .= &Apache::lonhtmlcommon::row_title($cloneabletitle).
                   16036:                    $cloneableonlyform.&Apache::lonhtmlcommon::row_closure();
                   16037:     }
                   16038:     if (exists($filter->{'descriptfilter'})) {
                   16039:         $output .= &Apache::lonhtmlcommon::row_title($lt{'cde'})
                   16040:                   .'<input type="text" name="descriptfilter" size="40" value="'
                   16041:                   .$list->{'descriptfilter'}.'" />'
                   16042:                   .&Apache::lonhtmlcommon::row_closure(1);
                   16043:     }
                   16044:     $output .= &Apache::lonhtmlcommon::end_pick_box().'<p>'.$clonetext."\n".
                   16045:                '<input type="hidden" name="updater" value="" />'."\n".
                   16046:                '<input type="submit" name="gosearch" value="'.
                   16047:                &mt('Search').'" /></p>'."\n".'</form>'."\n".'<hr />'."\n";
                   16048:     return $jscript.$clonewarning.$output;
                   16049: }
                   16050: 
                   16051: =pod
                   16052: 
                   16053: =item * &timebased_select_form()
                   16054: 
                   16055: Create markup for a dropdown list used to select a time-based
                   16056: filter e.g., Course Activity, Course Created, when searching for courses
                   16057: or communities
                   16058: 
                   16059: Inputs:
                   16060: 
                   16061: item - name of form element (sincefilter or createdfilter)
                   16062: 
                   16063: filter - anonymous hash of criteria and their values
                   16064: 
                   16065: Returns: HTML for a select box contained a blank, then six time selections,
                   16066:          with value set in incoming form variables currently selected.
                   16067: 
                   16068: Side Effects: None
                   16069: 
                   16070: =cut
                   16071: 
                   16072: sub timebased_select_form {
                   16073:     my ($item,$filter) = @_;
                   16074:     if (ref($filter) eq 'HASH') {
                   16075:         $filter->{$item} =~ s/[^\d-]//g;
                   16076:         if (!$filter->{$item}) { $filter->{$item}=-1; }
                   16077:         return &select_form(
                   16078:                             $filter->{$item},
                   16079:                             $item,
                   16080:                             {      '-1' => '',
                   16081:                                 '86400' => &mt('today'),
                   16082:                                '604800' => &mt('last week'),
                   16083:                               '2592000' => &mt('last month'),
                   16084:                               '7776000' => &mt('last three months'),
                   16085:                              '15552000' => &mt('last six months'),
                   16086:                              '31104000' => &mt('last year'),
                   16087:                     'select_form_order' =>
                   16088:                            ['-1','86400','604800','2592000','7776000',
                   16089:                             '15552000','31104000']});
                   16090:     }
                   16091: }
                   16092: 
                   16093: =pod
                   16094: 
                   16095: =item * &js_changer()
                   16096: 
                   16097: Create script tag containing Javascript used to submit course search form
                   16098: when course type or domain is changed, and also to hide 'Searching ...' on
                   16099: page load completion for page showing search result.
                   16100: 
                   16101: Inputs: None
                   16102: 
                   16103: Returns: markup containing updateFilters() and hideSearching() javascript functions.
                   16104: 
                   16105: Side Effects: None
                   16106: 
                   16107: =cut
                   16108: 
                   16109: sub js_changer {
                   16110:     return <<ENDJS;
                   16111: <script type="text/javascript">
                   16112: // <![CDATA[
                   16113: function updateFilters(caller) {
                   16114:     if (typeof(caller) != "undefined") {
                   16115:         document.filterpicker.updater.value = caller.name;
                   16116:     }
                   16117:     document.filterpicker.submit();
                   16118: }
                   16119: 
                   16120: function hideSearching() {
                   16121:     if (document.getElementById('searching')) {
                   16122:         document.getElementById('searching').style.display = 'none';
                   16123:     }
                   16124:     return;
                   16125: }
                   16126: 
                   16127: // ]]>
                   16128: </script>
                   16129: 
                   16130: ENDJS
                   16131: }
                   16132: 
                   16133: =pod
                   16134: 
                   16135: =item * &search_courses()
                   16136: 
                   16137: Process selected filters form course search form and pass to lonnet::courseiddump
                   16138: to retrieve a hash for which keys are courseIDs which match the selected filters.
                   16139: 
                   16140: Inputs:
                   16141: 
                   16142: dom - domain being searched
                   16143: 
                   16144: type - course type ('Course' or 'Community' or '.' if any).
                   16145: 
                   16146: filter - anonymous hash of criteria and their values
                   16147: 
                   16148: numtitles - for institutional codes - number of categories
                   16149: 
                   16150: cloneruname - optional username of new course owner
                   16151: 
                   16152: clonerudom - optional domain of new course owner
                   16153: 
1.1075.2.95  raeburn  16154: domcloner - optional "domcloner" flag; has value=1 if user has ccc priv in domain being filtered by,
1.1075.2.69  raeburn  16155:             (used when DC is using course creation form)
                   16156: 
                   16157: codetitles - reference to array of titles of components in institutional codes (official courses).
                   16158: 
1.1075.2.95  raeburn  16159: cc_clone - escaped comma separated list of courses for which course cloner has active CC role
                   16160:            (and so can clone automatically)
                   16161: 
                   16162: reqcrsdom - domain of new course, where search_courses is used to identify potential courses to clone
                   16163: 
                   16164: reqinstcode - institutional code of new course, where search_courses is used to identify potential
                   16165:               courses to clone
1.1075.2.69  raeburn  16166: 
                   16167: Returns: %courses - hash of courses satisfying search criteria, keys = course IDs, values are corresponding colon-separated escaped description, institutional code, owner and type.
                   16168: 
                   16169: 
                   16170: Side Effects: None
                   16171: 
                   16172: =cut
                   16173: 
                   16174: 
                   16175: sub search_courses {
1.1075.2.95  raeburn  16176:     my ($dom,$type,$filter,$numtitles,$cloneruname,$clonerudom,$domcloner,$codetitles,
                   16177:         $cc_clone,$reqcrsdom,$reqinstcode) = @_;
1.1075.2.69  raeburn  16178:     my (%courses,%showcourses,$cloner);
                   16179:     if (($filter->{'ownerfilter'} ne '') ||
                   16180:         ($filter->{'ownerdomfilter'} ne '')) {
                   16181:         $filter->{'combownerfilter'} = $filter->{'ownerfilter'}.':'.
                   16182:                                        $filter->{'ownerdomfilter'};
                   16183:     }
                   16184:     foreach my $item ('descriptfilter','coursefilter','combownerfilter') {
                   16185:         if (!$filter->{$item}) {
                   16186:             $filter->{$item}='.';
                   16187:         }
                   16188:     }
                   16189:     my $now = time;
                   16190:     my $timefilter =
                   16191:        ($filter->{'sincefilter'}==-1?1:$now-$filter->{'sincefilter'});
                   16192:     my ($createdbefore,$createdafter);
                   16193:     if (($filter->{'createdfilter'} ne '') && ($filter->{'createdfilter'} !=-1)) {
                   16194:         $createdbefore = $now;
                   16195:         $createdafter = $now-$filter->{'createdfilter'};
                   16196:     }
                   16197:     my ($instcodefilter,$regexpok);
                   16198:     if ($numtitles) {
                   16199:         if ($env{'form.official'} eq 'on') {
                   16200:             $instcodefilter =
                   16201:                 &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16202:             $regexpok = 1;
                   16203:         } elsif ($env{'form.official'} eq 'off') {
                   16204:             $instcodefilter = &Apache::courseclassifier::instcode_search_str($dom,$numtitles,$codetitles);
                   16205:             unless ($instcodefilter eq '') {
                   16206:                 $regexpok = -1;
                   16207:             }
                   16208:         }
                   16209:     } else {
                   16210:         $instcodefilter = $filter->{'instcodefilter'};
                   16211:     }
                   16212:     if ($instcodefilter eq '') { $instcodefilter = '.'; }
                   16213:     if ($type eq '') { $type = '.'; }
                   16214: 
                   16215:     if (($clonerudom ne '') && ($cloneruname ne '')) {
                   16216:         $cloner = $cloneruname.':'.$clonerudom;
                   16217:     }
                   16218:     %courses = &Apache::lonnet::courseiddump($dom,
                   16219:                                              $filter->{'descriptfilter'},
                   16220:                                              $timefilter,
                   16221:                                              $instcodefilter,
                   16222:                                              $filter->{'combownerfilter'},
                   16223:                                              $filter->{'coursefilter'},
                   16224:                                              undef,undef,$type,$regexpok,undef,undef,
1.1075.2.95  raeburn  16225:                                              undef,undef,$cloner,$cc_clone,
1.1075.2.69  raeburn  16226:                                              $filter->{'cloneableonly'},
                   16227:                                              $createdbefore,$createdafter,undef,
1.1075.2.95  raeburn  16228:                                              $domcloner,undef,$reqcrsdom,$reqinstcode);
1.1075.2.69  raeburn  16229:     if (($filter->{'personfilter'} ne '') && ($filter->{'persondomfilter'} ne '')) {
                   16230:         my $ccrole;
                   16231:         if ($type eq 'Community') {
                   16232:             $ccrole = 'co';
                   16233:         } else {
                   16234:             $ccrole = 'cc';
                   16235:         }
                   16236:         my %rolehash = &Apache::lonnet::get_my_roles($filter->{'personfilter'},
                   16237:                                                      $filter->{'persondomfilter'},
                   16238:                                                      'userroles',undef,
                   16239:                                                      [$ccrole,'in','ad','ep','ta','cr'],
                   16240:                                                      $dom);
                   16241:         foreach my $role (keys(%rolehash)) {
                   16242:             my ($cnum,$cdom,$courserole) = split(':',$role);
                   16243:             my $cid = $cdom.'_'.$cnum;
                   16244:             if (exists($courses{$cid})) {
                   16245:                 if (ref($courses{$cid}) eq 'HASH') {
                   16246:                     if (ref($courses{$cid}{roles}) eq 'ARRAY') {
                   16247:                         if (!grep(/^\Q$courserole\E$/,@{$courses{$cid}{roles}})) {
1.1075.2.119  raeburn  16248:                             push(@{$courses{$cid}{roles}},$courserole);
1.1075.2.69  raeburn  16249:                         }
                   16250:                     } else {
                   16251:                         $courses{$cid}{roles} = [$courserole];
                   16252:                     }
                   16253:                     $showcourses{$cid} = $courses{$cid};
                   16254:                 }
                   16255:             }
                   16256:         }
                   16257:         %courses = %showcourses;
                   16258:     }
                   16259:     return %courses;
                   16260: }
                   16261: 
                   16262: =pod
                   16263: 
                   16264: =back
                   16265: 
1.1075.2.88  raeburn  16266: =head1 Routines for version requirements for current course.
                   16267: 
                   16268: =over 4
                   16269: 
                   16270: =item * &check_release_required()
                   16271: 
                   16272: Compares required LON-CAPA version with version on server, and
                   16273: if required version is newer looks for a server with the required version.
                   16274: 
                   16275: Looks first at servers in user's owen domain; if none suitable, looks at
                   16276: servers in course's domain are permitted to host sessions for user's domain.
                   16277: 
                   16278: Inputs:
                   16279: 
                   16280: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16281: 
                   16282: $courseid - Course ID of current course
                   16283: 
                   16284: $rolecode - User's current role in course (for switchserver query string).
                   16285: 
                   16286: $required - LON-CAPA version needed by course (format: Major.Minor).
                   16287: 
                   16288: 
                   16289: Returns:
                   16290: 
                   16291: $switchserver - query string tp append to /adm/switchserver call (if
                   16292:                 current server's LON-CAPA version is too old.
                   16293: 
                   16294: $warning - Message is displayed if no suitable server could be found.
                   16295: 
                   16296: =cut
                   16297: 
                   16298: sub check_release_required {
                   16299:     my ($loncaparev,$courseid,$rolecode,$required) = @_;
                   16300:     my ($switchserver,$warning);
                   16301:     if ($required ne '') {
                   16302:         my ($reqdmajor,$reqdminor) = ($required =~ /^(\d+)\.(\d+)$/);
                   16303:         my ($major,$minor) = ($loncaparev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16304:         if ($reqdmajor ne '' && $reqdminor ne '') {
                   16305:             my $otherserver;
                   16306:             if (($major eq '' && $minor eq '') ||
                   16307:                 (($reqdmajor > $major) || (($reqdmajor == $major) && ($reqdminor > $minor)))) {
                   16308:                 my ($userdomserver) = &Apache::lonnet::choose_server($env{'user.domain'},undef,$required,1);
                   16309:                 my $switchlcrev =
                   16310:                     &Apache::lonnet::get_server_loncaparev($env{'user.domain'},
                   16311:                                                            $userdomserver);
                   16312:                 my ($swmajor,$swminor) = ($switchlcrev =~ /^\'?(\d+)\.(\d+)\.[\w.\-]+\'?$/);
                   16313:                 if (($swmajor eq '' && $swminor eq '') || ($reqdmajor > $swmajor) ||
                   16314:                     (($reqdmajor == $swmajor) && ($reqdminor > $swminor))) {
                   16315:                     my $cdom = $env{'course.'.$courseid.'.domain'};
                   16316:                     if ($cdom ne $env{'user.domain'}) {
                   16317:                         my ($coursedomserver,$coursehostname) = &Apache::lonnet::choose_server($cdom,undef,$required,1);
                   16318:                         my $serverhomeID = &Apache::lonnet::get_server_homeID($coursehostname);
                   16319:                         my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16320:                         my %defdomdefaults = &Apache::lonnet::get_domain_defaults($serverhomedom);
                   16321:                         my %udomdefaults = &Apache::lonnet::get_domain_defaults($env{'user.domain'});
                   16322:                         my $remoterev = &Apache::lonnet::get_server_loncaparev($serverhomedom,$coursedomserver);
                   16323:                         my $canhost =
                   16324:                             &Apache::lonnet::can_host_session($env{'user.domain'},
                   16325:                                                               $coursedomserver,
                   16326:                                                               $remoterev,
                   16327:                                                               $udomdefaults{'remotesessions'},
                   16328:                                                               $defdomdefaults{'hostedsessions'});
                   16329: 
                   16330:                         if ($canhost) {
                   16331:                             $otherserver = $coursedomserver;
                   16332:                         } else {
                   16333:                             $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.");
                   16334:                         }
                   16335:                     } else {
                   16336:                         $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).");
                   16337:                     }
                   16338:                 } else {
                   16339:                     $otherserver = $userdomserver;
                   16340:                 }
                   16341:             }
                   16342:             if ($otherserver ne '') {
                   16343:                 $switchserver = 'otherserver='.$otherserver.'&amp;role='.$rolecode;
                   16344:             }
                   16345:         }
                   16346:     }
                   16347:     return ($switchserver,$warning);
                   16348: }
                   16349: 
                   16350: =pod
                   16351: 
                   16352: =item * &check_release_result()
                   16353: 
                   16354: Inputs:
                   16355: 
                   16356: $switchwarning - Warning message if no suitable server found to host session.
                   16357: 
                   16358: $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16359:                 and current role.
                   16360: 
                   16361: Returns: HTML to display with information about requirement to switch server.
                   16362:          Either displaying warning with link to Roles/Courses screen or
                   16363:          display link to switchserver.
                   16364: 
1.1075.2.69  raeburn  16365: =cut
                   16366: 
1.1075.2.88  raeburn  16367: sub check_release_result {
                   16368:     my ($switchwarning,$switchserver) = @_;
                   16369:     my $output = &start_page('Selected course unavailable on this server').
                   16370:                  '<p class="LC_warning">';
                   16371:     if ($switchwarning) {
                   16372:         $output .= $switchwarning.'<br /><a href="/adm/roles">';
                   16373:         if (&show_course()) {
                   16374:             $output .= &mt('Display courses');
                   16375:         } else {
                   16376:             $output .= &mt('Display roles');
                   16377:         }
                   16378:         $output .= '</a>';
                   16379:     } elsif ($switchserver) {
                   16380:         $output .= &mt('This course requires a newer version of LON-CAPA than is installed on this server.').
                   16381:                    '<br />'.
                   16382:                    '<a href="/adm/switchserver?'.$switchserver.'">'.
                   16383:                    &mt('Switch Server').
                   16384:                    '</a>';
                   16385:     }
                   16386:     $output .= '</p>'.&end_page();
                   16387:     return $output;
                   16388: }
                   16389: 
                   16390: =pod
                   16391: 
                   16392: =item * &needs_coursereinit()
                   16393: 
                   16394: Determine if course contents stored for user's session needs to be
                   16395: refreshed, because content has changed since "Big Hash" last tied.
                   16396: 
                   16397: Check for change is made if time last checked is more than 10 minutes ago
                   16398: (by default).
                   16399: 
                   16400: Inputs:
                   16401: 
                   16402: $loncaparev - Version on current server (format: Major.Minor.Subrelease-datestamp)
                   16403: 
                   16404: $interval (optional) - Time which may elapse (in s) between last check for content
                   16405:                        change in current course. (default: 600 s).
                   16406: 
                   16407: Returns: an array; first element is:
                   16408: 
                   16409: =over 4
                   16410: 
                   16411: 'switch' - if content updates mean user's session
                   16412:            needs to be switched to a server running a newer LON-CAPA version
                   16413: 
                   16414: 'update' - if course session needs to be refreshed (i.e., Big Hash needs to be reloaded)
                   16415:            on current server hosting user's session
                   16416: 
                   16417: ''       - if no action required.
                   16418: 
                   16419: =back
                   16420: 
                   16421: If first item element is 'switch':
                   16422: 
                   16423: second item is $switchwarning - Warning message if no suitable server found to host session.
                   16424: 
                   16425: third item is $switchserver - query string to append to /adm/switchserver containing lonHostID
                   16426:                               and current role.
                   16427: 
                   16428: otherwise: no other elements returned.
                   16429: 
                   16430: =back
                   16431: 
                   16432: =cut
                   16433: 
                   16434: sub needs_coursereinit {
                   16435:     my ($loncaparev,$interval) = @_;
                   16436:     return() unless ($env{'request.course.id'} && $env{'request.course.tied'});
                   16437:     my $cdom = $env{'course.'.$env{'request.course.id'}.'.domain'};
                   16438:     my $cnum = $env{'course.'.$env{'request.course.id'}.'.num'};
                   16439:     my $now = time;
                   16440:     if ($interval eq '') {
                   16441:         $interval = 600;
                   16442:     }
                   16443:     if (($now-$env{'request.course.timechecked'})>$interval) {
                   16444:         my $lastchange = &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16445:         &Apache::lonnet::appenv({'request.course.timechecked'=>$now});
                   16446:         if ($lastchange > $env{'request.course.tied'}) {
                   16447:             my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16448:             if ($curr_reqd_hash{'internal.releaserequired'} ne '') {
                   16449:                 my $required = $env{'course.'.$cdom.'_'.$cnum.'.internal.releaserequired'};
                   16450:                 if ($curr_reqd_hash{'internal.releaserequired'} ne $required) {
                   16451:                     &Apache::lonnet::appenv({'course.'.$cdom.'_'.$cnum.'.internal.releaserequired' =>
                   16452:                                              $curr_reqd_hash{'internal.releaserequired'}});
                   16453:                     my ($switchserver,$switchwarning) =
                   16454:                         &check_release_required($loncaparev,$cdom.'_'.$cnum,$env{'request.role'},
                   16455:                                                 $curr_reqd_hash{'internal.releaserequired'});
                   16456:                     if ($switchwarning ne '' || $switchserver ne '') {
                   16457:                         return ('switch',$switchwarning,$switchserver);
                   16458:                     }
                   16459:                 }
                   16460:             }
                   16461:             return ('update');
                   16462:         }
                   16463:     }
                   16464:     return ();
                   16465: }
1.1075.2.69  raeburn  16466: 
1.1075.2.11  raeburn  16467: sub update_content_constraints {
                   16468:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16469:     my %curr_reqd_hash = &Apache::lonnet::userenvironment($cdom,$cnum,'internal.releaserequired');
                   16470:     my ($reqdmajor,$reqdminor) = split(/\./,$curr_reqd_hash{'internal.releaserequired'});
                   16471:     my %checkresponsetypes;
                   16472:     foreach my $key (keys(%Apache::lonnet::needsrelease)) {
                   16473:         my ($item,$name,$value) = split(/:/,$key);
                   16474:         if ($item eq 'resourcetag') {
                   16475:             if ($name eq 'responsetype') {
                   16476:                 $checkresponsetypes{$value} = $Apache::lonnet::needsrelease{$key}
                   16477:             }
                   16478:         }
                   16479:     }
                   16480:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16481:     if (defined($navmap)) {
                   16482:         my %allresponses;
                   16483:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_problem() },1,0)) {
                   16484:             my %responses = $res->responseTypes();
                   16485:             foreach my $key (keys(%responses)) {
                   16486:                 next unless(exists($checkresponsetypes{$key}));
                   16487:                 $allresponses{$key} += $responses{$key};
                   16488:             }
                   16489:         }
                   16490:         foreach my $key (keys(%allresponses)) {
                   16491:             my ($major,$minor) = split(/\./,$checkresponsetypes{$key});
                   16492:             if (($major > $reqdmajor) || ($major == $reqdmajor && $minor > $reqdminor)) {
                   16493:                 ($reqdmajor,$reqdminor) = ($major,$minor);
                   16494:             }
                   16495:         }
                   16496:         undef($navmap);
                   16497:     }
                   16498:     unless (($reqdmajor eq '') && ($reqdminor eq '')) {
                   16499:         &Apache::lonnet::update_released_required($reqdmajor.'.'.$reqdminor,$cdom,$cnum,$chome,$cid);
                   16500:     }
                   16501:     return;
                   16502: }
                   16503: 
1.1075.2.27  raeburn  16504: sub allmaps_incourse {
                   16505:     my ($cdom,$cnum,$chome,$cid) = @_;
                   16506:     if ($cdom eq '' || $cnum eq '' || $chome eq '' || $cid eq '') {
                   16507:         $cid = $env{'request.course.id'};
                   16508:         $cdom = $env{'course.'.$cid.'.domain'};
                   16509:         $cnum = $env{'course.'.$cid.'.num'};
                   16510:         $chome = $env{'course.'.$cid.'.home'};
                   16511:     }
                   16512:     my %allmaps = ();
                   16513:     my $lastchange =
                   16514:         &Apache::lonnet::get_coursechange($cdom,$cnum);
                   16515:     if ($lastchange > $env{'request.course.tied'}) {
                   16516:         my ($furl,$ferr) = &Apache::lonuserstate::readmap("$cdom/$cnum");
                   16517:         unless ($ferr) {
                   16518:             &update_content_constraints($cdom,$cnum,$chome,$cid);
                   16519:         }
                   16520:     }
                   16521:     my $navmap = Apache::lonnavmaps::navmap->new();
                   16522:     if (defined($navmap)) {
                   16523:         foreach my $res ($navmap->retrieveResources(undef,sub { $_[0]->is_map() },1,0,1)) {
                   16524:             $allmaps{$res->src()} = 1;
                   16525:         }
                   16526:     }
                   16527:     return \%allmaps;
                   16528: }
                   16529: 
1.1075.2.11  raeburn  16530: sub parse_supplemental_title {
                   16531:     my ($title) = @_;
                   16532: 
                   16533:     my ($foldertitle,$renametitle);
                   16534:     if ($title =~ /&amp;&amp;&amp;/) {
                   16535:         $title = &HTML::Entites::decode($title);
                   16536:     }
                   16537:     if ($title =~ m/^(\d+)___&&&___($match_username)___&&&___($match_domain)___&&&___(.*)$/) {
                   16538:         $renametitle=$4;
                   16539:         my ($time,$uname,$udom) = ($1,$2,$3);
                   16540:         $foldertitle=&Apache::lontexconvert::msgtexconverted($4);
                   16541:         my $name =  &plainname($uname,$udom);
                   16542:         $name = &HTML::Entities::encode($name,'"<>&\'');
                   16543:         $renametitle = &HTML::Entities::encode($renametitle,'"<>&\'');
                   16544:         $title='<i>'.&Apache::lonlocal::locallocaltime($time).'</i> '.
                   16545:             $name.': <br />'.$foldertitle;
                   16546:     }
                   16547:     if (wantarray) {
                   16548:         return ($title,$foldertitle,$renametitle);
                   16549:     }
                   16550:     return $title;
                   16551: }
                   16552: 
1.1075.2.43  raeburn  16553: sub recurse_supplemental {
                   16554:     my ($cnum,$cdom,$suppmap,$numfiles,$errors) = @_;
                   16555:     if ($suppmap) {
                   16556:         my ($errtext,$fatal) = &LONCAPA::map::mapread('/uploaded/'.$cdom.'/'.$cnum.'/'.$suppmap);
                   16557:         if ($fatal) {
                   16558:             $errors ++;
                   16559:         } else {
                   16560:             if ($#LONCAPA::map::resources > 0) {
                   16561:                 foreach my $res (@LONCAPA::map::resources) {
                   16562:                     my ($title,$src,$ext,$type,$status)=split(/\:/,$res);
                   16563:                     if (($src ne '') && ($status eq 'res')) {
1.1075.2.46  raeburn  16564:                         if ($src =~ m{^\Q/uploaded/$cdom/$cnum/\E(supplemental_\d+\.sequence)$}) {
                   16565:                             ($numfiles,$errors) = &recurse_supplemental($cnum,$cdom,$1,$numfiles,$errors);
1.1075.2.43  raeburn  16566:                         } else {
                   16567:                             $numfiles ++;
                   16568:                         }
                   16569:                     }
                   16570:                 }
                   16571:             }
                   16572:         }
                   16573:     }
                   16574:     return ($numfiles,$errors);
                   16575: }
                   16576: 
1.1075.2.18  raeburn  16577: sub symb_to_docspath {
1.1075.2.119  raeburn  16578:     my ($symb,$navmapref) = @_;
                   16579:     return unless ($symb && ref($navmapref));
1.1075.2.18  raeburn  16580:     my ($mapurl,$id,$resurl) = &Apache::lonnet::decode_symb($symb);
                   16581:     if ($resurl=~/\.(sequence|page)$/) {
                   16582:         $mapurl=$resurl;
                   16583:     } elsif ($resurl eq 'adm/navmaps') {
                   16584:         $mapurl=$env{'course.'.$env{'request.course.id'}.'.url'};
                   16585:     }
                   16586:     my $mapresobj;
1.1075.2.119  raeburn  16587:     unless (ref($$navmapref)) {
                   16588:         $$navmapref = Apache::lonnavmaps::navmap->new();
                   16589:     }
                   16590:     if (ref($$navmapref)) {
                   16591:         $mapresobj = $$navmapref->getResourceByUrl($mapurl);
1.1075.2.18  raeburn  16592:     }
                   16593:     $mapurl=~s{^.*/([^/]+)\.(\w+)$}{$1};
                   16594:     my $type=$2;
                   16595:     my $path;
                   16596:     if (ref($mapresobj)) {
                   16597:         my $pcslist = $mapresobj->map_hierarchy();
                   16598:         if ($pcslist ne '') {
                   16599:             foreach my $pc (split(/,/,$pcslist)) {
                   16600:                 next if ($pc <= 1);
1.1075.2.119  raeburn  16601:                 my $res = $$navmapref->getByMapPc($pc);
1.1075.2.18  raeburn  16602:                 if (ref($res)) {
                   16603:                     my $thisurl = $res->src();
                   16604:                     $thisurl=~s{^.*/([^/]+)\.\w+$}{$1};
                   16605:                     my $thistitle = $res->title();
                   16606:                     $path .= '&'.
                   16607:                              &Apache::lonhtmlcommon::entity_encode($thisurl).'&'.
1.1075.2.46  raeburn  16608:                              &escape($thistitle).
1.1075.2.18  raeburn  16609:                              ':'.$res->randompick().
                   16610:                              ':'.$res->randomout().
                   16611:                              ':'.$res->encrypted().
                   16612:                              ':'.$res->randomorder().
                   16613:                              ':'.$res->is_page();
                   16614:                 }
                   16615:             }
                   16616:         }
                   16617:         $path =~ s/^\&//;
                   16618:         my $maptitle = $mapresobj->title();
                   16619:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16620:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16621:         }
                   16622:         $path .= (($path ne '')? '&' : '').
                   16623:                  &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16624:                  &escape($maptitle).
1.1075.2.18  raeburn  16625:                  ':'.$mapresobj->randompick().
                   16626:                  ':'.$mapresobj->randomout().
                   16627:                  ':'.$mapresobj->encrypted().
                   16628:                  ':'.$mapresobj->randomorder().
                   16629:                  ':'.$mapresobj->is_page();
                   16630:     } else {
                   16631:         my $maptitle = &Apache::lonnet::gettitle($mapurl);
                   16632:         my $ispage = (($type eq 'page')? 1 : '');
                   16633:         if ($mapurl eq 'default') {
1.1075.2.38  raeburn  16634:             $maptitle = 'Main Content';
1.1075.2.18  raeburn  16635:         }
                   16636:         $path = &Apache::lonhtmlcommon::entity_encode($mapurl).'&'.
1.1075.2.46  raeburn  16637:                 &escape($maptitle).':::::'.$ispage;
1.1075.2.18  raeburn  16638:     }
                   16639:     unless ($mapurl eq 'default') {
                   16640:         $path = 'default&'.
1.1075.2.46  raeburn  16641:                 &escape('Main Content').
1.1075.2.18  raeburn  16642:                 ':::::&'.$path;
                   16643:     }
                   16644:     return $path;
                   16645: }
                   16646: 
1.1075.2.14  raeburn  16647: sub captcha_display {
                   16648:     my ($context,$lonhost) = @_;
                   16649:     my ($output,$error);
1.1075.2.107  raeburn  16650:     my ($captcha,$pubkey,$privkey,$version) =
                   16651:         &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16652:     if ($captcha eq 'original') {
                   16653:         $output = &create_captcha();
                   16654:         unless ($output) {
                   16655:             $error = 'captcha';
                   16656:         }
                   16657:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16658:         $output = &create_recaptcha($pubkey,$version);
1.1075.2.14  raeburn  16659:         unless ($output) {
                   16660:             $error = 'recaptcha';
                   16661:         }
                   16662:     }
1.1075.2.107  raeburn  16663:     return ($output,$error,$captcha,$version);
1.1075.2.14  raeburn  16664: }
                   16665: 
                   16666: sub captcha_response {
                   16667:     my ($context,$lonhost) = @_;
                   16668:     my ($captcha_chk,$captcha_error);
1.1075.2.109  raeburn  16669:     my ($captcha,$pubkey,$privkey,$version) = &get_captcha_config($context,$lonhost);
1.1075.2.14  raeburn  16670:     if ($captcha eq 'original') {
                   16671:         ($captcha_chk,$captcha_error) = &check_captcha();
                   16672:     } elsif ($captcha eq 'recaptcha') {
1.1075.2.107  raeburn  16673:         $captcha_chk = &check_recaptcha($privkey,$version);
1.1075.2.14  raeburn  16674:     } else {
                   16675:         $captcha_chk = 1;
                   16676:     }
                   16677:     return ($captcha_chk,$captcha_error);
                   16678: }
                   16679: 
                   16680: sub get_captcha_config {
                   16681:     my ($context,$lonhost) = @_;
1.1075.2.107  raeburn  16682:     my ($captcha,$pubkey,$privkey,$version,$hashtocheck);
1.1075.2.14  raeburn  16683:     my $hostname = &Apache::lonnet::hostname($lonhost);
                   16684:     my $serverhomeID = &Apache::lonnet::get_server_homeID($hostname);
                   16685:     my $serverhomedom = &Apache::lonnet::host_domain($serverhomeID);
                   16686:     if ($context eq 'usercreation') {
                   16687:         my %domconfig = &Apache::lonnet::get_dom('configuration',[$context],$serverhomedom);
                   16688:         if (ref($domconfig{$context}) eq 'HASH') {
                   16689:             $hashtocheck = $domconfig{$context}{'cancreate'};
                   16690:             if (ref($hashtocheck) eq 'HASH') {
                   16691:                 if ($hashtocheck->{'captcha'} eq 'recaptcha') {
                   16692:                     if (ref($hashtocheck->{'recaptchakeys'}) eq 'HASH') {
                   16693:                         $pubkey = $hashtocheck->{'recaptchakeys'}{'public'};
                   16694:                         $privkey = $hashtocheck->{'recaptchakeys'}{'private'};
                   16695:                     }
                   16696:                     if ($privkey && $pubkey) {
                   16697:                         $captcha = 'recaptcha';
1.1075.2.107  raeburn  16698:                         $version = $hashtocheck->{'recaptchaversion'};
                   16699:                         if ($version ne '2') {
                   16700:                             $version = 1;
                   16701:                         }
1.1075.2.14  raeburn  16702:                     } else {
                   16703:                         $captcha = 'original';
                   16704:                     }
                   16705:                 } elsif ($hashtocheck->{'captcha'} ne 'notused') {
                   16706:                     $captcha = 'original';
                   16707:                 }
                   16708:             }
                   16709:         } else {
                   16710:             $captcha = 'captcha';
                   16711:         }
                   16712:     } elsif ($context eq 'login') {
                   16713:         my %domconfhash = &Apache::loncommon::get_domainconf($serverhomedom);
                   16714:         if ($domconfhash{$serverhomedom.'.login.captcha'} eq 'recaptcha') {
                   16715:             $pubkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_public'};
                   16716:             $privkey = $domconfhash{$serverhomedom.'.login.recaptchakeys_private'};
                   16717:             if ($privkey && $pubkey) {
                   16718:                 $captcha = 'recaptcha';
1.1075.2.107  raeburn  16719:                 $version = $domconfhash{$serverhomedom.'.login.recaptchaversion'};
                   16720:                 if ($version ne '2') {
                   16721:                     $version = 1;
                   16722:                 }
1.1075.2.14  raeburn  16723:             } else {
                   16724:                 $captcha = 'original';
                   16725:             }
                   16726:         } elsif ($domconfhash{$serverhomedom.'.login.captcha'} eq 'original') {
                   16727:             $captcha = 'original';
                   16728:         }
                   16729:     }
1.1075.2.107  raeburn  16730:     return ($captcha,$pubkey,$privkey,$version);
1.1075.2.14  raeburn  16731: }
                   16732: 
                   16733: sub create_captcha {
                   16734:     my %captcha_params = &captcha_settings();
                   16735:     my ($output,$maxtries,$tries) = ('',10,0);
                   16736:     while ($tries < $maxtries) {
                   16737:         $tries ++;
                   16738:         my $captcha = Authen::Captcha->new (
                   16739:                                            output_folder => $captcha_params{'output_dir'},
                   16740:                                            data_folder   => $captcha_params{'db_dir'},
                   16741:                                           );
                   16742:         my $md5sum = $captcha->generate_code($captcha_params{'numchars'});
                   16743: 
                   16744:         if (-e $Apache::lonnet::perlvar{'lonCaptchaDir'}.'/'.$md5sum.'.png') {
                   16745:             $output = '<input type="hidden" name="crypt" value="'.$md5sum.'" />'."\n".
                   16746:                       &mt('Type in the letters/numbers shown below').'&nbsp;'.
1.1075.2.66  raeburn  16747:                       '<input type="text" size="5" name="code" value="" autocomplete="off" />'.
                   16748:                       '<br />'.
                   16749:                       '<img src="'.$captcha_params{'www_output_dir'}.'/'.$md5sum.'.png" alt="captcha" />';
1.1075.2.14  raeburn  16750:             last;
                   16751:         }
                   16752:     }
                   16753:     return $output;
                   16754: }
                   16755: 
                   16756: sub captcha_settings {
                   16757:     my %captcha_params = (
                   16758:                            output_dir     => $Apache::lonnet::perlvar{'lonCaptchaDir'},
                   16759:                            www_output_dir => "/captchaspool",
                   16760:                            db_dir         => $Apache::lonnet::perlvar{'lonCaptchaDb'},
                   16761:                            numchars       => '5',
                   16762:                          );
                   16763:     return %captcha_params;
                   16764: }
                   16765: 
                   16766: sub check_captcha {
                   16767:     my ($captcha_chk,$captcha_error);
                   16768:     my $code = $env{'form.code'};
                   16769:     my $md5sum = $env{'form.crypt'};
                   16770:     my %captcha_params = &captcha_settings();
                   16771:     my $captcha = Authen::Captcha->new(
                   16772:                       output_folder => $captcha_params{'output_dir'},
                   16773:                       data_folder   => $captcha_params{'db_dir'},
                   16774:                   );
1.1075.2.26  raeburn  16775:     $captcha_chk = $captcha->check_code($code,$md5sum);
1.1075.2.14  raeburn  16776:     my %captcha_hash = (
                   16777:                         0       => 'Code not checked (file error)',
                   16778:                        -1      => 'Failed: code expired',
                   16779:                        -2      => 'Failed: invalid code (not in database)',
                   16780:                        -3      => 'Failed: invalid code (code does not match crypt)',
                   16781:     );
                   16782:     if ($captcha_chk != 1) {
                   16783:         $captcha_error = $captcha_hash{$captcha_chk}
                   16784:     }
                   16785:     return ($captcha_chk,$captcha_error);
                   16786: }
                   16787: 
                   16788: sub create_recaptcha {
1.1075.2.107  raeburn  16789:     my ($pubkey,$version) = @_;
                   16790:     if ($version >= 2) {
                   16791:         return '<div class="g-recaptcha" data-sitekey="'.$pubkey.'"></div>';
                   16792:     } else {
                   16793:         my $use_ssl;
                   16794:         if ($ENV{'SERVER_PORT'} == 443) {
                   16795:             $use_ssl = 1;
                   16796:         }
                   16797:         my $captcha = Captcha::reCAPTCHA->new;
                   16798:         return $captcha->get_options_setter({theme => 'white'})."\n".
                   16799:                $captcha->get_html($pubkey,undef,$use_ssl).
                   16800:                &mt('If the text is hard to read, [_1] will replace them.',
                   16801:                    '<img src="/res/adm/pages/refresh.gif" alt="reCAPTCHA refresh" />').
                   16802:                '<br /><br />';
                   16803:      }
1.1075.2.14  raeburn  16804: }
                   16805: 
                   16806: sub check_recaptcha {
1.1075.2.107  raeburn  16807:     my ($privkey,$version) = @_;
1.1075.2.14  raeburn  16808:     my $captcha_chk;
1.1075.2.107  raeburn  16809:     if ($version >= 2) {
                   16810:         my $ua = LWP::UserAgent->new;
                   16811:         $ua->timeout(10);
                   16812:         my %info = (
                   16813:                      secret   => $privkey,
                   16814:                      response => $env{'form.g-recaptcha-response'},
                   16815:                      remoteip => $ENV{'REMOTE_ADDR'},
                   16816:                    );
                   16817:         my $response = $ua->post('https://www.google.com/recaptcha/api/siteverify',\%info);
                   16818:         if ($response->is_success)  {
                   16819:             my $data = JSON::DWIW->from_json($response->decoded_content);
                   16820:             if (ref($data) eq 'HASH') {
                   16821:                 if ($data->{'success'}) {
                   16822:                     $captcha_chk = 1;
                   16823:                 }
                   16824:             }
                   16825:         }
                   16826:     } else {
                   16827:         my $captcha = Captcha::reCAPTCHA->new;
                   16828:         my $captcha_result =
                   16829:             $captcha->check_answer(
                   16830:                                     $privkey,
                   16831:                                     $ENV{'REMOTE_ADDR'},
                   16832:                                     $env{'form.recaptcha_challenge_field'},
                   16833:                                     $env{'form.recaptcha_response_field'},
                   16834:                                   );
                   16835:         if ($captcha_result->{is_valid}) {
                   16836:             $captcha_chk = 1;
                   16837:         }
1.1075.2.14  raeburn  16838:     }
                   16839:     return $captcha_chk;
                   16840: }
                   16841: 
1.1075.2.64  raeburn  16842: sub emailusername_info {
1.1075.2.103  raeburn  16843:     my @fields = ('firstname','lastname','institution','web','location','officialemail','id');
1.1075.2.64  raeburn  16844:     my %titles = &Apache::lonlocal::texthash (
                   16845:                      lastname      => 'Last Name',
                   16846:                      firstname     => 'First Name',
                   16847:                      institution   => 'School/college/university',
                   16848:                      location      => "School's city, state/province, country",
                   16849:                      web           => "School's web address",
                   16850:                      officialemail => 'E-mail address at institution (if different)',
1.1075.2.103  raeburn  16851:                      id            => 'Student/Employee ID',
1.1075.2.64  raeburn  16852:                  );
                   16853:     return (\@fields,\%titles);
                   16854: }
                   16855: 
1.1075.2.56  raeburn  16856: sub cleanup_html {
                   16857:     my ($incoming) = @_;
                   16858:     my $outgoing;
                   16859:     if ($incoming ne '') {
                   16860:         $outgoing = $incoming;
                   16861:         $outgoing =~ s/;/&#059;/g;
                   16862:         $outgoing =~ s/\#/&#035;/g;
                   16863:         $outgoing =~ s/\&/&#038;/g;
                   16864:         $outgoing =~ s/</&#060;/g;
                   16865:         $outgoing =~ s/>/&#062;/g;
                   16866:         $outgoing =~ s/\(/&#040/g;
                   16867:         $outgoing =~ s/\)/&#041;/g;
                   16868:         $outgoing =~ s/"/&#034;/g;
                   16869:         $outgoing =~ s/'/&#039;/g;
                   16870:         $outgoing =~ s/\$/&#036;/g;
                   16871:         $outgoing =~ s{/}{&#047;}g;
                   16872:         $outgoing =~ s/=/&#061;/g;
                   16873:         $outgoing =~ s/\\/&#092;/g
                   16874:     }
                   16875:     return $outgoing;
                   16876: }
                   16877: 
1.1075.2.74  raeburn  16878: # Checks for critical messages and returns a redirect url if one exists.
                   16879: # $interval indicates how often to check for messages.
                   16880: sub critical_redirect {
                   16881:     my ($interval) = @_;
                   16882:     if ((time-$env{'user.criticalcheck.time'})>$interval) {
                   16883:         my @what=&Apache::lonnet::dump('critical', $env{'user.domain'},
                   16884:                                         $env{'user.name'});
                   16885:         &Apache::lonnet::appenv({'user.criticalcheck.time'=>time});
                   16886:         my $redirecturl;
                   16887:         if ($what[0]) {
                   16888:             if (($what[0] ne 'con_lost') && ($what[0]!~/^error\:/)) {
                   16889:                 $redirecturl='/adm/email?critical=display';
                   16890:                 my $url=&Apache::lonnet::absolute_url().$redirecturl;
                   16891:                 return (1, $url);
                   16892:             }
                   16893:         }
                   16894:     }
                   16895:     return ();
                   16896: }
                   16897: 
1.1075.2.64  raeburn  16898: # Use:
                   16899: #   my $answer=reply("encrypt:passwd:$udom:$uname:$upass",$tryserver);
                   16900: #
                   16901: ##################################################
                   16902: #          password associated functions         #
                   16903: ##################################################
                   16904: sub des_keys {
                   16905:     # Make a new key for DES encryption.
                   16906:     # Each key has two parts which are returned separately.
                   16907:     # Please note:  Each key must be passed through the &hex function
                   16908:     # before it is output to the web browser.  The hex versions cannot
                   16909:     # be used to decrypt.
                   16910:     my @hexstr=('0','1','2','3','4','5','6','7',
                   16911:                 '8','9','a','b','c','d','e','f');
                   16912:     my $lkey='';
                   16913:     for (0..7) {
                   16914:         $lkey.=$hexstr[rand(15)];
                   16915:     }
                   16916:     my $ukey='';
                   16917:     for (0..7) {
                   16918:         $ukey.=$hexstr[rand(15)];
                   16919:     }
                   16920:     return ($lkey,$ukey);
                   16921: }
                   16922: 
                   16923: sub des_decrypt {
                   16924:     my ($key,$cyphertext) = @_;
                   16925:     my $keybin=pack("H16",$key);
                   16926:     my $cypher;
                   16927:     if ($Crypt::DES::VERSION>=2.03) {
                   16928:         $cypher=new Crypt::DES $keybin;
                   16929:     } else {
                   16930:         $cypher=new DES $keybin;
                   16931:     }
1.1075.2.106  raeburn  16932:     my $plaintext='';
                   16933:     my $cypherlength = length($cyphertext);
                   16934:     my $numchunks = int($cypherlength/32);
                   16935:     for (my $j=0; $j<$numchunks; $j++) {
                   16936:         my $start = $j*32;
                   16937:         my $cypherblock = substr($cyphertext,$start,32);
                   16938:         my $chunk =
                   16939:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,0,16))));
                   16940:         $chunk .=
                   16941:             $cypher->decrypt(unpack("a8",pack("H16",substr($cypherblock,16,16))));
                   16942:         $chunk=substr($chunk,1,ord(substr($chunk,0,1)) );
                   16943:         $plaintext .= $chunk;
                   16944:     }
1.1075.2.64  raeburn  16945:     return $plaintext;
                   16946: }
                   16947: 
1.112     bowersj2 16948: 1;
                   16949: __END__;
1.41      ng       16950: 

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